org.el (org-priority): Don't use `org-preserve-lc'
[org-mode.git] / lisp / org.el
bloba225bae005dc3e7847fd5b5629d03a54155991bd
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 (load "org-loaddefs.el" t t t)
82 (require 'org-macs)
83 (require 'org-compat)
85 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
86 ;; some places -- e.g. see the macro `org-with-limited-levels'.
88 ;; In Org buffers, the value of `outline-regexp' is that of
89 ;; `org-outline-regexp'. The only function still directly relying on
90 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
91 ;; job when `orgstruct-mode' is active.
92 (defvar org-outline-regexp "\\*+ "
93 "Regexp to match Org headlines.")
95 (defvar org-outline-regexp-bol "^\\*+ "
96 "Regexp to match Org headlines.
97 This is similar to `org-outline-regexp' but additionally makes
98 sure that we are at the beginning of the line.")
100 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
101 "Matches a headline, putting stars and text into groups.
102 Stars are put in group 1 and the trimmed body in group 2.")
104 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (org-defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (org-defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-clocktable-shift "org-clock" (dir n))
119 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
120 (declare-function org-clock-update-time-maybe "org-clock" ())
121 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
122 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
123 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
124 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
127 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
128 (declare-function orgtbl-mode "org-table" (&optional arg))
129 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
130 (declare-function org-beamer-mode "ox-beamer" ())
131 (declare-function org-table-blank-field "org-table" ())
132 (declare-function org-table-edit-field "org-table" (arg))
133 (declare-function org-table-insert-row "org-table" (&optional arg))
134 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
135 (declare-function org-table-set-constants "org-table" ())
136 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
137 (declare-function org-id-get-create "org-id" (&optional force))
138 (declare-function org-add-archive-files "org-archive" (files))
139 (declare-function org-id-find-id-file "org-id" (id))
140 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
141 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
142 (declare-function org-agenda-redo "org-agenda" (&optional all))
143 (declare-function org-table-align "org-table" ())
144 (declare-function org-table-begin "org-table" (&optional table-type))
145 (declare-function org-table-end "org-table" (&optional table-type))
146 (declare-function org-table-paste-rectangle "org-table" ())
147 (declare-function org-table-maybe-eval-formula "org-table" ())
148 (declare-function org-table-maybe-recalculate-line "org-table" ())
150 (declare-function org-element--parse-objects "org-element"
151 (beg end acc restriction))
152 (declare-function org-element-at-point "org-element" ())
153 (declare-function org-element-cache-reset "org-element" (&optional all))
154 (declare-function org-element-contents "org-element" (element))
155 (declare-function org-element-context "org-element" (&optional element))
156 (declare-function org-element-interpret-data "org-element"
157 (data &optional parent))
158 (declare-function org-element-map "org-element"
159 (data types fun &optional info first-match no-recursion))
160 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
161 (declare-function org-element-parse-buffer "org-element"
162 (&optional granularity visible-only))
163 (declare-function org-element-property "org-element" (property element))
164 (declare-function org-element-put-property "org-element"
165 (element property value))
166 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
167 (declare-function org-element--parse-objects "org-element"
168 (beg end acc restriction))
169 (declare-function org-element-parse-buffer "org-element"
170 (&optional granularity visible-only))
171 (declare-function org-element-restriction "org-element" (element))
172 (declare-function org-element-type "org-element" (element))
174 (defsubst org-uniquify (list)
175 "Non-destructively remove duplicate elements from LIST."
176 (let ((res (copy-sequence list))) (delete-dups res)))
178 ;; load languages based on value of `org-babel-load-languages'
179 (defvar org-babel-load-languages)
181 ;;;###autoload
182 (defun org-babel-do-load-languages (sym value)
183 "Load the languages defined in `org-babel-load-languages'."
184 (set-default sym value)
185 (mapc (lambda (pair)
186 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
187 (if active
188 (progn
189 (require (intern (concat "ob-" lang))))
190 (progn
191 (funcall 'fmakunbound
192 (intern (concat "org-babel-execute:" lang)))
193 (funcall 'fmakunbound
194 (intern (concat "org-babel-expand-body:" lang)))))))
195 org-babel-load-languages))
197 ;;;###autoload
198 (defun org-babel-load-file (file &optional compile)
199 "Load Emacs Lisp source code blocks in the Org-mode FILE.
200 This function exports the source code using `org-babel-tangle'
201 and then loads the resulting file using `load-file'. With prefix
202 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
203 file to byte-code before it is loaded."
204 (interactive "fFile to load: \nP")
205 (let* ((age (lambda (file)
206 (float-time
207 (time-subtract (current-time)
208 (nth 5 (or (file-attributes (file-truename file))
209 (file-attributes file)))))))
210 (base-name (file-name-sans-extension file))
211 (exported-file (concat base-name ".el")))
212 ;; tangle if the org-mode file is newer than the elisp file
213 (unless (and (file-exists-p exported-file)
214 (> (funcall age file) (funcall age exported-file)))
215 (setq exported-file
216 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
217 (message "%s %s"
218 (if compile
219 (progn (byte-compile-file exported-file 'load)
220 "Compiled and loaded")
221 (progn (load-file exported-file) "Loaded"))
222 exported-file)))
224 (defcustom org-babel-load-languages '((emacs-lisp . t))
225 "Languages which can be evaluated in Org-mode buffers.
226 This list can be used to load support for any of the languages
227 below, note that each language will depend on a different set of
228 system executables and/or Emacs modes. When a language is
229 \"loaded\", then code blocks in that language can be evaluated
230 with `org-babel-execute-src-block' bound by default to C-c
231 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
232 be set to remove code block evaluation from the C-c C-c
233 keybinding. By default only Emacs Lisp (which has no
234 requirements) is loaded."
235 :group 'org-babel
236 :set 'org-babel-do-load-languages
237 :version "24.1"
238 :type '(alist :tag "Babel Languages"
239 :key-type
240 (choice
241 (const :tag "Awk" awk)
242 (const :tag "C" C)
243 (const :tag "R" R)
244 (const :tag "Asymptote" asymptote)
245 (const :tag "Calc" calc)
246 (const :tag "Clojure" clojure)
247 (const :tag "CSS" css)
248 (const :tag "Ditaa" ditaa)
249 (const :tag "Dot" dot)
250 (const :tag "Emacs Lisp" emacs-lisp)
251 (const :tag "Fortran" fortran)
252 (const :tag "Gnuplot" gnuplot)
253 (const :tag "Haskell" haskell)
254 (const :tag "IO" io)
255 (const :tag "J" J)
256 (const :tag "Java" java)
257 (const :tag "Javascript" js)
258 (const :tag "LaTeX" latex)
259 (const :tag "Ledger" ledger)
260 (const :tag "Lilypond" lilypond)
261 (const :tag "Lisp" lisp)
262 (const :tag "Makefile" makefile)
263 (const :tag "Maxima" maxima)
264 (const :tag "Matlab" matlab)
265 (const :tag "Mscgen" mscgen)
266 (const :tag "Ocaml" ocaml)
267 (const :tag "Octave" octave)
268 (const :tag "Org" org)
269 (const :tag "Perl" perl)
270 (const :tag "Pico Lisp" picolisp)
271 (const :tag "PlantUML" plantuml)
272 (const :tag "Python" python)
273 (const :tag "Ruby" ruby)
274 (const :tag "Sass" sass)
275 (const :tag "Scala" scala)
276 (const :tag "Scheme" scheme)
277 (const :tag "Screen" screen)
278 (const :tag "Shell Script" sh)
279 (const :tag "Shen" shen)
280 (const :tag "Sql" sql)
281 (const :tag "Sqlite" sqlite)
282 (const :tag "ebnf2ps" ebnf2ps))
283 :value-type (boolean :tag "Activate" :value t)))
285 ;;;; Customization variables
286 (defcustom org-clone-delete-id nil
287 "Remove ID property of clones of a subtree.
288 When non-nil, clones of a subtree don't inherit the ID property.
289 Otherwise they inherit the ID property with a new unique
290 identifier."
291 :type 'boolean
292 :version "24.1"
293 :group 'org-id)
295 ;;; Version
296 (org-check-version)
298 ;;;###autoload
299 (defun org-version (&optional here full message)
300 "Show the org-mode version in the echo area.
301 With prefix argument HERE, insert it at point.
302 When FULL is non-nil, use a verbose version string.
303 When MESSAGE is non-nil, display a message with the version."
304 (interactive "P")
305 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
306 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
307 (load-suffixes (list ".el"))
308 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
309 (org-trash (or
310 (and (fboundp 'org-release) (fboundp 'org-git-version))
311 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
312 (load-suffixes save-load-suffixes)
313 (org-version (org-release))
314 (git-version (org-git-version))
315 (version (format "Org-mode version %s (%s @ %s)"
316 org-version
317 git-version
318 (if org-install-dir
319 (if (string= org-dir org-install-dir)
320 org-install-dir
321 (concat "mixed installation! " org-install-dir " and " org-dir))
322 "org-loaddefs.el can not be found!")))
323 (version1 (if full version org-version)))
324 (if (org-called-interactively-p 'interactive)
325 (if here
326 (insert version)
327 (message version))
328 (if message (message version1))
329 version1)))
331 (defconst org-version (org-version))
334 ;;; Syntax Constants
336 ;;;; Block
338 (defconst org-block-regexp
339 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
340 "Regular expression for hiding blocks.")
342 (defconst org-dblock-start-re
343 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
344 "Matches the start line of a dynamic block, with parameters.")
346 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
347 "Matches the end of a dynamic block.")
349 ;;;; Clock and Planning
351 (defconst org-clock-string "CLOCK:"
352 "String used as prefix for timestamps clocking work hours on an item.")
354 (defconst org-closed-string "CLOSED:"
355 "String used as the prefix for timestamps logging closing a TODO entry.")
357 (defconst org-deadline-string "DEADLINE:"
358 "String to mark deadline entries.
359 A deadline is this string, followed by a time stamp. Should be a word,
360 terminated by a colon. You can insert a schedule keyword and
361 a timestamp with \\[org-deadline].")
363 (defconst org-scheduled-string "SCHEDULED:"
364 "String to mark scheduled TODO entries.
365 A schedule is this string, followed by a time stamp. Should be a word,
366 terminated by a colon. You can insert a schedule keyword and
367 a timestamp with \\[org-schedule].")
369 (defconst org-planning-or-clock-line-re
370 (concat "^[ \t]*"
371 (regexp-opt
372 (list org-clock-string org-closed-string org-deadline-string
373 org-scheduled-string)
375 "Matches a line with planning or clock info.
376 Matched keyword is in group 1.")
378 ;;;; Drawer
380 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
381 "Matches first or last line of a hidden block.
382 Group 1 contains drawer's name or \"END\".")
384 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
385 "Regular expression matching the first line of a property drawer.")
387 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
388 "Regular expression matching the last line of a property drawer.")
390 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
391 "Regular expression matching the first line of a clock drawer.")
393 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
394 "Regular expression matching the last line of a clock drawer.")
396 (defconst org-property-drawer-re
397 (concat "\\(" org-property-start-re "\\)[^\000]*?\\("
398 org-property-end-re "\\)\n?")
399 "Matches an entire property drawer.")
401 (defconst org-clock-drawer-re
402 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
403 org-clock-drawer-end-re "\\)\n?")
404 "Matches an entire clock drawer.")
406 ;;;; Headline
408 (defconst org-heading-keyword-regexp-format
409 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
410 "Printf format for a regexp matching a headline with some keyword.
411 This regexp will match the headline of any node which has the
412 exact keyword that is put into the format. The keyword isn't in
413 any group by default, but the stars and the body are.")
415 (defconst org-heading-keyword-maybe-regexp-format
416 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
417 "Printf format for a regexp matching a headline, possibly with some keyword.
418 This regexp can match any headline with the specified keyword, or
419 without a keyword. The keyword isn't in any group by default,
420 but the stars and the body are.")
422 (defconst org-archive-tag "ARCHIVE"
423 "The tag that marks a subtree as archived.
424 An archived subtree does not open during visibility cycling, and does
425 not contribute to the agenda listings.")
427 (defconst org-comment-string "COMMENT"
428 "Entries starting with this keyword will never be exported.
429 An entry can be toggled between COMMENT and normal with
430 \\[org-toggle-comment].")
432 (defconst org-quote-string "QUOTE"
433 "Entries starting with this keyword will be exported in fixed-width font.
434 Quoting applies only to the text in the entry following the headline, and does
435 not extend beyond the next headline, even if that is lower level.
436 An entry can be toggled between QUOTE and normal with
437 \\[org-toggle-fixed-width-section].")
439 ;;;; LaTeX Environments and Fragments
441 (defconst org-latex-regexps
442 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
443 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
444 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
445 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
446 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
447 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
448 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
449 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
450 "Regular expressions for matching embedded LaTeX.")
452 ;;;; Node Property
454 (defconst org-effort-property "Effort"
455 "The property that is being used to keep track of effort estimates.
456 Effort estimates given in this property need to have the format H:MM.")
458 ;;;; Table
460 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
461 "Detect an org-type or table-type table.")
463 (defconst org-table-line-regexp "^[ \t]*|"
464 "Detect an org-type table line.")
466 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
467 "Detect an org-type table line.")
469 (defconst org-table-hline-regexp "^[ \t]*|-"
470 "Detect an org-type table hline.")
472 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
473 "Detect a table-type table hline.")
475 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
476 "Detect the first line outside a table when searching from within it.
477 This works for both table types.")
479 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
480 "Detect a #+TBLFM line.")
482 ;;;; Timestamp
484 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
485 "Regular expression for fast time stamp matching.")
487 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
488 "Regular expression for fast time stamp matching.")
490 (defconst org-ts-regexp0
491 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
492 "Regular expression matching time strings for analysis.
493 This one does not require the space after the date, so it can be used
494 on a string that terminates immediately after the date.")
496 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
497 "Regular expression matching time strings for analysis.")
499 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
500 "Regular expression matching time stamps, with groups.")
502 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
503 "Regular expression matching time stamps (also [..]), with groups.")
505 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
506 "Regular expression matching a time stamp range.")
508 (defconst org-tr-regexp-both
509 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
510 "Regular expression matching a time stamp range.")
512 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
513 org-ts-regexp "\\)?")
514 "Regular expression matching a time stamp or time stamp range.")
516 (defconst org-tsr-regexp-both
517 (concat org-ts-regexp-both "\\(--?-?"
518 org-ts-regexp-both "\\)?")
519 "Regular expression matching a time stamp or time stamp range.
520 The time stamps may be either active or inactive.")
522 (defconst org-repeat-re
523 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
524 "Regular expression for specifying repeated events.
525 After a match, group 1 contains the repeat expression.")
527 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
528 "Formats for `format-time-string' which are used for time stamps.")
531 ;;; The custom variables
533 (defgroup org nil
534 "Outline-based notes management and organizer."
535 :tag "Org"
536 :group 'outlines
537 :group 'calendar)
539 (defcustom org-mode-hook nil
540 "Mode hook for Org-mode, run after the mode was turned on."
541 :group 'org
542 :type 'hook)
544 (defcustom org-load-hook nil
545 "Hook that is run after org.el has been loaded."
546 :group 'org
547 :type 'hook)
549 (defcustom org-log-buffer-setup-hook nil
550 "Hook that is run after an Org log buffer is created."
551 :group 'org
552 :version "24.1"
553 :type 'hook)
555 (defvar org-modules) ; defined below
556 (defvar org-modules-loaded nil
557 "Have the modules been loaded already?")
559 (defun org-load-modules-maybe (&optional force)
560 "Load all extensions listed in `org-modules'."
561 (when (or force (not org-modules-loaded))
562 (mapc (lambda (ext)
563 (condition-case nil (require ext)
564 (error (message "Problems while trying to load feature `%s'" ext))))
565 org-modules)
566 (setq org-modules-loaded t)))
568 (defun org-set-modules (var value)
569 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
570 (set var value)
571 (when (featurep 'org)
572 (org-load-modules-maybe 'force)
573 (org-element-cache-reset 'all)))
575 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
576 "Modules that should always be loaded together with org.el.
578 If a description starts with <C>, the file is not part of Emacs
579 and loading it will require that you have downloaded and properly
580 installed the Org mode distribution.
582 You can also use this system to load external packages (i.e. neither Org
583 core modules, nor modules from the CONTRIB directory). Just add symbols
584 to the end of the list. If the package is called org-xyz.el, then you need
585 to add the symbol `xyz', and the package must have a call to:
587 \(provide 'org-xyz)
589 For export specific modules, see also `org-export-backends'."
590 :group 'org
591 :set 'org-set-modules
592 :version "24.4"
593 :package-version '(Org . "8.0")
594 :type
595 '(set :greedy t
596 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
597 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
598 (const :tag " crypt: Encryption of subtrees" org-crypt)
599 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
600 (const :tag " docview: Links to doc-view buffers" org-docview)
601 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
602 (const :tag " habit: Track your consistency with habits" org-habit)
603 (const :tag " id: Global IDs for identifying entries" org-id)
604 (const :tag " info: Links to Info nodes" org-info)
605 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
606 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
607 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
608 (const :tag " mouse: Additional mouse support" org-mouse)
609 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
610 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
611 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
613 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
614 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
615 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
616 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
617 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
618 (const :tag "C collector: Collect properties into tables" org-collector)
619 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
620 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
621 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
622 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
623 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
624 (const :tag "C eval: Include command output as text" org-eval)
625 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
626 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
627 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
628 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
629 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
630 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
631 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
632 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
633 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
634 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
635 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
636 (const :tag "C mew: Links to Mew folders/messages" org-mew)
637 (const :tag "C mtags: Support for muse-like tags" org-mtags)
638 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
639 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
640 (const :tag "C registry: A registry for Org-mode links" org-registry)
641 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
642 (const :tag "C secretary: Team management with org-mode" org-secretary)
643 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
644 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
645 (const :tag "C track: Keep up with Org-mode development" org-track)
646 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
647 (const :tag "C vm: Links to VM folders/messages" org-vm)
648 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
649 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
650 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
652 (defvar org-export--registered-backends) ; From ox.el.
653 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
654 (declare-function org-export-backend-name "ox" (backend))
655 (defcustom org-export-backends '(ascii html icalendar latex)
656 "List of export back-ends that should be always available.
658 If a description starts with <C>, the file is not part of Emacs
659 and loading it will require that you have downloaded and properly
660 installed the Org mode distribution.
662 Unlike to `org-modules', libraries in this list will not be
663 loaded along with Org, but only once the export framework is
664 needed.
666 This variable needs to be set before org.el is loaded. If you
667 need to make a change while Emacs is running, use the customize
668 interface or run the following code, where VAL stands for the new
669 value of the variable, after updating it:
671 \(progn
672 \(setq org-export--registered-backends
673 \(org-remove-if-not
674 \(lambda (backend)
675 \(let ((name (org-export-backend-name backend)))
676 \(or (memq name val)
677 \(catch 'parentp
678 \(dolist (b val)
679 \(and (org-export-derived-backend-p b name)
680 \(throw 'parentp t)))))))
681 org-export--registered-backends))
682 \(let ((new-list (mapcar 'org-export-backend-name
683 org-export--registered-backends)))
684 \(dolist (backend val)
685 \(cond
686 \((not (load (format \"ox-%s\" backend) t t))
687 \(message \"Problems while trying to load export back-end `%s'\"
688 backend))
689 \((not (memq backend new-list)) (push backend new-list))))
690 \(set-default 'org-export-backends new-list)))
692 Adding a back-end to this list will also pull the back-end it
693 depends on, if any."
694 :group 'org
695 :group 'org-export
696 :version "24.4"
697 :package-version '(Org . "8.0")
698 :initialize 'custom-initialize-set
699 :set (lambda (var val)
700 (if (not (featurep 'ox)) (set-default var val)
701 ;; Any back-end not required anymore (not present in VAL and not
702 ;; a parent of any back-end in the new value) is removed from the
703 ;; list of registered back-ends.
704 (setq org-export--registered-backends
705 (org-remove-if-not
706 (lambda (backend)
707 (let ((name (org-export-backend-name backend)))
708 (or (memq name val)
709 (catch 'parentp
710 (dolist (b val)
711 (and (org-export-derived-backend-p b name)
712 (throw 'parentp t)))))))
713 org-export--registered-backends))
714 ;; Now build NEW-LIST of both new back-ends and required
715 ;; parents.
716 (let ((new-list (mapcar 'org-export-backend-name
717 org-export--registered-backends)))
718 (dolist (backend val)
719 (cond
720 ((not (load (format "ox-%s" backend) t t))
721 (message "Problems while trying to load export back-end `%s'"
722 backend))
723 ((not (memq backend new-list)) (push backend new-list))))
724 ;; Set VAR to that list with fixed dependencies.
725 (set-default var new-list))))
726 :type '(set :greedy t
727 (const :tag " ascii Export buffer to ASCII format" ascii)
728 (const :tag " beamer Export buffer to Beamer presentation" beamer)
729 (const :tag " html Export buffer to HTML format" html)
730 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
731 (const :tag " latex Export buffer to LaTeX format" latex)
732 (const :tag " man Export buffer to MAN format" man)
733 (const :tag " md Export buffer to Markdown format" md)
734 (const :tag " odt Export buffer to ODT format" odt)
735 (const :tag " org Export buffer to Org format" org)
736 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
737 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
738 (const :tag "C deck Export buffer to deck.js presentations" deck)
739 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
740 (const :tag "C groff Export buffer to Groff format" groff)
741 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
742 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
743 (const :tag "C s5 Export buffer to s5 presentations" s5)
744 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
746 (eval-after-load 'ox
747 '(mapc
748 (lambda (backend)
749 (condition-case nil (require (intern (format "ox-%s" backend)))
750 (error (message "Problems while trying to load export back-end `%s'"
751 backend))))
752 org-export-backends))
754 (defcustom org-support-shift-select nil
755 "Non-nil means make shift-cursor commands select text when possible.
757 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
758 start selecting a region, or enlarge regions started in this way.
759 In Org-mode, in special contexts, these same keys are used for
760 other purposes, important enough to compete with shift selection.
761 Org tries to balance these needs by supporting `shift-select-mode'
762 outside these special contexts, under control of this variable.
764 The default of this variable is nil, to avoid confusing behavior. Shifted
765 cursor keys will then execute Org commands in the following contexts:
766 - on a headline, changing TODO state (left/right) and priority (up/down)
767 - on a time stamp, changing the time
768 - in a plain list item, changing the bullet type
769 - in a property definition line, switching between allowed values
770 - in the BEGIN line of a clock table (changing the time block).
771 Outside these contexts, the commands will throw an error.
773 When this variable is t and the cursor is not in a special
774 context, Org-mode will support shift-selection for making and
775 enlarging regions. To make this more effective, the bullet
776 cycling will no longer happen anywhere in an item line, but only
777 if the cursor is exactly on the bullet.
779 If you set this variable to the symbol `always', then the keys
780 will not be special in headlines, property lines, and item lines,
781 to make shift selection work there as well. If this is what you
782 want, you can use the following alternative commands: `C-c C-t'
783 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
784 can be used to switch TODO sets, `C-c -' to cycle item bullet
785 types, and properties can be edited by hand or in column view.
787 However, when the cursor is on a timestamp, shift-cursor commands
788 will still edit the time stamp - this is just too good to give up.
790 XEmacs user should have this variable set to nil, because
791 `shift-select-mode' is in Emacs 23 or later only."
792 :group 'org
793 :type '(choice
794 (const :tag "Never" nil)
795 (const :tag "When outside special context" t)
796 (const :tag "Everywhere except timestamps" always)))
798 (defcustom org-loop-over-headlines-in-active-region nil
799 "Shall some commands act upon headlines in the active region?
801 When set to `t', some commands will be performed in all headlines
802 within the active region.
804 When set to `start-level', some commands will be performed in all
805 headlines within the active region, provided that these headlines
806 are of the same level than the first one.
808 When set to a string, those commands will be performed on the
809 matching headlines within the active region. Such string must be
810 a tags/property/todo match as it is used in the agenda tags view.
812 The list of commands is: `org-schedule', `org-deadline',
813 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
814 `org-archive-to-archive-sibling'. The archiving commands skip
815 already archived entries."
816 :type '(choice (const :tag "Don't loop" nil)
817 (const :tag "All headlines in active region" t)
818 (const :tag "In active region, headlines at the same level than the first one" start-level)
819 (string :tag "Tags/Property/Todo matcher"))
820 :version "24.1"
821 :group 'org-todo
822 :group 'org-archive)
824 (defgroup org-startup nil
825 "Options concerning startup of Org-mode."
826 :tag "Org Startup"
827 :group 'org)
829 (defcustom org-startup-folded t
830 "Non-nil means entering Org-mode will switch to OVERVIEW.
831 This can also be configured on a per-file basis by adding one of
832 the following lines anywhere in the buffer:
834 #+STARTUP: fold (or `overview', this is equivalent)
835 #+STARTUP: nofold (or `showall', this is equivalent)
836 #+STARTUP: content
837 #+STARTUP: showeverything
839 By default, this option is ignored when Org opens agenda files
840 for the first time. If you want the agenda to honor the startup
841 option, set `org-agenda-inhibit-startup' to nil."
842 :group 'org-startup
843 :type '(choice
844 (const :tag "nofold: show all" nil)
845 (const :tag "fold: overview" t)
846 (const :tag "content: all headlines" content)
847 (const :tag "show everything, even drawers" showeverything)))
849 (defcustom org-startup-truncated t
850 "Non-nil means entering Org-mode will set `truncate-lines'.
851 This is useful since some lines containing links can be very long and
852 uninteresting. Also tables look terrible when wrapped."
853 :group 'org-startup
854 :type 'boolean)
856 (defcustom org-startup-indented nil
857 "Non-nil means turn on `org-indent-mode' on startup.
858 This can also be configured on a per-file basis by adding one of
859 the following lines anywhere in the buffer:
861 #+STARTUP: indent
862 #+STARTUP: noindent"
863 :group 'org-structure
864 :type '(choice
865 (const :tag "Not" nil)
866 (const :tag "Globally (slow on startup in large files)" t)))
868 (defcustom org-use-sub-superscripts t
869 "Non-nil means interpret \"_\" and \"^\" for display.
871 If you want to control how Org exports those characters, see
872 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
873 used to be an alias for `org-export-with-sub-superscripts' in
874 Org <8.0, it is not anymore.
876 When this option is turned on, you can use TeX-like syntax for
877 sub- and superscripts within the buffer. Several characters after
878 \"_\" or \"^\" will be considered as a single item - so grouping
879 with {} is normally not needed. For example, the following things
880 will be parsed as single sub- or superscripts:
882 10^24 or 10^tau several digits will be considered 1 item.
883 10^-12 or 10^-tau a leading sign with digits or a word
884 x^2-y^3 will be read as x^2 - y^3, because items are
885 terminated by almost any nonword/nondigit char.
886 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
888 Still, ambiguity is possible. So when in doubt, use {} to enclose
889 the sub/superscript. If you set this variable to the symbol `{}',
890 the braces are *required* in order to trigger interpretations as
891 sub/superscript. This can be helpful in documents that need \"_\"
892 frequently in plain text."
893 :group 'org-startup
894 :version "24.4"
895 :package-version '(Org . "8.0")
896 :type '(choice
897 (const :tag "Always interpret" t)
898 (const :tag "Only with braces" {})
899 (const :tag "Never interpret" nil)))
901 (defcustom org-startup-with-beamer-mode nil
902 "Non-nil means turn on `org-beamer-mode' on startup.
903 This can also be configured on a per-file basis by adding one of
904 the following lines anywhere in the buffer:
906 #+STARTUP: beamer"
907 :group 'org-startup
908 :version "24.1"
909 :type 'boolean)
911 (defcustom org-startup-align-all-tables nil
912 "Non-nil means align all tables when visiting a file.
913 This is useful when the column width in tables is forced with <N> cookies
914 in table fields. Such tables will look correct only after the first re-align.
915 This can also be configured on a per-file basis by adding one of
916 the following lines anywhere in the buffer:
917 #+STARTUP: align
918 #+STARTUP: noalign"
919 :group 'org-startup
920 :type 'boolean)
922 (defcustom org-startup-with-inline-images nil
923 "Non-nil means show inline images when loading a new Org file.
924 This can also be configured on a per-file basis by adding one of
925 the following lines anywhere in the buffer:
926 #+STARTUP: inlineimages
927 #+STARTUP: noinlineimages"
928 :group 'org-startup
929 :version "24.1"
930 :type 'boolean)
932 (defcustom org-startup-with-latex-preview nil
933 "Non-nil means preview LaTeX fragments when loading a new Org file.
935 This can also be configured on a per-file basis by adding one of
936 the following lines anywhere in the buffer:
937 #+STARTUP: latexpreview
938 #+STARTUP: nolatexpreview"
939 :group 'org-startup
940 :version "24.4"
941 :package-version '(Org . "8.0")
942 :type 'boolean)
944 (defcustom org-insert-mode-line-in-empty-file nil
945 "Non-nil means insert the first line setting Org-mode in empty files.
946 When the function `org-mode' is called interactively in an empty file, this
947 normally means that the file name does not automatically trigger Org-mode.
948 To ensure that the file will always be in Org-mode in the future, a
949 line enforcing Org-mode will be inserted into the buffer, if this option
950 has been set."
951 :group 'org-startup
952 :type 'boolean)
954 (defcustom org-replace-disputed-keys nil
955 "Non-nil means use alternative key bindings for some keys.
956 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
957 These keys are also used by other packages like shift-selection-mode'
958 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
959 If you want to use Org-mode together with one of these other modes,
960 or more generally if you would like to move some Org-mode commands to
961 other keys, set this variable and configure the keys with the variable
962 `org-disputed-keys'.
964 This option is only relevant at load-time of Org-mode, and must be set
965 *before* org.el is loaded. Changing it requires a restart of Emacs to
966 become effective."
967 :group 'org-startup
968 :type 'boolean)
970 (defcustom org-use-extra-keys nil
971 "Non-nil means use extra key sequence definitions for certain commands.
972 This happens automatically if you run XEmacs or if `window-system'
973 is nil. This variable lets you do the same manually. You must
974 set it before loading org.
976 Example: on Carbon Emacs 22 running graphically, with an external
977 keyboard on a Powerbook, the default way of setting M-left might
978 not work for either Alt or ESC. Setting this variable will make
979 it work for ESC."
980 :group 'org-startup
981 :type 'boolean)
983 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
985 (defcustom org-disputed-keys
986 '(([(shift up)] . [(meta p)])
987 ([(shift down)] . [(meta n)])
988 ([(shift left)] . [(meta -)])
989 ([(shift right)] . [(meta +)])
990 ([(control shift right)] . [(meta shift +)])
991 ([(control shift left)] . [(meta shift -)]))
992 "Keys for which Org-mode and other modes compete.
993 This is an alist, cars are the default keys, second element specifies
994 the alternative to use when `org-replace-disputed-keys' is t.
996 Keys can be specified in any syntax supported by `define-key'.
997 The value of this option takes effect only at Org-mode's startup,
998 therefore you'll have to restart Emacs to apply it after changing."
999 :group 'org-startup
1000 :type 'alist)
1002 (defun org-key (key)
1003 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1004 Or return the original if not disputed.
1005 Also apply the translations defined in `org-xemacs-key-equivalents'."
1006 (when org-replace-disputed-keys
1007 (let* ((nkey (key-description key))
1008 (x (org-find-if (lambda (x)
1009 (equal (key-description (car x)) nkey))
1010 org-disputed-keys)))
1011 (setq key (if x (cdr x) key))))
1012 (when (featurep 'xemacs)
1013 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1014 key)
1016 (defun org-find-if (predicate seq)
1017 (catch 'exit
1018 (while seq
1019 (if (funcall predicate (car seq))
1020 (throw 'exit (car seq))
1021 (pop seq)))))
1023 (defun org-defkey (keymap key def)
1024 "Define a key, possibly translated, as returned by `org-key'."
1025 (define-key keymap (org-key key) def))
1027 (defcustom org-ellipsis nil
1028 "The ellipsis to use in the Org-mode outline.
1029 When nil, just use the standard three dots.
1030 When a string, use that string instead.
1031 When a face, use the standard 3 dots, but with the specified face.
1032 The change affects only Org-mode (which will then use its own display table).
1033 Changing this requires executing `M-x org-mode RET' in a buffer to become
1034 effective."
1035 :group 'org-startup
1036 :type '(choice (const :tag "Default" nil)
1037 (face :tag "Face" :value org-warning)
1038 (string :tag "String" :value "...#")))
1040 (defvar org-display-table nil
1041 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1043 (defgroup org-keywords nil
1044 "Keywords in Org-mode."
1045 :tag "Org Keywords"
1046 :group 'org)
1048 (defcustom org-closed-keep-when-no-todo nil
1049 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1050 :group 'org-todo
1051 :group 'org-keywords
1052 :version "24.4"
1053 :package-version '(Org . "8.0")
1054 :type 'boolean)
1056 (defgroup org-structure nil
1057 "Options concerning the general structure of Org-mode files."
1058 :tag "Org Structure"
1059 :group 'org)
1061 (defgroup org-reveal-location nil
1062 "Options about how to make context of a location visible."
1063 :tag "Org Reveal Location"
1064 :group 'org-structure)
1066 (defconst org-context-choice
1067 '(choice
1068 (const :tag "Always" t)
1069 (const :tag "Never" nil)
1070 (repeat :greedy t :tag "Individual contexts"
1071 (cons
1072 (choice :tag "Context"
1073 (const agenda)
1074 (const org-goto)
1075 (const occur-tree)
1076 (const tags-tree)
1077 (const link-search)
1078 (const mark-goto)
1079 (const bookmark-jump)
1080 (const isearch)
1081 (const default))
1082 (boolean))))
1083 "Contexts for the reveal options.")
1085 (defcustom org-show-hierarchy-above '((default . t))
1086 "Non-nil means show full hierarchy when revealing a location.
1087 Org-mode often shows locations in an org-mode file which might have
1088 been invisible before. When this is set, the hierarchy of headings
1089 above the exposed location is shown.
1090 Turning this off for example for sparse trees makes them very compact.
1091 Instead of t, this can also be an alist specifying this option for different
1092 contexts. Valid contexts are
1093 agenda when exposing an entry from the agenda
1094 org-goto when using the command `org-goto' on key C-c C-j
1095 occur-tree when using the command `org-occur' on key C-c /
1096 tags-tree when constructing a sparse tree based on tags matches
1097 link-search when exposing search matches associated with a link
1098 mark-goto when exposing the jump goal of a mark
1099 bookmark-jump when exposing a bookmark location
1100 isearch when exiting from an incremental search
1101 default default for all contexts not set explicitly"
1102 :group 'org-reveal-location
1103 :type org-context-choice)
1105 (defcustom org-show-following-heading '((default . nil))
1106 "Non-nil means show following heading when revealing a location.
1107 Org-mode often shows locations in an org-mode file which might have
1108 been invisible before. When this is set, the heading following the
1109 match is shown.
1110 Turning this off for example for sparse trees makes them very compact,
1111 but makes it harder to edit the location of the match. In such a case,
1112 use the command \\[org-reveal] to show more context.
1113 Instead of t, this can also be an alist specifying this option for different
1114 contexts. See `org-show-hierarchy-above' for valid contexts."
1115 :group 'org-reveal-location
1116 :type org-context-choice)
1118 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
1119 "Non-nil means show all sibling heading when revealing a location.
1120 Org-mode often shows locations in an org-mode file which might have
1121 been invisible before. When this is set, the sibling of the current entry
1122 heading are all made visible. If `org-show-hierarchy-above' is t,
1123 the same happens on each level of the hierarchy above the current entry.
1125 By default this is on for the isearch context, off for all other contexts.
1126 Turning this off for example for sparse trees makes them very compact,
1127 but makes it harder to edit the location of the match. In such a case,
1128 use the command \\[org-reveal] to show more context.
1129 Instead of t, this can also be an alist specifying this option for different
1130 contexts. See `org-show-hierarchy-above' for valid contexts."
1131 :group 'org-reveal-location
1132 :type org-context-choice
1133 :version "24.4"
1134 :package-version '(Org . "8.0"))
1136 (defcustom org-show-entry-below '((default . nil))
1137 "Non-nil means show the entry below a headline when revealing a location.
1138 Org-mode often shows locations in an org-mode file which might have
1139 been invisible before. When this is set, the text below the headline that is
1140 exposed is also shown.
1142 By default this is off for all contexts.
1143 Instead of t, this can also be an alist specifying this option for different
1144 contexts. See `org-show-hierarchy-above' for valid contexts."
1145 :group 'org-reveal-location
1146 :type org-context-choice)
1148 (defcustom org-indirect-buffer-display 'other-window
1149 "How should indirect tree buffers be displayed?
1150 This applies to indirect buffers created with the commands
1151 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1152 Valid values are:
1153 current-window Display in the current window
1154 other-window Just display in another window.
1155 dedicated-frame Create one new frame, and re-use it each time.
1156 new-frame Make a new frame each time. Note that in this case
1157 previously-made indirect buffers are kept, and you need to
1158 kill these buffers yourself."
1159 :group 'org-structure
1160 :group 'org-agenda-windows
1161 :type '(choice
1162 (const :tag "In current window" current-window)
1163 (const :tag "In current frame, other window" other-window)
1164 (const :tag "Each time a new frame" new-frame)
1165 (const :tag "One dedicated frame" dedicated-frame)))
1167 (defcustom org-use-speed-commands nil
1168 "Non-nil means activate single letter commands at beginning of a headline.
1169 This may also be a function to test for appropriate locations where speed
1170 commands should be active.
1172 For example, to activate speed commands when the point is on any
1173 star at the beginning of the headline, you can do this:
1175 (setq org-use-speed-commands
1176 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1177 :group 'org-structure
1178 :type '(choice
1179 (const :tag "Never" nil)
1180 (const :tag "At beginning of headline stars" t)
1181 (function)))
1183 (defcustom org-speed-commands-user nil
1184 "Alist of additional speed commands.
1185 This list will be checked before `org-speed-commands-default'
1186 when the variable `org-use-speed-commands' is non-nil
1187 and when the cursor is at the beginning of a headline.
1188 The car if each entry is a string with a single letter, which must
1189 be assigned to `self-insert-command' in the global map.
1190 The cdr is either a command to be called interactively, a function
1191 to be called, or a form to be evaluated.
1192 An entry that is just a list with a single string will be interpreted
1193 as a descriptive headline that will be added when listing the speed
1194 commands in the Help buffer using the `?' speed command."
1195 :group 'org-structure
1196 :type '(repeat :value ("k" . ignore)
1197 (choice :value ("k" . ignore)
1198 (list :tag "Descriptive Headline" (string :tag "Headline"))
1199 (cons :tag "Letter and Command"
1200 (string :tag "Command letter")
1201 (choice
1202 (function)
1203 (sexp))))))
1205 (defcustom org-bookmark-names-plist
1206 '(:last-capture "org-capture-last-stored"
1207 :last-refile "org-refile-last-stored"
1208 :last-capture-marker "org-capture-last-stored-marker")
1209 "Names for bookmarks automatically set by some Org commands.
1210 This can provide strings as names for a number of bookmarks Org sets
1211 automatically. The following keys are currently implemented:
1212 :last-capture
1213 :last-capture-marker
1214 :last-refile
1215 When a key does not show up in the property list, the corresponding bookmark
1216 is not set."
1217 :group 'org-structure
1218 :type 'plist)
1220 (defgroup org-cycle nil
1221 "Options concerning visibility cycling in Org-mode."
1222 :tag "Org Cycle"
1223 :group 'org-structure)
1225 (defcustom org-cycle-skip-children-state-if-no-children t
1226 "Non-nil means skip CHILDREN state in entries that don't have any."
1227 :group 'org-cycle
1228 :type 'boolean)
1230 (defcustom org-cycle-max-level nil
1231 "Maximum level which should still be subject to visibility cycling.
1232 Levels higher than this will, for cycling, be treated as text, not a headline.
1233 When `org-odd-levels-only' is set, a value of N in this variable actually
1234 means 2N-1 stars as the limiting headline.
1235 When nil, cycle all levels.
1236 Note that the limiting level of cycling is also influenced by
1237 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1238 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1239 than its value."
1240 :group 'org-cycle
1241 :type '(choice
1242 (const :tag "No limit" nil)
1243 (integer :tag "Maximum level")))
1245 (defcustom org-hide-block-startup nil
1246 "Non-nil means entering Org-mode will fold all blocks.
1247 This can also be set in on a per-file basis with
1249 #+STARTUP: hideblocks
1250 #+STARTUP: showblocks"
1251 :group 'org-startup
1252 :group 'org-cycle
1253 :type 'boolean)
1255 (defcustom org-cycle-global-at-bob nil
1256 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1257 This makes it possible to do global cycling without having to use S-TAB or
1258 \\[universal-argument] TAB. For this special case to work, the first line
1259 of the buffer must not be a headline -- it may be empty or some other text.
1260 When used in this way, `org-cycle-hook' is disabled temporarily to make
1261 sure the cursor stays at the beginning of the buffer. When this option is
1262 nil, don't do anything special at the beginning of the buffer."
1263 :group 'org-cycle
1264 :type 'boolean)
1266 (defcustom org-cycle-level-after-item/entry-creation t
1267 "Non-nil means cycle entry level or item indentation in new empty entries.
1269 When the cursor is at the end of an empty headline, i.e., with only stars
1270 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1271 and then all possible ancestor states, before returning to the original state.
1272 This makes data entry extremely fast: M-RET to create a new headline,
1273 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1275 When the cursor is at the end of an empty plain list item, one TAB will
1276 make it a subitem, two or more tabs will back up to make this an item
1277 higher up in the item hierarchy."
1278 :group 'org-cycle
1279 :type 'boolean)
1281 (defcustom org-cycle-emulate-tab t
1282 "Where should `org-cycle' emulate TAB.
1283 nil Never
1284 white Only in completely white lines
1285 whitestart Only at the beginning of lines, before the first non-white char
1286 t Everywhere except in headlines
1287 exc-hl-bol Everywhere except at the start of a headline
1288 If TAB is used in a place where it does not emulate TAB, the current subtree
1289 visibility is cycled."
1290 :group 'org-cycle
1291 :type '(choice (const :tag "Never" nil)
1292 (const :tag "Only in completely white lines" white)
1293 (const :tag "Before first char in a line" whitestart)
1294 (const :tag "Everywhere except in headlines" t)
1295 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1297 (defcustom org-cycle-separator-lines 2
1298 "Number of empty lines needed to keep an empty line between collapsed trees.
1299 If you leave an empty line between the end of a subtree and the following
1300 headline, this empty line is hidden when the subtree is folded.
1301 Org-mode will leave (exactly) one empty line visible if the number of
1302 empty lines is equal or larger to the number given in this variable.
1303 So the default 2 means at least 2 empty lines after the end of a subtree
1304 are needed to produce free space between a collapsed subtree and the
1305 following headline.
1307 If the number is negative, and the number of empty lines is at least -N,
1308 all empty lines are shown.
1310 Special case: when 0, never leave empty lines in collapsed view."
1311 :group 'org-cycle
1312 :type 'integer)
1313 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1315 (defcustom org-pre-cycle-hook nil
1316 "Hook that is run before visibility cycling is happening.
1317 The function(s) in this hook must accept a single argument which indicates
1318 the new state that will be set right after running this hook. The
1319 argument is a symbol. Before a global state change, it can have the values
1320 `overview', `content', or `all'. Before a local state change, it can have
1321 the values `folded', `children', or `subtree'."
1322 :group 'org-cycle
1323 :type 'hook)
1325 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1326 org-cycle-hide-drawers
1327 org-cycle-hide-inline-tasks
1328 org-cycle-show-empty-lines
1329 org-optimize-window-after-visibility-change)
1330 "Hook that is run after `org-cycle' has changed the buffer visibility.
1331 The function(s) in this hook must accept a single argument which indicates
1332 the new state that was set by the most recent `org-cycle' command. The
1333 argument is a symbol. After a global state change, it can have the values
1334 `overview', `contents', or `all'. After a local state change, it can have
1335 the values `folded', `children', or `subtree'."
1336 :group 'org-cycle
1337 :type 'hook)
1339 (defgroup org-edit-structure nil
1340 "Options concerning structure editing in Org-mode."
1341 :tag "Org Edit Structure"
1342 :group 'org-structure)
1344 (defcustom org-odd-levels-only nil
1345 "Non-nil means skip even levels and only use odd levels for the outline.
1346 This has the effect that two stars are being added/taken away in
1347 promotion/demotion commands. It also influences how levels are
1348 handled by the exporters.
1349 Changing it requires restart of `font-lock-mode' to become effective
1350 for fontification also in regions already fontified.
1351 You may also set this on a per-file basis by adding one of the following
1352 lines to the buffer:
1354 #+STARTUP: odd
1355 #+STARTUP: oddeven"
1356 :group 'org-edit-structure
1357 :group 'org-appearance
1358 :type 'boolean)
1360 (defcustom org-adapt-indentation t
1361 "Non-nil means adapt indentation to outline node level.
1363 When this variable is set, Org assumes that you write outlines by
1364 indenting text in each node to align with the headline (after the stars).
1365 The following issues are influenced by this variable:
1367 - When this is set and the *entire* text in an entry is indented, the
1368 indentation is increased by one space in a demotion command, and
1369 decreased by one in a promotion command. If any line in the entry
1370 body starts with text at column 0, indentation is not changed at all.
1372 - Property drawers and planning information is inserted indented when
1373 this variable s set. When nil, they will not be indented.
1375 - TAB indents a line relative to context. The lines below a headline
1376 will be indented when this variable is set.
1378 Note that this is all about true indentation, by adding and removing
1379 space characters. See also `org-indent.el' which does level-dependent
1380 indentation in a virtual way, i.e. at display time in Emacs."
1381 :group 'org-edit-structure
1382 :type 'boolean)
1384 (defcustom org-special-ctrl-a/e nil
1385 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1387 When t, `C-a' will bring back the cursor to the beginning of the
1388 headline text, i.e. after the stars and after a possible TODO
1389 keyword. In an item, this will be the position after bullet and
1390 check-box, if any. When the cursor is already at that position,
1391 another `C-a' will bring it to the beginning of the line.
1393 `C-e' will jump to the end of the headline, ignoring the presence
1394 of tags in the headline. A second `C-e' will then jump to the
1395 true end of the line, after any tags. This also means that, when
1396 this variable is non-nil, `C-e' also will never jump beyond the
1397 end of the heading of a folded section, i.e. not after the
1398 ellipses.
1400 When set to the symbol `reversed', the first `C-a' or `C-e' works
1401 normally, going to the true line boundary first. Only a directly
1402 following, identical keypress will bring the cursor to the
1403 special positions.
1405 This may also be a cons cell where the behavior for `C-a' and
1406 `C-e' is set separately."
1407 :group 'org-edit-structure
1408 :type '(choice
1409 (const :tag "off" nil)
1410 (const :tag "on: after stars/bullet and before tags first" t)
1411 (const :tag "reversed: true line boundary first" reversed)
1412 (cons :tag "Set C-a and C-e separately"
1413 (choice :tag "Special C-a"
1414 (const :tag "off" nil)
1415 (const :tag "on: after stars/bullet first" t)
1416 (const :tag "reversed: before stars/bullet first" reversed))
1417 (choice :tag "Special C-e"
1418 (const :tag "off" nil)
1419 (const :tag "on: before tags first" t)
1420 (const :tag "reversed: after tags first" reversed)))))
1421 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1423 (defcustom org-special-ctrl-k nil
1424 "Non-nil means `C-k' will behave specially in headlines.
1425 When nil, `C-k' will call the default `kill-line' command.
1426 When t, the following will happen while the cursor is in the headline:
1428 - When the cursor is at the beginning of a headline, kill the entire
1429 line and possible the folded subtree below the line.
1430 - When in the middle of the headline text, kill the headline up to the tags.
1431 - When after the headline text, kill the tags."
1432 :group 'org-edit-structure
1433 :type 'boolean)
1435 (defcustom org-ctrl-k-protect-subtree nil
1436 "Non-nil means, do not delete a hidden subtree with C-k.
1437 When set to the symbol `error', simply throw an error when C-k is
1438 used to kill (part-of) a headline that has hidden text behind it.
1439 Any other non-nil value will result in a query to the user, if it is
1440 OK to kill that hidden subtree. When nil, kill without remorse."
1441 :group 'org-edit-structure
1442 :version "24.1"
1443 :type '(choice
1444 (const :tag "Do not protect hidden subtrees" nil)
1445 (const :tag "Protect hidden subtrees with a security query" t)
1446 (const :tag "Never kill a hidden subtree with C-k" error)))
1448 (defcustom org-special-ctrl-o t
1449 "Non-nil means, make `C-o' insert a row in tables."
1450 :group 'org-edit-structure
1451 :type 'boolean)
1453 (defcustom org-catch-invisible-edits nil
1454 "Check if in invisible region before inserting or deleting a character.
1455 Valid values are:
1457 nil Do not check, so just do invisible edits.
1458 error Throw an error and do nothing.
1459 show Make point visible, and do the requested edit.
1460 show-and-error Make point visible, then throw an error and abort the edit.
1461 smart Make point visible, and do insertion/deletion if it is
1462 adjacent to visible text and the change feels predictable.
1463 Never delete a previously invisible character or add in the
1464 middle or right after an invisible region. Basically, this
1465 allows insertion and backward-delete right before ellipses.
1466 FIXME: maybe in this case we should not even show?"
1467 :group 'org-edit-structure
1468 :version "24.1"
1469 :type '(choice
1470 (const :tag "Do not check" nil)
1471 (const :tag "Throw error when trying to edit" error)
1472 (const :tag "Unhide, but do not do the edit" show-and-error)
1473 (const :tag "Show invisible part and do the edit" show)
1474 (const :tag "Be smart and do the right thing" smart)))
1476 (defcustom org-yank-folded-subtrees t
1477 "Non-nil means when yanking subtrees, fold them.
1478 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1479 it starts with a heading and all other headings in it are either children
1480 or siblings, then fold all the subtrees. However, do this only if no
1481 text after the yank would be swallowed into a folded tree by this action."
1482 :group 'org-edit-structure
1483 :type 'boolean)
1485 (defcustom org-yank-adjusted-subtrees nil
1486 "Non-nil means when yanking subtrees, adjust the level.
1487 With this setting, `org-paste-subtree' is used to insert the subtree, see
1488 this function for details."
1489 :group 'org-edit-structure
1490 :type 'boolean)
1492 (defcustom org-M-RET-may-split-line '((default . t))
1493 "Non-nil means M-RET will split the line at the cursor position.
1494 When nil, it will go to the end of the line before making a
1495 new line.
1496 You may also set this option in a different way for different
1497 contexts. Valid contexts are:
1499 headline when creating a new headline
1500 item when creating a new item
1501 table in a table field
1502 default the value to be used for all contexts not explicitly
1503 customized"
1504 :group 'org-structure
1505 :group 'org-table
1506 :type '(choice
1507 (const :tag "Always" t)
1508 (const :tag "Never" nil)
1509 (repeat :greedy t :tag "Individual contexts"
1510 (cons
1511 (choice :tag "Context"
1512 (const headline)
1513 (const item)
1514 (const table)
1515 (const default))
1516 (boolean)))))
1519 (defcustom org-insert-heading-respect-content nil
1520 "Non-nil means insert new headings after the current subtree.
1521 When nil, the new heading is created directly after the current line.
1522 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1523 this variable on for the duration of the command."
1524 :group 'org-structure
1525 :type 'boolean)
1527 (defcustom org-blank-before-new-entry '((heading . auto)
1528 (plain-list-item . auto))
1529 "Should `org-insert-heading' leave a blank line before new heading/item?
1530 The value is an alist, with `heading' and `plain-list-item' as CAR,
1531 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1532 which case Org will look at the surrounding headings/items and try to
1533 make an intelligent decision whether to insert a blank line or not.
1535 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1536 the setting here is ignored and no empty line is inserted to avoid breaking
1537 the list structure."
1538 :group 'org-edit-structure
1539 :type '(list
1540 (cons (const heading)
1541 (choice (const :tag "Never" nil)
1542 (const :tag "Always" t)
1543 (const :tag "Auto" auto)))
1544 (cons (const plain-list-item)
1545 (choice (const :tag "Never" nil)
1546 (const :tag "Always" t)
1547 (const :tag "Auto" auto)))))
1549 (defcustom org-insert-heading-hook nil
1550 "Hook being run after inserting a new heading."
1551 :group 'org-edit-structure
1552 :type 'hook)
1554 (defcustom org-enable-fixed-width-editor t
1555 "Non-nil means lines starting with \":\" are treated as fixed-width.
1556 This currently only means they are never auto-wrapped.
1557 When nil, such lines will be treated like ordinary lines.
1558 See also the QUOTE keyword."
1559 :group 'org-edit-structure
1560 :type 'boolean)
1562 (defcustom org-goto-auto-isearch t
1563 "Non-nil means typing characters in `org-goto' starts incremental search.
1564 When nil, you can use these keybindings to navigate the buffer:
1566 q Quit the org-goto interface
1567 n Go to the next visible heading
1568 p Go to the previous visible heading
1569 f Go one heading forward on same level
1570 b Go one heading backward on same level
1571 u Go one heading up"
1572 :group 'org-edit-structure
1573 :type 'boolean)
1575 (defgroup org-sparse-trees nil
1576 "Options concerning sparse trees in Org-mode."
1577 :tag "Org Sparse Trees"
1578 :group 'org-structure)
1580 (defcustom org-highlight-sparse-tree-matches t
1581 "Non-nil means highlight all matches that define a sparse tree.
1582 The highlights will automatically disappear the next time the buffer is
1583 changed by an edit command."
1584 :group 'org-sparse-trees
1585 :type 'boolean)
1587 (defcustom org-remove-highlights-with-change t
1588 "Non-nil means any change to the buffer will remove temporary highlights.
1589 Such highlights are created by `org-occur' and `org-clock-display'.
1590 When nil, `C-c C-c needs to be used to get rid of the highlights.
1591 The highlights created by `org-preview-latex-fragment' always need
1592 `C-c C-c' to be removed."
1593 :group 'org-sparse-trees
1594 :group 'org-time
1595 :type 'boolean)
1598 (defcustom org-occur-hook '(org-first-headline-recenter)
1599 "Hook that is run after `org-occur' has constructed a sparse tree.
1600 This can be used to recenter the window to show as much of the structure
1601 as possible."
1602 :group 'org-sparse-trees
1603 :type 'hook)
1605 (defgroup org-imenu-and-speedbar nil
1606 "Options concerning imenu and speedbar in Org-mode."
1607 :tag "Org Imenu and Speedbar"
1608 :group 'org-structure)
1610 (defcustom org-imenu-depth 2
1611 "The maximum level for Imenu access to Org-mode headlines.
1612 This also applied for speedbar access."
1613 :group 'org-imenu-and-speedbar
1614 :type 'integer)
1616 (defgroup org-table nil
1617 "Options concerning tables in Org-mode."
1618 :tag "Org Table"
1619 :group 'org)
1621 (defcustom org-enable-table-editor 'optimized
1622 "Non-nil means lines starting with \"|\" are handled by the table editor.
1623 When nil, such lines will be treated like ordinary lines.
1625 When equal to the symbol `optimized', the table editor will be optimized to
1626 do the following:
1627 - Automatic overwrite mode in front of whitespace in table fields.
1628 This makes the structure of the table stay in tact as long as the edited
1629 field does not exceed the column width.
1630 - Minimize the number of realigns. Normally, the table is aligned each time
1631 TAB or RET are pressed to move to another field. With optimization this
1632 happens only if changes to a field might have changed the column width.
1633 Optimization requires replacing the functions `self-insert-command',
1634 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1635 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1636 very good at guessing when a re-align will be necessary, but you can always
1637 force one with \\[org-ctrl-c-ctrl-c].
1639 If you would like to use the optimized version in Org-mode, but the
1640 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1642 This variable can be used to turn on and off the table editor during a session,
1643 but in order to toggle optimization, a restart is required.
1645 See also the variable `org-table-auto-blank-field'."
1646 :group 'org-table
1647 :type '(choice
1648 (const :tag "off" nil)
1649 (const :tag "on" t)
1650 (const :tag "on, optimized" optimized)))
1652 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1653 (version<= emacs-version "24.1"))
1654 "Non-nil means cluster self-insert commands for undo when possible.
1655 If this is set, then, like in the Emacs command loop, 20 consecutive
1656 characters will be undone together.
1657 This is configurable, because there is some impact on typing performance."
1658 :group 'org-table
1659 :type 'boolean)
1661 (defcustom org-table-tab-recognizes-table.el t
1662 "Non-nil means TAB will automatically notice a table.el table.
1663 When it sees such a table, it moves point into it and - if necessary -
1664 calls `table-recognize-table'."
1665 :group 'org-table-editing
1666 :type 'boolean)
1668 (defgroup org-link nil
1669 "Options concerning links in Org-mode."
1670 :tag "Org Link"
1671 :group 'org)
1673 (defvar org-link-abbrev-alist-local nil
1674 "Buffer-local version of `org-link-abbrev-alist', which see.
1675 The value of this is taken from the #+LINK lines.")
1676 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1678 (defcustom org-link-abbrev-alist nil
1679 "Alist of link abbreviations.
1680 The car of each element is a string, to be replaced at the start of a link.
1681 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1682 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1684 [[linkkey:tag][description]]
1686 The 'linkkey' must be a word word, starting with a letter, followed
1687 by letters, numbers, '-' or '_'.
1689 If REPLACE is a string, the tag will simply be appended to create the link.
1690 If the string contains \"%s\", the tag will be inserted there. If the string
1691 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1692 at that point (see the function `url-hexify-string'). If the string contains
1693 the specifier \"%(my-function)\", then the custom function `my-function' will
1694 be invoked: this function takes the tag as its only argument and must return
1695 a string.
1697 REPLACE may also be a function that will be called with the tag as the
1698 only argument to create the link, which should be returned as a string.
1700 See the manual for examples."
1701 :group 'org-link
1702 :type '(repeat
1703 (cons
1704 (string :tag "Protocol")
1705 (choice
1706 (string :tag "Format")
1707 (function)))))
1709 (defcustom org-descriptive-links t
1710 "Non-nil means Org will display descriptive links.
1711 E.g. [[http://orgmode.org][Org website]] will be displayed as
1712 \"Org Website\", hiding the link itself and just displaying its
1713 description. When set to `nil', Org will display the full links
1714 literally.
1716 You can interactively set the value of this variable by calling
1717 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1718 :group 'org-link
1719 :type 'boolean)
1721 (defcustom org-link-file-path-type 'adaptive
1722 "How the path name in file links should be stored.
1723 Valid values are:
1725 relative Relative to the current directory, i.e. the directory of the file
1726 into which the link is being inserted.
1727 absolute Absolute path, if possible with ~ for home directory.
1728 noabbrev Absolute path, no abbreviation of home directory.
1729 adaptive Use relative path for files in the current directory and sub-
1730 directories of it. For other files, use an absolute path."
1731 :group 'org-link
1732 :type '(choice
1733 (const relative)
1734 (const absolute)
1735 (const noabbrev)
1736 (const adaptive)))
1738 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1739 "Types of links that should be activated in Org-mode files.
1740 This is a list of symbols, each leading to the activation of a certain link
1741 type. In principle, it does not hurt to turn on most link types - there may
1742 be a small gain when turning off unused link types. The types are:
1744 bracket The recommended [[link][description]] or [[link]] links with hiding.
1745 angle Links in angular brackets that may contain whitespace like
1746 <bbdb:Carsten Dominik>.
1747 plain Plain links in normal text, no whitespace, like http://google.com.
1748 radio Text that is matched by a radio target, see manual for details.
1749 tag Tag settings in a headline (link to tag search).
1750 date Time stamps (link to calendar).
1751 footnote Footnote labels.
1753 Changing this variable requires a restart of Emacs to become effective."
1754 :group 'org-link
1755 :type '(set :greedy t
1756 (const :tag "Double bracket links" bracket)
1757 (const :tag "Angular bracket links" angle)
1758 (const :tag "Plain text links" plain)
1759 (const :tag "Radio target matches" radio)
1760 (const :tag "Tags" tag)
1761 (const :tag "Timestamps" date)
1762 (const :tag "Footnotes" footnote)))
1764 (defcustom org-make-link-description-function nil
1765 "Function to use for generating link descriptions from links.
1766 When nil, the link location will be used. This function must take
1767 two parameters: the first one is the link, the second one is the
1768 description generated by `org-insert-link'. The function should
1769 return the description to use."
1770 :group 'org-link
1771 :type '(choice (const nil) (function)))
1773 (defgroup org-link-store nil
1774 "Options concerning storing links in Org-mode."
1775 :tag "Org Store Link"
1776 :group 'org-link)
1778 (defcustom org-url-hexify-p t
1779 "When non-nil, hexify URL when creating a link."
1780 :type 'boolean
1781 :version "24.3"
1782 :group 'org-link-store)
1784 (defcustom org-email-link-description-format "Email %c: %.30s"
1785 "Format of the description part of a link to an email or usenet message.
1786 The following %-escapes will be replaced by corresponding information:
1788 %F full \"From\" field
1789 %f name, taken from \"From\" field, address if no name
1790 %T full \"To\" field
1791 %t first name in \"To\" field, address if no name
1792 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1793 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1794 %s subject
1795 %d date
1796 %m message-id.
1798 You may use normal field width specification between the % and the letter.
1799 This is for example useful to limit the length of the subject.
1801 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1802 :group 'org-link-store
1803 :type 'string)
1805 (defcustom org-from-is-user-regexp
1806 (let (r1 r2)
1807 (when (and user-mail-address (not (string= user-mail-address "")))
1808 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1809 (when (and user-full-name (not (string= user-full-name "")))
1810 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1811 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1812 "Regexp matched against the \"From:\" header of an email or usenet message.
1813 It should match if the message is from the user him/herself."
1814 :group 'org-link-store
1815 :type 'regexp)
1817 (defcustom org-context-in-file-links t
1818 "Non-nil means file links from `org-store-link' contain context.
1819 A search string will be added to the file name with :: as separator and
1820 used to find the context when the link is activated by the command
1821 `org-open-at-point'. When this option is t, the entire active region
1822 will be placed in the search string of the file link. If set to a
1823 positive integer, only the first n lines of context will be stored.
1825 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1826 negates this setting for the duration of the command."
1827 :group 'org-link-store
1828 :type '(choice boolean integer))
1830 (defcustom org-keep-stored-link-after-insertion nil
1831 "Non-nil means keep link in list for entire session.
1833 The command `org-store-link' adds a link pointing to the current
1834 location to an internal list. These links accumulate during a session.
1835 The command `org-insert-link' can be used to insert links into any
1836 Org-mode file (offering completion for all stored links). When this
1837 option is nil, every link which has been inserted once using \\[org-insert-link]
1838 will be removed from the list, to make completing the unused links
1839 more efficient."
1840 :group 'org-link-store
1841 :type 'boolean)
1843 (defgroup org-link-follow nil
1844 "Options concerning following links in Org-mode."
1845 :tag "Org Follow Link"
1846 :group 'org-link)
1848 (defcustom org-link-translation-function nil
1849 "Function to translate links with different syntax to Org syntax.
1850 This can be used to translate links created for example by the Planner
1851 or emacs-wiki packages to Org syntax.
1852 The function must accept two parameters, a TYPE containing the link
1853 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1854 which is everything after the link protocol. It should return a cons
1855 with possibly modified values of type and path.
1856 Org contains a function for this, so if you set this variable to
1857 `org-translate-link-from-planner', you should be able follow many
1858 links created by planner."
1859 :group 'org-link-follow
1860 :type '(choice (const nil) (function)))
1862 (defcustom org-follow-link-hook nil
1863 "Hook that is run after a link has been followed."
1864 :group 'org-link-follow
1865 :type 'hook)
1867 (defcustom org-tab-follows-link nil
1868 "Non-nil means on links TAB will follow the link.
1869 Needs to be set before org.el is loaded.
1870 This really should not be used, it does not make sense, and the
1871 implementation is bad."
1872 :group 'org-link-follow
1873 :type 'boolean)
1875 (defcustom org-return-follows-link nil
1876 "Non-nil means on links RET will follow the link.
1877 In tables, the special behavior of RET has precedence."
1878 :group 'org-link-follow
1879 :type 'boolean)
1881 (defcustom org-mouse-1-follows-link
1882 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1883 "Non-nil means mouse-1 on a link will follow the link.
1884 A longer mouse click will still set point. Does not work on XEmacs.
1885 Needs to be set before org.el is loaded."
1886 :group 'org-link-follow
1887 :version "24.4"
1888 :package-version '(Org . "8.3")
1889 :type '(choice
1890 (const :tag "A double click follows the link" double)
1891 (const :tag "Unconditionally follow the link with mouse-1" t)
1892 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1894 (defcustom org-mark-ring-length 4
1895 "Number of different positions to be recorded in the ring.
1896 Changing this requires a restart of Emacs to work correctly."
1897 :group 'org-link-follow
1898 :type 'integer)
1900 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1901 "Non-nil means internal links in Org files must exactly match a headline.
1902 When nil, the link search tries to match a phrase with all words
1903 in the search text."
1904 :group 'org-link-follow
1905 :version "24.1"
1906 :type '(choice
1907 (const :tag "Use fuzzy text search" nil)
1908 (const :tag "Match only exact headline" t)
1909 (const :tag "Match exact headline or query to create it"
1910 query-to-create)))
1912 (defcustom org-link-frame-setup
1913 '((vm . vm-visit-folder-other-frame)
1914 (vm-imap . vm-visit-imap-folder-other-frame)
1915 (gnus . org-gnus-no-new-news)
1916 (file . find-file-other-window)
1917 (wl . wl-other-frame))
1918 "Setup the frame configuration for following links.
1919 When following a link with Emacs, it may often be useful to display
1920 this link in another window or frame. This variable can be used to
1921 set this up for the different types of links.
1922 For VM, use any of
1923 `vm-visit-folder'
1924 `vm-visit-folder-other-window'
1925 `vm-visit-folder-other-frame'
1926 For Gnus, use any of
1927 `gnus'
1928 `gnus-other-frame'
1929 `org-gnus-no-new-news'
1930 For FILE, use any of
1931 `find-file'
1932 `find-file-other-window'
1933 `find-file-other-frame'
1934 For Wanderlust use any of
1935 `wl'
1936 `wl-other-frame'
1937 For the calendar, use the variable `calendar-setup'.
1938 For BBDB, it is currently only possible to display the matches in
1939 another window."
1940 :group 'org-link-follow
1941 :type '(list
1942 (cons (const vm)
1943 (choice
1944 (const vm-visit-folder)
1945 (const vm-visit-folder-other-window)
1946 (const vm-visit-folder-other-frame)))
1947 (cons (const vm-imap)
1948 (choice
1949 (const vm-visit-imap-folder)
1950 (const vm-visit-imap-folder-other-window)
1951 (const vm-visit-imap-folder-other-frame)))
1952 (cons (const gnus)
1953 (choice
1954 (const gnus)
1955 (const gnus-other-frame)
1956 (const org-gnus-no-new-news)))
1957 (cons (const file)
1958 (choice
1959 (const find-file)
1960 (const find-file-other-window)
1961 (const find-file-other-frame)))
1962 (cons (const wl)
1963 (choice
1964 (const wl)
1965 (const wl-other-frame)))))
1967 (defcustom org-display-internal-link-with-indirect-buffer nil
1968 "Non-nil means use indirect buffer to display infile links.
1969 Activating internal links (from one location in a file to another location
1970 in the same file) normally just jumps to the location. When the link is
1971 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1972 is displayed in
1973 another window. When this option is set, the other window actually displays
1974 an indirect buffer clone of the current buffer, to avoid any visibility
1975 changes to the current buffer."
1976 :group 'org-link-follow
1977 :type 'boolean)
1979 (defcustom org-open-non-existing-files nil
1980 "Non-nil means `org-open-file' will open non-existing files.
1981 When nil, an error will be generated.
1982 This variable applies only to external applications because they
1983 might choke on non-existing files. If the link is to a file that
1984 will be opened in Emacs, the variable is ignored."
1985 :group 'org-link-follow
1986 :type 'boolean)
1988 (defcustom org-open-directory-means-index-dot-org nil
1989 "Non-nil means a link to a directory really means to index.org.
1990 When nil, following a directory link will run dired or open a finder/explorer
1991 window on that directory."
1992 :group 'org-link-follow
1993 :type 'boolean)
1995 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1996 "Function and arguments to call for following mailto links.
1997 This is a list with the first element being a Lisp function, and the
1998 remaining elements being arguments to the function. In string arguments,
1999 %a will be replaced by the address, and %s will be replaced by the subject
2000 if one was given like in <mailto:arthur@galaxy.org::this subject>."
2001 :group 'org-link-follow
2002 :type '(choice
2003 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
2004 (const :tag "compose-mail" (compose-mail "%a" "%s"))
2005 (const :tag "message-mail" (message-mail "%a" "%s"))
2006 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
2008 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2009 "Non-nil means ask for confirmation before executing shell links.
2010 Shell links can be dangerous: just think about a link
2012 [[shell:rm -rf ~/*][Google Search]]
2014 This link would show up in your Org-mode document as \"Google Search\",
2015 but really it would remove your entire home directory.
2016 Therefore we advise against setting this variable to nil.
2017 Just change it to `y-or-n-p' if you want to confirm with a
2018 single keystroke rather than having to type \"yes\"."
2019 :group 'org-link-follow
2020 :type '(choice
2021 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2022 (const :tag "with y-or-n (faster)" y-or-n-p)
2023 (const :tag "no confirmation (dangerous)" nil)))
2024 (put 'org-confirm-shell-link-function
2025 'safe-local-variable
2026 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2028 (defcustom org-confirm-shell-link-not-regexp ""
2029 "A regexp to skip confirmation for shell links."
2030 :group 'org-link-follow
2031 :version "24.1"
2032 :type 'regexp)
2034 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2035 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2036 Elisp links can be dangerous: just think about a link
2038 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2040 This link would show up in your Org-mode document as \"Google Search\",
2041 but really it would remove your entire home directory.
2042 Therefore we advise against setting this variable to nil.
2043 Just change it to `y-or-n-p' if you want to confirm with a
2044 single keystroke rather than having to type \"yes\"."
2045 :group 'org-link-follow
2046 :type '(choice
2047 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2048 (const :tag "with y-or-n (faster)" y-or-n-p)
2049 (const :tag "no confirmation (dangerous)" nil)))
2050 (put 'org-confirm-shell-link-function
2051 'safe-local-variable
2052 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2054 (defcustom org-confirm-elisp-link-not-regexp ""
2055 "A regexp to skip confirmation for Elisp links."
2056 :group 'org-link-follow
2057 :version "24.1"
2058 :type 'regexp)
2060 (defconst org-file-apps-defaults-gnu
2061 '((remote . emacs)
2062 (system . mailcap)
2063 (t . mailcap))
2064 "Default file applications on a UNIX or GNU/Linux system.
2065 See `org-file-apps'.")
2067 (defconst org-file-apps-defaults-macosx
2068 '((remote . emacs)
2069 (t . "open %s")
2070 (system . "open %s")
2071 ("ps.gz" . "gv %s")
2072 ("eps.gz" . "gv %s")
2073 ("dvi" . "xdvi %s")
2074 ("fig" . "xfig %s"))
2075 "Default file applications on a MacOS X system.
2076 The system \"open\" is known as a default, but we use X11 applications
2077 for some files for which the OS does not have a good default.
2078 See `org-file-apps'.")
2080 (defconst org-file-apps-defaults-windowsnt
2081 (list
2082 '(remote . emacs)
2083 (cons t
2084 (list (if (featurep 'xemacs)
2085 'mswindows-shell-execute
2086 'w32-shell-execute)
2087 "open" 'file))
2088 (cons 'system
2089 (list (if (featurep 'xemacs)
2090 'mswindows-shell-execute
2091 'w32-shell-execute)
2092 "open" 'file)))
2093 "Default file applications on a Windows NT system.
2094 The system \"open\" is used for most files.
2095 See `org-file-apps'.")
2097 (defcustom org-file-apps
2098 '((auto-mode . emacs)
2099 ("\\.mm\\'" . default)
2100 ("\\.x?html?\\'" . default)
2101 ("\\.pdf\\'" . default))
2102 "External applications for opening `file:path' items in a document.
2103 Org-mode uses system defaults for different file types, but
2104 you can use this variable to set the application for a given file
2105 extension. The entries in this list are cons cells where the car identifies
2106 files and the cdr the corresponding command. Possible values for the
2107 file identifier are
2108 \"string\" A string as a file identifier can be interpreted in different
2109 ways, depending on its contents:
2111 - Alphanumeric characters only:
2112 Match links with this file extension.
2113 Example: (\"pdf\" . \"evince %s\")
2114 to open PDFs with evince.
2116 - Regular expression: Match links where the
2117 filename matches the regexp. If you want to
2118 use groups here, use shy groups.
2120 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2121 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2122 to open *.html and *.xhtml with firefox.
2124 - Regular expression which contains (non-shy) groups:
2125 Match links where the whole link, including \"::\", and
2126 anything after that, matches the regexp.
2127 In a custom command string, %1, %2, etc. are replaced with
2128 the parts of the link that were matched by the groups.
2129 For backwards compatibility, if a command string is given
2130 that does not use any of the group matches, this case is
2131 handled identically to the second one (i.e. match against
2132 file name only).
2133 In a custom lisp form, you can access the group matches with
2134 (match-string n link).
2136 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2137 to open [[file:document.pdf::5]] with evince at page 5.
2139 `directory' Matches a directory
2140 `remote' Matches a remote file, accessible through tramp or efs.
2141 Remote files most likely should be visited through Emacs
2142 because external applications cannot handle such paths.
2143 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2144 so all files Emacs knows how to handle. Using this with
2145 command `emacs' will open most files in Emacs. Beware that this
2146 will also open html files inside Emacs, unless you add
2147 (\"html\" . default) to the list as well.
2148 t Default for files not matched by any of the other options.
2149 `system' The system command to open files, like `open' on Windows
2150 and Mac OS X, and mailcap under GNU/Linux. This is the command
2151 that will be selected if you call `C-c C-o' with a double
2152 \\[universal-argument] \\[universal-argument] prefix.
2154 Possible values for the command are:
2155 `emacs' The file will be visited by the current Emacs process.
2156 `default' Use the default application for this file type, which is the
2157 association for t in the list, most likely in the system-specific
2158 part.
2159 This can be used to overrule an unwanted setting in the
2160 system-specific variable.
2161 `system' Use the system command for opening files, like \"open\".
2162 This command is specified by the entry whose car is `system'.
2163 Most likely, the system-specific version of this variable
2164 does define this command, but you can overrule/replace it
2165 here.
2166 string A command to be executed by a shell; %s will be replaced
2167 by the path to the file.
2168 sexp A Lisp form which will be evaluated. The file path will
2169 be available in the Lisp variable `file'.
2170 For more examples, see the system specific constants
2171 `org-file-apps-defaults-macosx'
2172 `org-file-apps-defaults-windowsnt'
2173 `org-file-apps-defaults-gnu'."
2174 :group 'org-link-follow
2175 :type '(repeat
2176 (cons (choice :value ""
2177 (string :tag "Extension")
2178 (const :tag "System command to open files" system)
2179 (const :tag "Default for unrecognized files" t)
2180 (const :tag "Remote file" remote)
2181 (const :tag "Links to a directory" directory)
2182 (const :tag "Any files that have Emacs modes"
2183 auto-mode))
2184 (choice :value ""
2185 (const :tag "Visit with Emacs" emacs)
2186 (const :tag "Use default" default)
2187 (const :tag "Use the system command" system)
2188 (string :tag "Command")
2189 (sexp :tag "Lisp form")))))
2191 (defcustom org-doi-server-url "http://dx.doi.org/"
2192 "The URL of the DOI server."
2193 :type 'string
2194 :version "24.3"
2195 :group 'org-link-follow)
2197 (defgroup org-refile nil
2198 "Options concerning refiling entries in Org-mode."
2199 :tag "Org Refile"
2200 :group 'org)
2202 (defcustom org-directory "~/org"
2203 "Directory with org files.
2204 This is just a default location to look for Org files. There is no need
2205 at all to put your files into this directory. It is only used in the
2206 following situations:
2208 1. When a capture template specifies a target file that is not an
2209 absolute path. The path will then be interpreted relative to
2210 `org-directory'
2211 2. When a capture note is filed away in an interactive way (when exiting the
2212 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2213 with `org-directory' as the default path."
2214 :group 'org-refile
2215 :group 'org-capture
2216 :type 'directory)
2218 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2219 "Default target for storing notes.
2220 Used as a fall back file for org-capture.el, for templates that
2221 do not specify a target file."
2222 :group 'org-refile
2223 :group 'org-capture
2224 :type '(choice
2225 (const :tag "Default from remember-data-file" nil)
2226 file))
2228 (defcustom org-goto-interface 'outline
2229 "The default interface to be used for `org-goto'.
2230 Allowed values are:
2231 outline The interface shows an outline of the relevant file
2232 and the correct heading is found by moving through
2233 the outline or by searching with incremental search.
2234 outline-path-completion Headlines in the current buffer are offered via
2235 completion. This is the interface also used by
2236 the refile command."
2237 :group 'org-refile
2238 :type '(choice
2239 (const :tag "Outline" outline)
2240 (const :tag "Outline-path-completion" outline-path-completion)))
2242 (defcustom org-goto-max-level 5
2243 "Maximum target level when running `org-goto' with refile interface."
2244 :group 'org-refile
2245 :type 'integer)
2247 (defcustom org-reverse-note-order nil
2248 "Non-nil means store new notes at the beginning of a file or entry.
2249 When nil, new notes will be filed to the end of a file or entry.
2250 This can also be a list with cons cells of regular expressions that
2251 are matched against file names, and values."
2252 :group 'org-capture
2253 :group 'org-refile
2254 :type '(choice
2255 (const :tag "Reverse always" t)
2256 (const :tag "Reverse never" nil)
2257 (repeat :tag "By file name regexp"
2258 (cons regexp boolean))))
2260 (defcustom org-log-refile nil
2261 "Information to record when a task is refiled.
2263 Possible values are:
2265 nil Don't add anything
2266 time Add a time stamp to the task
2267 note Prompt for a note and add it with template `org-log-note-headings'
2269 This option can also be set with on a per-file-basis with
2271 #+STARTUP: nologrefile
2272 #+STARTUP: logrefile
2273 #+STARTUP: lognoterefile
2275 You can have local logging settings for a subtree by setting the LOGGING
2276 property to one or more of these keywords.
2278 When bulk-refiling from the agenda, the value `note' is forbidden and
2279 will temporarily be changed to `time'."
2280 :group 'org-refile
2281 :group 'org-progress
2282 :version "24.1"
2283 :type '(choice
2284 (const :tag "No logging" nil)
2285 (const :tag "Record timestamp" time)
2286 (const :tag "Record timestamp with note." note)))
2288 (defcustom org-refile-targets nil
2289 "Targets for refiling entries with \\[org-refile].
2290 This is a list of cons cells. Each cell contains:
2291 - a specification of the files to be considered, either a list of files,
2292 or a symbol whose function or variable value will be used to retrieve
2293 a file name or a list of file names. If you use `org-agenda-files' for
2294 that, all agenda files will be scanned for targets. Nil means consider
2295 headings in the current buffer.
2296 - A specification of how to find candidate refile targets. This may be
2297 any of:
2298 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2299 This tag has to be present in all target headlines, inheritance will
2300 not be considered.
2301 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2302 todo keyword.
2303 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2304 headlines that are refiling targets.
2305 - a cons cell (:level . N). Any headline of level N is considered a target.
2306 Note that, when `org-odd-levels-only' is set, level corresponds to
2307 order in hierarchy, not to the number of stars.
2308 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2309 Note that, when `org-odd-levels-only' is set, level corresponds to
2310 order in hierarchy, not to the number of stars.
2312 Each element of this list generates a set of possible targets.
2313 The union of these sets is presented (with completion) to
2314 the user by `org-refile'.
2316 You can set the variable `org-refile-target-verify-function' to a function
2317 to verify each headline found by the simple criteria above.
2319 When this variable is nil, all top-level headlines in the current buffer
2320 are used, equivalent to the value `((nil . (:level . 1))'."
2321 :group 'org-refile
2322 :type '(repeat
2323 (cons
2324 (choice :value org-agenda-files
2325 (const :tag "All agenda files" org-agenda-files)
2326 (const :tag "Current buffer" nil)
2327 (function) (variable) (file))
2328 (choice :tag "Identify target headline by"
2329 (cons :tag "Specific tag" (const :value :tag) (string))
2330 (cons :tag "TODO keyword" (const :value :todo) (string))
2331 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2332 (cons :tag "Level number" (const :value :level) (integer))
2333 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2335 (defcustom org-refile-target-verify-function nil
2336 "Function to verify if the headline at point should be a refile target.
2337 The function will be called without arguments, with point at the
2338 beginning of the headline. It should return t and leave point
2339 where it is if the headline is a valid target for refiling.
2341 If the target should not be selected, the function must return nil.
2342 In addition to this, it may move point to a place from where the search
2343 should be continued. For example, the function may decide that the entire
2344 subtree of the current entry should be excluded and move point to the end
2345 of the subtree."
2346 :group 'org-refile
2347 :type '(choice
2348 (const nil)
2349 (function)))
2351 (defcustom org-refile-use-cache nil
2352 "Non-nil means cache refile targets to speed up the process.
2353 The cache for a particular file will be updated automatically when
2354 the buffer has been killed, or when any of the marker used for flagging
2355 refile targets no longer points at a live buffer.
2356 If you have added new entries to a buffer that might themselves be targets,
2357 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2358 find that easier, `C-u C-u C-u C-c C-w'."
2359 :group 'org-refile
2360 :version "24.1"
2361 :type 'boolean)
2363 (defcustom org-refile-use-outline-path nil
2364 "Non-nil means provide refile targets as paths.
2365 So a level 3 headline will be available as level1/level2/level3.
2367 When the value is `file', also include the file name (without directory)
2368 into the path. In this case, you can also stop the completion after
2369 the file name, to get entries inserted as top level in the file.
2371 When `full-file-path', include the full file path."
2372 :group 'org-refile
2373 :type '(choice
2374 (const :tag "Not" nil)
2375 (const :tag "Yes" t)
2376 (const :tag "Start with file name" file)
2377 (const :tag "Start with full file path" full-file-path)))
2379 (defcustom org-outline-path-complete-in-steps t
2380 "Non-nil means complete the outline path in hierarchical steps.
2381 When Org-mode uses the refile interface to select an outline path
2382 \(see variable `org-refile-use-outline-path'), the completion of
2383 the path can be done is a single go, or if can be done in steps down
2384 the headline hierarchy. Going in steps is probably the best if you
2385 do not use a special completion package like `ido' or `icicles'.
2386 However, when using these packages, going in one step can be very
2387 fast, while still showing the whole path to the entry."
2388 :group 'org-refile
2389 :type 'boolean)
2391 (defcustom org-refile-allow-creating-parent-nodes nil
2392 "Non-nil means allow to create new nodes as refile targets.
2393 New nodes are then created by adding \"/new node name\" to the completion
2394 of an existing node. When the value of this variable is `confirm',
2395 new node creation must be confirmed by the user (recommended).
2396 When nil, the completion must match an existing entry.
2398 Note that, if the new heading is not seen by the criteria
2399 listed in `org-refile-targets', multiple instances of the same
2400 heading would be created by trying again to file under the new
2401 heading."
2402 :group 'org-refile
2403 :type '(choice
2404 (const :tag "Never" nil)
2405 (const :tag "Always" t)
2406 (const :tag "Prompt for confirmation" confirm)))
2408 (defcustom org-refile-active-region-within-subtree nil
2409 "Non-nil means also refile active region within a subtree.
2411 By default `org-refile' doesn't allow refiling regions if they
2412 don't contain a set of subtrees, but it might be convenient to
2413 do so sometimes: in that case, the first line of the region is
2414 converted to a headline before refiling."
2415 :group 'org-refile
2416 :version "24.1"
2417 :type 'boolean)
2419 (defgroup org-todo nil
2420 "Options concerning TODO items in Org-mode."
2421 :tag "Org TODO"
2422 :group 'org)
2424 (defgroup org-progress nil
2425 "Options concerning Progress logging in Org-mode."
2426 :tag "Org Progress"
2427 :group 'org-time)
2429 (defvar org-todo-interpretation-widgets
2430 '((:tag "Sequence (cycling hits every state)" sequence)
2431 (:tag "Type (cycling directly to DONE)" type))
2432 "The available interpretation symbols for customizing `org-todo-keywords'.
2433 Interested libraries should add to this list.")
2435 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2436 "List of TODO entry keyword sequences and their interpretation.
2437 \\<org-mode-map>This is a list of sequences.
2439 Each sequence starts with a symbol, either `sequence' or `type',
2440 indicating if the keywords should be interpreted as a sequence of
2441 action steps, or as different types of TODO items. The first
2442 keywords are states requiring action - these states will select a headline
2443 for inclusion into the global TODO list Org-mode produces. If one of
2444 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2445 signify that no further action is necessary. If \"|\" is not found,
2446 the last keyword is treated as the only DONE state of the sequence.
2448 The command \\[org-todo] cycles an entry through these states, and one
2449 additional state where no keyword is present. For details about this
2450 cycling, see the manual.
2452 TODO keywords and interpretation can also be set on a per-file basis with
2453 the special #+SEQ_TODO and #+TYP_TODO lines.
2455 Each keyword can optionally specify a character for fast state selection
2456 \(in combination with the variable `org-use-fast-todo-selection')
2457 and specifiers for state change logging, using the same syntax that
2458 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2459 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2460 indicates to record a time stamp each time this state is selected.
2462 Each keyword may also specify if a timestamp or a note should be
2463 recorded when entering or leaving the state, by adding additional
2464 characters in the parenthesis after the keyword. This looks like this:
2465 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2466 record only the time of the state change. With X and Y being either
2467 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2468 Y when leaving the state if and only if the *target* state does not
2469 define X. You may omit any of the fast-selection key or X or /Y,
2470 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2472 For backward compatibility, this variable may also be just a list
2473 of keywords. In this case the interpretation (sequence or type) will be
2474 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2475 :group 'org-todo
2476 :group 'org-keywords
2477 :type '(choice
2478 (repeat :tag "Old syntax, just keywords"
2479 (string :tag "Keyword"))
2480 (repeat :tag "New syntax"
2481 (cons
2482 (choice
2483 :tag "Interpretation"
2484 ;;Quick and dirty way to see
2485 ;;`org-todo-interpretations'. This takes the
2486 ;;place of item arguments
2487 :convert-widget
2488 (lambda (widget)
2489 (widget-put widget
2490 :args (mapcar
2491 #'(lambda (x)
2492 (widget-convert
2493 (cons 'const x)))
2494 org-todo-interpretation-widgets))
2495 widget))
2496 (repeat
2497 (string :tag "Keyword"))))))
2499 (defvar org-todo-keywords-1 nil
2500 "All TODO and DONE keywords active in a buffer.")
2501 (make-variable-buffer-local 'org-todo-keywords-1)
2502 (defvar org-todo-keywords-for-agenda nil)
2503 (defvar org-done-keywords-for-agenda nil)
2504 (defvar org-todo-keyword-alist-for-agenda nil)
2505 (defvar org-tag-alist-for-agenda nil
2506 "Alist of all tags from all agenda files.")
2507 (defvar org-tag-groups-alist-for-agenda nil
2508 "Alist of all groups tags from all current agenda files.")
2509 (defvar org-tag-groups-alist nil)
2510 (make-variable-buffer-local 'org-tag-groups-alist)
2511 (defvar org-agenda-contributing-files nil)
2512 (defvar org-not-done-keywords nil)
2513 (make-variable-buffer-local 'org-not-done-keywords)
2514 (defvar org-done-keywords nil)
2515 (make-variable-buffer-local 'org-done-keywords)
2516 (defvar org-todo-heads nil)
2517 (make-variable-buffer-local 'org-todo-heads)
2518 (defvar org-todo-sets nil)
2519 (make-variable-buffer-local 'org-todo-sets)
2520 (defvar org-todo-log-states nil)
2521 (make-variable-buffer-local 'org-todo-log-states)
2522 (defvar org-todo-kwd-alist nil)
2523 (make-variable-buffer-local 'org-todo-kwd-alist)
2524 (defvar org-todo-key-alist nil)
2525 (make-variable-buffer-local 'org-todo-key-alist)
2526 (defvar org-todo-key-trigger nil)
2527 (make-variable-buffer-local 'org-todo-key-trigger)
2529 (defcustom org-todo-interpretation 'sequence
2530 "Controls how TODO keywords are interpreted.
2531 This variable is in principle obsolete and is only used for
2532 backward compatibility, if the interpretation of todo keywords is
2533 not given already in `org-todo-keywords'. See that variable for
2534 more information."
2535 :group 'org-todo
2536 :group 'org-keywords
2537 :type '(choice (const sequence)
2538 (const type)))
2540 (defcustom org-use-fast-todo-selection t
2541 "Non-nil means use the fast todo selection scheme with C-c C-t.
2542 This variable describes if and under what circumstances the cycling
2543 mechanism for TODO keywords will be replaced by a single-key, direct
2544 selection scheme.
2546 When nil, fast selection is never used.
2548 When the symbol `prefix', it will be used when `org-todo' is called
2549 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2550 `C-u t' in an agenda buffer.
2552 When t, fast selection is used by default. In this case, the prefix
2553 argument forces cycling instead.
2555 In all cases, the special interface is only used if access keys have
2556 actually been assigned by the user, i.e. if keywords in the configuration
2557 are followed by a letter in parenthesis, like TODO(t)."
2558 :group 'org-todo
2559 :type '(choice
2560 (const :tag "Never" nil)
2561 (const :tag "By default" t)
2562 (const :tag "Only with C-u C-c C-t" prefix)))
2564 (defcustom org-provide-todo-statistics t
2565 "Non-nil means update todo statistics after insert and toggle.
2566 ALL-HEADLINES means update todo statistics by including headlines
2567 with no TODO keyword as well, counting them as not done.
2568 A list of TODO keywords means the same, but skip keywords that are
2569 not in this list.
2570 When set to a list of two lists, the first list contains keywords
2571 to consider as TODO keywords, the second list contains keywords
2572 to consider as DONE keywords.
2574 When this is set, todo statistics is updated in the parent of the
2575 current entry each time a todo state is changed."
2576 :group 'org-todo
2577 :type '(choice
2578 (const :tag "Yes, only for TODO entries" t)
2579 (const :tag "Yes, including all entries" all-headlines)
2580 (repeat :tag "Yes, for TODOs in this list"
2581 (string :tag "TODO keyword"))
2582 (list :tag "Yes, for TODOs and DONEs in these lists"
2583 (repeat (string :tag "TODO keyword"))
2584 (repeat (string :tag "DONE keyword")))
2585 (other :tag "No TODO statistics" nil)))
2587 (defcustom org-hierarchical-todo-statistics t
2588 "Non-nil means TODO statistics covers just direct children.
2589 When nil, all entries in the subtree are considered.
2590 This has only an effect if `org-provide-todo-statistics' is set.
2591 To set this to nil for only a single subtree, use a COOKIE_DATA
2592 property and include the word \"recursive\" into the value."
2593 :group 'org-todo
2594 :type 'boolean)
2596 (defcustom org-after-todo-state-change-hook nil
2597 "Hook which is run after the state of a TODO item was changed.
2598 The new state (a string with a TODO keyword, or nil) is available in the
2599 Lisp variable `org-state'."
2600 :group 'org-todo
2601 :type 'hook)
2603 (defvar org-blocker-hook nil
2604 "Hook for functions that are allowed to block a state change.
2606 Functions in this hook should not modify the buffer.
2607 Each function gets as its single argument a property list,
2608 see `org-trigger-hook' for more information about this list.
2610 If any of the functions in this hook returns nil, the state change
2611 is blocked.")
2613 (defvar org-trigger-hook nil
2614 "Hook for functions that are triggered by a state change.
2616 Each function gets as its single argument a property list with at
2617 least the following elements:
2619 (:type type-of-change :position pos-at-entry-start
2620 :from old-state :to new-state)
2622 Depending on the type, more properties may be present.
2624 This mechanism is currently implemented for:
2626 TODO state changes
2627 ------------------
2628 :type todo-state-change
2629 :from previous state (keyword as a string), or nil, or a symbol
2630 'todo' or 'done', to indicate the general type of state.
2631 :to new state, like in :from")
2633 (defcustom org-enforce-todo-dependencies nil
2634 "Non-nil means undone TODO entries will block switching the parent to DONE.
2635 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2636 be blocked if any prior sibling is not yet done.
2637 Finally, if the parent is blocked because of ordered siblings of its own,
2638 the child will also be blocked."
2639 :set (lambda (var val)
2640 (set var val)
2641 (if val
2642 (add-hook 'org-blocker-hook
2643 'org-block-todo-from-children-or-siblings-or-parent)
2644 (remove-hook 'org-blocker-hook
2645 'org-block-todo-from-children-or-siblings-or-parent)))
2646 :group 'org-todo
2647 :type 'boolean)
2649 (defcustom org-enforce-todo-checkbox-dependencies nil
2650 "Non-nil means unchecked boxes will block switching the parent to DONE.
2651 When this is nil, checkboxes have no influence on switching TODO states.
2652 When non-nil, you first need to check off all check boxes before the TODO
2653 entry can be switched to DONE.
2654 This variable needs to be set before org.el is loaded, and you need to
2655 restart Emacs after a change to make the change effective. The only way
2656 to change is while Emacs is running is through the customize interface."
2657 :set (lambda (var val)
2658 (set var val)
2659 (if val
2660 (add-hook 'org-blocker-hook
2661 'org-block-todo-from-checkboxes)
2662 (remove-hook 'org-blocker-hook
2663 'org-block-todo-from-checkboxes)))
2664 :group 'org-todo
2665 :type 'boolean)
2667 (defcustom org-treat-insert-todo-heading-as-state-change nil
2668 "Non-nil means inserting a TODO heading is treated as state change.
2669 So when the command \\[org-insert-todo-heading] is used, state change
2670 logging will apply if appropriate. When nil, the new TODO item will
2671 be inserted directly, and no logging will take place."
2672 :group 'org-todo
2673 :type 'boolean)
2675 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2676 "Non-nil means switching TODO states with S-cursor counts as state change.
2677 This is the default behavior. However, setting this to nil allows a
2678 convenient way to select a TODO state and bypass any logging associated
2679 with that."
2680 :group 'org-todo
2681 :type 'boolean)
2683 (defcustom org-todo-state-tags-triggers nil
2684 "Tag changes that should be triggered by TODO state changes.
2685 This is a list. Each entry is
2687 (state-change (tag . flag) .......)
2689 State-change can be a string with a state, and empty string to indicate the
2690 state that has no TODO keyword, or it can be one of the symbols `todo'
2691 or `done', meaning any not-done or done state, respectively."
2692 :group 'org-todo
2693 :group 'org-tags
2694 :type '(repeat
2695 (cons (choice :tag "When changing to"
2696 (const :tag "Not-done state" todo)
2697 (const :tag "Done state" done)
2698 (string :tag "State"))
2699 (repeat
2700 (cons :tag "Tag action"
2701 (string :tag "Tag")
2702 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2704 (defcustom org-log-done nil
2705 "Information to record when a task moves to the DONE state.
2707 Possible values are:
2709 nil Don't add anything, just change the keyword
2710 time Add a time stamp to the task
2711 note Prompt for a note and add it with template `org-log-note-headings'
2713 This option can also be set with on a per-file-basis with
2715 #+STARTUP: nologdone
2716 #+STARTUP: logdone
2717 #+STARTUP: lognotedone
2719 You can have local logging settings for a subtree by setting the LOGGING
2720 property to one or more of these keywords."
2721 :group 'org-todo
2722 :group 'org-progress
2723 :type '(choice
2724 (const :tag "No logging" nil)
2725 (const :tag "Record CLOSED timestamp" time)
2726 (const :tag "Record CLOSED timestamp with note." note)))
2728 ;; Normalize old uses of org-log-done.
2729 (cond
2730 ((eq org-log-done t) (setq org-log-done 'time))
2731 ((and (listp org-log-done) (memq 'done org-log-done))
2732 (setq org-log-done 'note)))
2734 (defcustom org-log-reschedule nil
2735 "Information to record when the scheduling date of a tasks is modified.
2737 Possible values are:
2739 nil Don't add anything, just change the date
2740 time Add a time stamp to the task
2741 note Prompt for a note and add it with template `org-log-note-headings'
2743 This option can also be set with on a per-file-basis with
2745 #+STARTUP: nologreschedule
2746 #+STARTUP: logreschedule
2747 #+STARTUP: lognotereschedule"
2748 :group 'org-todo
2749 :group 'org-progress
2750 :type '(choice
2751 (const :tag "No logging" nil)
2752 (const :tag "Record timestamp" time)
2753 (const :tag "Record timestamp with note." note)))
2755 (defcustom org-log-redeadline nil
2756 "Information to record when the deadline date of a tasks is modified.
2758 Possible values are:
2760 nil Don't add anything, just change the date
2761 time Add a time stamp to the task
2762 note Prompt for a note and add it with template `org-log-note-headings'
2764 This option can also be set with on a per-file-basis with
2766 #+STARTUP: nologredeadline
2767 #+STARTUP: logredeadline
2768 #+STARTUP: lognoteredeadline
2770 You can have local logging settings for a subtree by setting the LOGGING
2771 property to one or more of these keywords."
2772 :group 'org-todo
2773 :group 'org-progress
2774 :type '(choice
2775 (const :tag "No logging" nil)
2776 (const :tag "Record timestamp" time)
2777 (const :tag "Record timestamp with note." note)))
2779 (defcustom org-log-note-clock-out nil
2780 "Non-nil means record a note when clocking out of an item.
2781 This can also be configured on a per-file basis by adding one of
2782 the following lines anywhere in the buffer:
2784 #+STARTUP: lognoteclock-out
2785 #+STARTUP: nolognoteclock-out"
2786 :group 'org-todo
2787 :group 'org-progress
2788 :type 'boolean)
2790 (defcustom org-log-done-with-time t
2791 "Non-nil means the CLOSED time stamp will contain date and time.
2792 When nil, only the date will be recorded."
2793 :group 'org-progress
2794 :type 'boolean)
2796 (defcustom org-log-note-headings
2797 '((done . "CLOSING NOTE %t")
2798 (state . "State %-12s from %-12S %t")
2799 (note . "Note taken on %t")
2800 (reschedule . "Rescheduled from %S on %t")
2801 (delschedule . "Not scheduled, was %S on %t")
2802 (redeadline . "New deadline from %S on %t")
2803 (deldeadline . "Removed deadline, was %S on %t")
2804 (refile . "Refiled on %t")
2805 (clock-out . ""))
2806 "Headings for notes added to entries.
2807 The value is an alist, with the car being a symbol indicating the note
2808 context, and the cdr is the heading to be used. The heading may also be the
2809 empty string.
2810 %t in the heading will be replaced by a time stamp.
2811 %T will be an active time stamp instead the default inactive one
2812 %d will be replaced by a short-format time stamp.
2813 %D will be replaced by an active short-format time stamp.
2814 %s will be replaced by the new TODO state, in double quotes.
2815 %S will be replaced by the old TODO state, in double quotes.
2816 %u will be replaced by the user name.
2817 %U will be replaced by the full user name.
2819 In fact, it is not a good idea to change the `state' entry, because
2820 agenda log mode depends on the format of these entries."
2821 :group 'org-todo
2822 :group 'org-progress
2823 :type '(list :greedy t
2824 (cons (const :tag "Heading when closing an item" done) string)
2825 (cons (const :tag
2826 "Heading when changing todo state (todo sequence only)"
2827 state) string)
2828 (cons (const :tag "Heading when just taking a note" note) string)
2829 (cons (const :tag "Heading when rescheduling" reschedule) string)
2830 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2831 (cons (const :tag "Heading when changing deadline" redeadline) string)
2832 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2833 (cons (const :tag "Heading when refiling" refile) string)
2834 (cons (const :tag "Heading when clocking out" clock-out) string)))
2836 (unless (assq 'note org-log-note-headings)
2837 (push '(note . "%t") org-log-note-headings))
2839 (defcustom org-log-into-drawer nil
2840 "Non-nil means insert state change notes and time stamps into a drawer.
2841 When nil, state changes notes will be inserted after the headline and
2842 any scheduling and clock lines, but not inside a drawer.
2844 The value of this variable should be the name of the drawer to use.
2845 LOGBOOK is proposed as the default drawer for this purpose, you can
2846 also set this to a string to define the drawer of your choice.
2848 A value of t is also allowed, representing \"LOGBOOK\".
2850 A value of t or nil can also be set with on a per-file-basis with
2852 #+STARTUP: logdrawer
2853 #+STARTUP: nologdrawer
2855 If this variable is set, `org-log-state-notes-insert-after-drawers'
2856 will be ignored.
2858 You can set the property LOG_INTO_DRAWER to overrule this setting for
2859 a subtree."
2860 :group 'org-todo
2861 :group 'org-progress
2862 :type '(choice
2863 (const :tag "Not into a drawer" nil)
2864 (const :tag "LOGBOOK" t)
2865 (string :tag "Other")))
2867 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2869 (defun org-log-into-drawer ()
2870 "Return the value of `org-log-into-drawer', but let properties overrule.
2871 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2872 used instead of the default value."
2873 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2874 (cond
2875 ((not p) org-log-into-drawer)
2876 ((equal p "nil") nil)
2877 ((equal p "t") "LOGBOOK")
2878 (t p))))
2880 (defcustom org-log-state-notes-insert-after-drawers nil
2881 "Non-nil means insert state change notes after any drawers in entry.
2882 Only the drawers that *immediately* follow the headline and the
2883 deadline/scheduled line are skipped.
2884 When nil, insert notes right after the heading and perhaps the line
2885 with deadline/scheduling if present.
2887 This variable will have no effect if `org-log-into-drawer' is
2888 set."
2889 :group 'org-todo
2890 :group 'org-progress
2891 :type 'boolean)
2893 (defcustom org-log-states-order-reversed t
2894 "Non-nil means the latest state note will be directly after heading.
2895 When nil, the state change notes will be ordered according to time.
2897 This option can also be set with on a per-file-basis with
2899 #+STARTUP: logstatesreversed
2900 #+STARTUP: nologstatesreversed"
2901 :group 'org-todo
2902 :group 'org-progress
2903 :type 'boolean)
2905 (defcustom org-todo-repeat-to-state nil
2906 "The TODO state to which a repeater should return the repeating task.
2907 By default this is the first task in a TODO sequence, or the previous state
2908 in a TODO_TYP set. But you can specify another task here.
2909 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2910 :group 'org-todo
2911 :version "24.1"
2912 :type '(choice (const :tag "Head of sequence" nil)
2913 (string :tag "Specific state")))
2915 (defcustom org-log-repeat 'time
2916 "Non-nil means record moving through the DONE state when triggering repeat.
2917 An auto-repeating task is immediately switched back to TODO when
2918 marked DONE. If you are not logging state changes (by adding \"@\"
2919 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2920 record a closing note, there will be no record of the task moving
2921 through DONE. This variable forces taking a note anyway.
2923 nil Don't force a record
2924 time Record a time stamp
2925 note Prompt for a note and add it with template `org-log-note-headings'
2927 This option can also be set with on a per-file-basis with
2929 #+STARTUP: nologrepeat
2930 #+STARTUP: logrepeat
2931 #+STARTUP: lognoterepeat
2933 You can have local logging settings for a subtree by setting the LOGGING
2934 property to one or more of these keywords."
2935 :group 'org-todo
2936 :group 'org-progress
2937 :type '(choice
2938 (const :tag "Don't force a record" nil)
2939 (const :tag "Force recording the DONE state" time)
2940 (const :tag "Force recording a note with the DONE state" note)))
2943 (defgroup org-priorities nil
2944 "Priorities in Org-mode."
2945 :tag "Org Priorities"
2946 :group 'org-todo)
2948 (defcustom org-enable-priority-commands t
2949 "Non-nil means priority commands are active.
2950 When nil, these commands will be disabled, so that you never accidentally
2951 set a priority."
2952 :group 'org-priorities
2953 :type 'boolean)
2955 (defcustom org-highest-priority ?A
2956 "The highest priority of TODO items. A character like ?A, ?B etc.
2957 Must have a smaller ASCII number than `org-lowest-priority'."
2958 :group 'org-priorities
2959 :type 'character)
2961 (defcustom org-lowest-priority ?C
2962 "The lowest priority of TODO items. A character like ?A, ?B etc.
2963 Must have a larger ASCII number than `org-highest-priority'."
2964 :group 'org-priorities
2965 :type 'character)
2967 (defcustom org-default-priority ?B
2968 "The default priority of TODO items.
2969 This is the priority an item gets if no explicit priority is given.
2970 When starting to cycle on an empty priority the first step in the cycle
2971 depends on `org-priority-start-cycle-with-default'. The resulting first
2972 step priority must not exceed the range from `org-highest-priority' to
2973 `org-lowest-priority' which means that `org-default-priority' has to be
2974 in this range exclusive or inclusive the range boundaries. Else the
2975 first step refuses to set the default and the second will fall back
2976 to (depending on the command used) the highest or lowest priority."
2977 :group 'org-priorities
2978 :type 'character)
2980 (defcustom org-priority-start-cycle-with-default t
2981 "Non-nil means start with default priority when starting to cycle.
2982 When this is nil, the first step in the cycle will be (depending on the
2983 command used) one higher or lower than the default priority.
2984 See also `org-default-priority'."
2985 :group 'org-priorities
2986 :type 'boolean)
2988 (defcustom org-get-priority-function nil
2989 "Function to extract the priority from a string.
2990 The string is normally the headline. If this is nil Org computes the
2991 priority from the priority cookie like [#A] in the headline. It returns
2992 an integer, increasing by 1000 for each priority level.
2993 The user can set a different function here, which should take a string
2994 as an argument and return the numeric priority."
2995 :group 'org-priorities
2996 :version "24.1"
2997 :type '(choice
2998 (const nil)
2999 (function)))
3001 (defgroup org-time nil
3002 "Options concerning time stamps and deadlines in Org-mode."
3003 :tag "Org Time"
3004 :group 'org)
3006 (defcustom org-insert-labeled-timestamps-at-point nil
3007 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
3008 When nil, these labeled time stamps are forces into the second line of an
3009 entry, just after the headline. When scheduling from the global TODO list,
3010 the time stamp will always be forced into the second line."
3011 :group 'org-time
3012 :type 'boolean)
3014 (defcustom org-time-stamp-rounding-minutes '(0 5)
3015 "Number of minutes to round time stamps to.
3016 These are two values, the first applies when first creating a time stamp.
3017 The second applies when changing it with the commands `S-up' and `S-down'.
3018 When changing the time stamp, this means that it will change in steps
3019 of N minutes, as given by the second value.
3021 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3022 numbers should be factors of 60, so for example 5, 10, 15.
3024 When this is larger than 1, you can still force an exact time stamp by using
3025 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3026 and by using a prefix arg to `S-up/down' to specify the exact number
3027 of minutes to shift."
3028 :group 'org-time
3029 :get #'(lambda (var) ; Make sure both elements are there
3030 (if (integerp (default-value var))
3031 (list (default-value var) 5)
3032 (default-value var)))
3033 :type '(list
3034 (integer :tag "when inserting times")
3035 (integer :tag "when modifying times")))
3037 ;; Normalize old customizations of this variable.
3038 (when (integerp org-time-stamp-rounding-minutes)
3039 (setq org-time-stamp-rounding-minutes
3040 (list org-time-stamp-rounding-minutes
3041 org-time-stamp-rounding-minutes)))
3043 (defcustom org-display-custom-times nil
3044 "Non-nil means overlay custom formats over all time stamps.
3045 The formats are defined through the variable `org-time-stamp-custom-formats'.
3046 To turn this on on a per-file basis, insert anywhere in the file:
3047 #+STARTUP: customtime"
3048 :group 'org-time
3049 :set 'set-default
3050 :type 'sexp)
3051 (make-variable-buffer-local 'org-display-custom-times)
3053 (defcustom org-time-stamp-custom-formats
3054 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3055 "Custom formats for time stamps. See `format-time-string' for the syntax.
3056 These are overlaid over the default ISO format if the variable
3057 `org-display-custom-times' is set. Time like %H:%M should be at the
3058 end of the second format. The custom formats are also honored by export
3059 commands, if custom time display is turned on at the time of export."
3060 :group 'org-time
3061 :type 'sexp)
3063 (defun org-time-stamp-format (&optional long inactive)
3064 "Get the right format for a time string."
3065 (let ((f (if long (cdr org-time-stamp-formats)
3066 (car org-time-stamp-formats))))
3067 (if inactive
3068 (concat "[" (substring f 1 -1) "]")
3069 f)))
3071 (defcustom org-time-clocksum-format
3072 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3073 "The format string used when creating CLOCKSUM lines.
3074 This is also used when Org mode generates a time duration.
3076 The value can be a single format string containing two
3077 %-sequences, which will be filled with the number of hours and
3078 minutes in that order.
3080 Alternatively, the value can be a plist associating any of the
3081 keys :years, :months, :weeks, :days, :hours or :minutes with
3082 format strings. The time duration is formatted using only the
3083 time components that are needed and concatenating the results.
3084 If a time unit in absent, it falls back to the next smallest
3085 unit.
3087 The keys :require-years, :require-months, :require-days,
3088 :require-weeks, :require-hours, :require-minutes are also
3089 meaningful. A non-nil value for these keys indicates that the
3090 corresponding time component should always be included, even if
3091 its value is 0.
3094 For example,
3096 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3097 :require-minutes t)
3099 means durations longer than a day will be expressed in days,
3100 hours and minutes, and durations less than a day will always be
3101 expressed in hours and minutes (even for durations less than an
3102 hour).
3104 The value
3106 \(:days \"%dd\" :minutes \"%dm\")
3108 means durations longer than a day will be expressed in days and
3109 minutes, and durations less than a day will be expressed entirely
3110 in minutes (even for durations longer than an hour)."
3111 :group 'org-time
3112 :group 'org-clock
3113 :version "24.4"
3114 :package-version '(Org . "8.0")
3115 :type '(choice (string :tag "Format string")
3116 (set :tag "Plist"
3117 (group :inline t (const :tag "Years" :years)
3118 (string :tag "Format string"))
3119 (group :inline t
3120 (const :tag "Always show years" :require-years)
3121 (const t))
3122 (group :inline t (const :tag "Months" :months)
3123 (string :tag "Format string"))
3124 (group :inline t
3125 (const :tag "Always show months" :require-months)
3126 (const t))
3127 (group :inline t (const :tag "Weeks" :weeks)
3128 (string :tag "Format string"))
3129 (group :inline t
3130 (const :tag "Always show weeks" :require-weeks)
3131 (const t))
3132 (group :inline t (const :tag "Days" :days)
3133 (string :tag "Format string"))
3134 (group :inline t
3135 (const :tag "Always show days" :require-days)
3136 (const t))
3137 (group :inline t (const :tag "Hours" :hours)
3138 (string :tag "Format string"))
3139 (group :inline t
3140 (const :tag "Always show hours" :require-hours)
3141 (const t))
3142 (group :inline t (const :tag "Minutes" :minutes)
3143 (string :tag "Format string"))
3144 (group :inline t
3145 (const :tag "Always show minutes" :require-minutes)
3146 (const t)))))
3148 (defcustom org-time-clocksum-use-fractional nil
3149 "When non-nil, \\[org-clock-display] uses fractional times.
3150 See `org-time-clocksum-format' for more on time clock formats."
3151 :group 'org-time
3152 :group 'org-clock
3153 :version "24.3"
3154 :type 'boolean)
3156 (defcustom org-time-clocksum-use-effort-durations nil
3157 "When non-nil, \\[org-clock-display] uses effort durations.
3158 E.g. by default, one day is considered to be a 8 hours effort,
3159 so a task that has been clocked for 16 hours will be displayed
3160 as during 2 days in the clock display or in the clocktable.
3162 See `org-effort-durations' on how to set effort durations
3163 and `org-time-clocksum-format' for more on time clock formats."
3164 :group 'org-time
3165 :group 'org-clock
3166 :version "24.4"
3167 :package-version '(Org . "8.0")
3168 :type 'boolean)
3170 (defcustom org-time-clocksum-fractional-format "%.2f"
3171 "The format string used when creating CLOCKSUM lines,
3172 or when Org mode generates a time duration, if
3173 `org-time-clocksum-use-fractional' is enabled.
3175 The value can be a single format string containing one
3176 %-sequence, which will be filled with the number of hours as
3177 a float.
3179 Alternatively, the value can be a plist associating any of the
3180 keys :years, :months, :weeks, :days, :hours or :minutes with
3181 a format string. The time duration is formatted using the
3182 largest time unit which gives a non-zero integer part. If all
3183 specified formats have zero integer part, the smallest time unit
3184 is used."
3185 :group 'org-time
3186 :type '(choice (string :tag "Format string")
3187 (set (group :inline t (const :tag "Years" :years)
3188 (string :tag "Format string"))
3189 (group :inline t (const :tag "Months" :months)
3190 (string :tag "Format string"))
3191 (group :inline t (const :tag "Weeks" :weeks)
3192 (string :tag "Format string"))
3193 (group :inline t (const :tag "Days" :days)
3194 (string :tag "Format string"))
3195 (group :inline t (const :tag "Hours" :hours)
3196 (string :tag "Format string"))
3197 (group :inline t (const :tag "Minutes" :minutes)
3198 (string :tag "Format string")))))
3200 (defcustom org-deadline-warning-days 14
3201 "Number of days before expiration during which a deadline becomes active.
3202 This variable governs the display in sparse trees and in the agenda.
3203 When 0 or negative, it means use this number (the absolute value of it)
3204 even if a deadline has a different individual lead time specified.
3206 Custom commands can set this variable in the options section."
3207 :group 'org-time
3208 :group 'org-agenda-daily/weekly
3209 :type 'integer)
3211 (defcustom org-scheduled-delay-days 0
3212 "Number of days before a scheduled item becomes active.
3213 This variable governs the display in sparse trees and in the agenda.
3214 The default value (i.e. 0) means: don't delay scheduled item.
3215 When negative, it means use this number (the absolute value of it)
3216 even if a scheduled item has a different individual delay time
3217 specified.
3219 Custom commands can set this variable in the options section."
3220 :group 'org-time
3221 :group 'org-agenda-daily/weekly
3222 :version "24.4"
3223 :package-version '(Org . "8.0")
3224 :type 'integer)
3226 (defcustom org-read-date-prefer-future t
3227 "Non-nil means assume future for incomplete date input from user.
3228 This affects the following situations:
3229 1. The user gives a month but not a year.
3230 For example, if it is April and you enter \"feb 2\", this will be read
3231 as Feb 2, *next* year. \"May 5\", however, will be this year.
3232 2. The user gives a day, but no month.
3233 For example, if today is the 15th, and you enter \"3\", Org-mode will
3234 read this as the third of *next* month. However, if you enter \"17\",
3235 it will be considered as *this* month.
3237 If you set this variable to the symbol `time', then also the following
3238 will work:
3240 3. If the user gives a time.
3241 If the time is before now, it will be interpreted as tomorrow.
3243 Currently none of this works for ISO week specifications.
3245 When this option is nil, the current day, month and year will always be
3246 used as defaults.
3248 See also `org-agenda-jump-prefer-future'."
3249 :group 'org-time
3250 :type '(choice
3251 (const :tag "Never" nil)
3252 (const :tag "Check month and day" t)
3253 (const :tag "Check month, day, and time" time)))
3255 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3256 "Should the agenda jump command prefer the future for incomplete dates?
3257 The default is to do the same as configured in `org-read-date-prefer-future'.
3258 But you can also set a deviating value here.
3259 This may t or nil, or the symbol `org-read-date-prefer-future'."
3260 :group 'org-agenda
3261 :group 'org-time
3262 :version "24.1"
3263 :type '(choice
3264 (const :tag "Use org-read-date-prefer-future"
3265 org-read-date-prefer-future)
3266 (const :tag "Never" nil)
3267 (const :tag "Always" t)))
3269 (defcustom org-read-date-force-compatible-dates t
3270 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3272 Depending on the system Emacs is running on, certain dates cannot
3273 be represented with the type used internally to represent time.
3274 Dates between 1970-1-1 and 2038-1-1 can always be represented
3275 correctly. Some systems allow for earlier dates, some for later,
3276 some for both. One way to find out it to insert any date into an
3277 Org buffer, putting the cursor on the year and hitting S-up and
3278 S-down to test the range.
3280 When this variable is set to t, the date/time prompt will not let
3281 you specify dates outside the 1970-2037 range, so it is certain that
3282 these dates will work in whatever version of Emacs you are
3283 running, and also that you can move a file from one Emacs implementation
3284 to another. WHenever Org is forcing the year for you, it will display
3285 a message and beep.
3287 When this variable is nil, Org will check if the date is
3288 representable in the specific Emacs implementation you are using.
3289 If not, it will force a year, usually the current year, and beep
3290 to remind you. Currently this setting is not recommended because
3291 the likelihood that you will open your Org files in an Emacs that
3292 has limited date range is not negligible.
3294 A workaround for this problem is to use diary sexp dates for time
3295 stamps outside of this range."
3296 :group 'org-time
3297 :version "24.1"
3298 :type 'boolean)
3300 (defcustom org-read-date-display-live t
3301 "Non-nil means display current interpretation of date prompt live.
3302 This display will be in an overlay, in the minibuffer."
3303 :group 'org-time
3304 :type 'boolean)
3306 (defcustom org-read-date-popup-calendar t
3307 "Non-nil means pop up a calendar when prompting for a date.
3308 In the calendar, the date can be selected with mouse-1. However, the
3309 minibuffer will also be active, and you can simply enter the date as well.
3310 When nil, only the minibuffer will be available."
3311 :group 'org-time
3312 :type 'boolean)
3313 (org-defvaralias 'org-popup-calendar-for-date-prompt
3314 'org-read-date-popup-calendar)
3316 (make-obsolete-variable
3317 'org-read-date-minibuffer-setup-hook
3318 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3319 (defcustom org-read-date-minibuffer-setup-hook nil
3320 "Hook to be used to set up keys for the date/time interface.
3321 Add key definitions to `minibuffer-local-map', which will be a
3322 temporary copy.
3324 WARNING: This option is obsolete, you should use
3325 `org-read-date-minibuffer-local-map' to set up keys."
3326 :group 'org-time
3327 :type 'hook)
3329 (defcustom org-extend-today-until 0
3330 "The hour when your day really ends. Must be an integer.
3331 This has influence for the following applications:
3332 - When switching the agenda to \"today\". It it is still earlier than
3333 the time given here, the day recognized as TODAY is actually yesterday.
3334 - When a date is read from the user and it is still before the time given
3335 here, the current date and time will be assumed to be yesterday, 23:59.
3336 Also, timestamps inserted in capture templates follow this rule.
3338 IMPORTANT: This is a feature whose implementation is and likely will
3339 remain incomplete. Really, it is only here because past midnight seems to
3340 be the favorite working time of John Wiegley :-)"
3341 :group 'org-time
3342 :type 'integer)
3344 (defcustom org-use-effective-time nil
3345 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3346 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3347 \"effective time\" of any timestamps between midnight and 8am will be
3348 23:59 of the previous day."
3349 :group 'org-time
3350 :version "24.1"
3351 :type 'boolean)
3353 (defcustom org-use-last-clock-out-time-as-effective-time nil
3354 "When non-nil, use the last clock out time for `org-todo'.
3355 Note that this option has precedence over the combined use of
3356 `org-use-effective-time' and `org-extend-today-until'."
3357 :group 'org-time
3358 :version "24.4"
3359 :package-version '(Org . "8.0")
3360 :type 'boolean)
3362 (defcustom org-edit-timestamp-down-means-later nil
3363 "Non-nil means S-down will increase the time in a time stamp.
3364 When nil, S-up will increase."
3365 :group 'org-time
3366 :type 'boolean)
3368 (defcustom org-calendar-follow-timestamp-change t
3369 "Non-nil means make the calendar window follow timestamp changes.
3370 When a timestamp is modified and the calendar window is visible, it will be
3371 moved to the new date."
3372 :group 'org-time
3373 :type 'boolean)
3375 (defgroup org-tags nil
3376 "Options concerning tags in Org-mode."
3377 :tag "Org Tags"
3378 :group 'org)
3380 (defcustom org-tag-alist nil
3381 "List of tags allowed in Org-mode files.
3382 When this list is nil, Org-mode will base TAG input on what is already in the
3383 buffer.
3384 The value of this variable is an alist, the car of each entry must be a
3385 keyword as a string, the cdr may be a character that is used to select
3386 that tag through the fast-tag-selection interface.
3387 See the manual for details."
3388 :group 'org-tags
3389 :type '(repeat
3390 (choice
3391 (cons (string :tag "Tag name")
3392 (character :tag "Access char"))
3393 (list :tag "Start radio group"
3394 (const :startgroup)
3395 (option (string :tag "Group description")))
3396 (list :tag "Group tags delimiter"
3397 (const :grouptags))
3398 (list :tag "End radio group"
3399 (const :endgroup)
3400 (option (string :tag "Group description")))
3401 (const :tag "New line" (:newline)))))
3403 (defcustom org-tag-persistent-alist nil
3404 "List of tags that will always appear in all Org-mode files.
3405 This is in addition to any in buffer settings or customizations
3406 of `org-tag-alist'.
3407 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3408 The value of this variable is an alist, the car of each entry must be a
3409 keyword as a string, the cdr may be a character that is used to select
3410 that tag through the fast-tag-selection interface.
3411 See the manual for details.
3412 To disable these tags on a per-file basis, insert anywhere in the file:
3413 #+STARTUP: noptag"
3414 :group 'org-tags
3415 :type '(repeat
3416 (choice
3417 (cons (string :tag "Tag name")
3418 (character :tag "Access char"))
3419 (const :tag "Start radio group" (:startgroup))
3420 (const :tag "Group tags delimiter" (:grouptags))
3421 (const :tag "End radio group" (:endgroup))
3422 (const :tag "New line" (:newline)))))
3424 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3425 "If non-nil, always offer completion for all tags of all agenda files.
3426 Instead of customizing this variable directly, you might want to
3427 set it locally for capture buffers, because there no list of
3428 tags in that file can be created dynamically (there are none).
3430 (add-hook 'org-capture-mode-hook
3431 (lambda ()
3432 (set (make-local-variable
3433 'org-complete-tags-always-offer-all-agenda-tags)
3434 t)))"
3435 :group 'org-tags
3436 :version "24.1"
3437 :type 'boolean)
3439 (defvar org-file-tags nil
3440 "List of tags that can be inherited by all entries in the file.
3441 The tags will be inherited if the variable `org-use-tag-inheritance'
3442 says they should be.
3443 This variable is populated from #+FILETAGS lines.")
3445 (defcustom org-use-fast-tag-selection 'auto
3446 "Non-nil means use fast tag selection scheme.
3447 This is a special interface to select and deselect tags with single keys.
3448 When nil, fast selection is never used.
3449 When the symbol `auto', fast selection is used if and only if selection
3450 characters for tags have been configured, either through the variable
3451 `org-tag-alist' or through a #+TAGS line in the buffer.
3452 When t, fast selection is always used and selection keys are assigned
3453 automatically if necessary."
3454 :group 'org-tags
3455 :type '(choice
3456 (const :tag "Always" t)
3457 (const :tag "Never" nil)
3458 (const :tag "When selection characters are configured" auto)))
3460 (defcustom org-fast-tag-selection-single-key nil
3461 "Non-nil means fast tag selection exits after first change.
3462 When nil, you have to press RET to exit it.
3463 During fast tag selection, you can toggle this flag with `C-c'.
3464 This variable can also have the value `expert'. In this case, the window
3465 displaying the tags menu is not even shown, until you press C-c again."
3466 :group 'org-tags
3467 :type '(choice
3468 (const :tag "No" nil)
3469 (const :tag "Yes" t)
3470 (const :tag "Expert" expert)))
3472 (defvar org-fast-tag-selection-include-todo nil
3473 "Non-nil means fast tags selection interface will also offer TODO states.
3474 This is an undocumented feature, you should not rely on it.")
3476 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3477 "The column to which tags should be indented in a headline.
3478 If this number is positive, it specifies the column. If it is negative,
3479 it means that the tags should be flushright to that column. For example,
3480 -80 works well for a normal 80 character screen.
3481 When 0, place tags directly after headline text, with only one space in
3482 between."
3483 :group 'org-tags
3484 :type 'integer)
3486 (defcustom org-auto-align-tags t
3487 "Non-nil keeps tags aligned when modifying headlines.
3488 Some operations (i.e. demoting) change the length of a headline and
3489 therefore shift the tags around. With this option turned on, after
3490 each such operation the tags are again aligned to `org-tags-column'."
3491 :group 'org-tags
3492 :type 'boolean)
3494 (defcustom org-use-tag-inheritance t
3495 "Non-nil means tags in levels apply also for sublevels.
3496 When nil, only the tags directly given in a specific line apply there.
3497 This may also be a list of tags that should be inherited, or a regexp that
3498 matches tags that should be inherited. Additional control is possible
3499 with the variable `org-tags-exclude-from-inheritance' which gives an
3500 explicit list of tags to be excluded from inheritance, even if the value of
3501 `org-use-tag-inheritance' would select it for inheritance.
3503 If this option is t, a match early-on in a tree can lead to a large
3504 number of matches in the subtree when constructing the agenda or creating
3505 a sparse tree. If you only want to see the first match in a tree during
3506 a search, check out the variable `org-tags-match-list-sublevels'."
3507 :group 'org-tags
3508 :type '(choice
3509 (const :tag "Not" nil)
3510 (const :tag "Always" t)
3511 (repeat :tag "Specific tags" (string :tag "Tag"))
3512 (regexp :tag "Tags matched by regexp")))
3514 (defcustom org-tags-exclude-from-inheritance nil
3515 "List of tags that should never be inherited.
3516 This is a way to exclude a few tags from inheritance. For way to do
3517 the opposite, to actively allow inheritance for selected tags,
3518 see the variable `org-use-tag-inheritance'."
3519 :group 'org-tags
3520 :type '(repeat (string :tag "Tag")))
3522 (defun org-tag-inherit-p (tag)
3523 "Check if TAG is one that should be inherited."
3524 (cond
3525 ((member tag org-tags-exclude-from-inheritance) nil)
3526 ((eq org-use-tag-inheritance t) t)
3527 ((not org-use-tag-inheritance) nil)
3528 ((stringp org-use-tag-inheritance)
3529 (string-match org-use-tag-inheritance tag))
3530 ((listp org-use-tag-inheritance)
3531 (member tag org-use-tag-inheritance))
3532 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3534 (defcustom org-tags-match-list-sublevels t
3535 "Non-nil means list also sublevels of headlines matching a search.
3536 This variable applies to tags/property searches, and also to stuck
3537 projects because this search is based on a tags match as well.
3539 When set to the symbol `indented', sublevels are indented with
3540 leading dots.
3542 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3543 the sublevels of a headline matching a tag search often also match
3544 the same search. Listing all of them can create very long lists.
3545 Setting this variable to nil causes subtrees of a match to be skipped.
3547 This variable is semi-obsolete and probably should always be true. It
3548 is better to limit inheritance to certain tags using the variables
3549 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3550 :group 'org-tags
3551 :type '(choice
3552 (const :tag "No, don't list them" nil)
3553 (const :tag "Yes, do list them" t)
3554 (const :tag "List them, indented with leading dots" indented)))
3556 (defcustom org-tags-sort-function nil
3557 "When set, tags are sorted using this function as a comparator."
3558 :group 'org-tags
3559 :type '(choice
3560 (const :tag "No sorting" nil)
3561 (const :tag "Alphabetical" string<)
3562 (const :tag "Reverse alphabetical" string>)
3563 (function :tag "Custom function" nil)))
3565 (defvar org-tags-history nil
3566 "History of minibuffer reads for tags.")
3567 (defvar org-last-tags-completion-table nil
3568 "The last used completion table for tags.")
3569 (defvar org-after-tags-change-hook nil
3570 "Hook that is run after the tags in a line have changed.")
3572 (defgroup org-properties nil
3573 "Options concerning properties in Org-mode."
3574 :tag "Org Properties"
3575 :group 'org)
3577 (defcustom org-property-format "%-10s %s"
3578 "How property key/value pairs should be formatted by `indent-line'.
3579 When `indent-line' hits a property definition, it will format the line
3580 according to this format, mainly to make sure that the values are
3581 lined-up with respect to each other."
3582 :group 'org-properties
3583 :type 'string)
3585 (defcustom org-properties-postprocess-alist nil
3586 "Alist of properties and functions to adjust inserted values.
3587 Elements of this alist must be of the form
3589 ([string] [function])
3591 where [string] must be a property name and [function] must be a
3592 lambda expression: this lambda expression must take one argument,
3593 the value to adjust, and return the new value as a string.
3595 For example, this element will allow the property \"Remaining\"
3596 to be updated wrt the relation between the \"Effort\" property
3597 and the clock summary:
3599 ((\"Remaining\" (lambda(value)
3600 (let ((clocksum (org-clock-sum-current-item))
3601 (effort (org-duration-string-to-minutes
3602 (org-entry-get (point) \"Effort\"))))
3603 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3604 :group 'org-properties
3605 :version "24.1"
3606 :type '(alist :key-type (string :tag "Property")
3607 :value-type (function :tag "Function")))
3609 (defcustom org-use-property-inheritance nil
3610 "Non-nil means properties apply also for sublevels.
3612 This setting is chiefly used during property searches. Turning it on can
3613 cause significant overhead when doing a search, which is why it is not
3614 on by default.
3616 When nil, only the properties directly given in the current entry count.
3617 When t, every property is inherited. The value may also be a list of
3618 properties that should have inheritance, or a regular expression matching
3619 properties that should be inherited.
3621 However, note that some special properties use inheritance under special
3622 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3623 and the properties ending in \"_ALL\" when they are used as descriptor
3624 for valid values of a property.
3626 Note for programmers:
3627 When querying an entry with `org-entry-get', you can control if inheritance
3628 should be used. By default, `org-entry-get' looks only at the local
3629 properties. You can request inheritance by setting the inherit argument
3630 to t (to force inheritance) or to `selective' (to respect the setting
3631 in this variable)."
3632 :group 'org-properties
3633 :type '(choice
3634 (const :tag "Not" nil)
3635 (const :tag "Always" t)
3636 (repeat :tag "Specific properties" (string :tag "Property"))
3637 (regexp :tag "Properties matched by regexp")))
3639 (defun org-property-inherit-p (property)
3640 "Check if PROPERTY is one that should be inherited."
3641 (cond
3642 ((eq org-use-property-inheritance t) t)
3643 ((not org-use-property-inheritance) nil)
3644 ((stringp org-use-property-inheritance)
3645 (string-match org-use-property-inheritance property))
3646 ((listp org-use-property-inheritance)
3647 (member property org-use-property-inheritance))
3648 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3650 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3651 "The default column format, if no other format has been defined.
3652 This variable can be set on the per-file basis by inserting a line
3654 #+COLUMNS: %25ITEM ....."
3655 :group 'org-properties
3656 :type 'string)
3658 (defcustom org-columns-ellipses ".."
3659 "The ellipses to be used when a field in column view is truncated.
3660 When this is the empty string, as many characters as possible are shown,
3661 but then there will be no visual indication that the field has been truncated.
3662 When this is a string of length N, the last N characters of a truncated
3663 field are replaced by this string. If the column is narrower than the
3664 ellipses string, only part of the ellipses string will be shown."
3665 :group 'org-properties
3666 :type 'string)
3668 (defcustom org-columns-modify-value-for-display-function nil
3669 "Function that modifies values for display in column view.
3670 For example, it can be used to cut out a certain part from a time stamp.
3671 The function must take 2 arguments:
3673 column-title The title of the column (*not* the property name)
3674 value The value that should be modified.
3676 The function should return the value that should be displayed,
3677 or nil if the normal value should be used."
3678 :group 'org-properties
3679 :type '(choice (const nil) (function)))
3681 (defconst org-global-properties-fixed
3682 '(("VISIBILITY_ALL" . "folded children content all")
3683 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3684 "List of property/value pairs that can be inherited by any entry.
3686 These are fixed values, for the preset properties. The user variable
3687 that can be used to add to this list is `org-global-properties'.
3689 The entries in this list are cons cells where the car is a property
3690 name and cdr is a string with the value. If the value represents
3691 multiple items like an \"_ALL\" property, separate the items by
3692 spaces.")
3694 (defcustom org-global-properties nil
3695 "List of property/value pairs that can be inherited by any entry.
3697 This list will be combined with the constant `org-global-properties-fixed'.
3699 The entries in this list are cons cells where the car is a property
3700 name and cdr is a string with the value.
3702 You can set buffer-local values for the same purpose in the variable
3703 `org-file-properties' this by adding lines like
3705 #+PROPERTY: NAME VALUE"
3706 :group 'org-properties
3707 :type '(repeat
3708 (cons (string :tag "Property")
3709 (string :tag "Value"))))
3711 (defvar org-file-properties nil
3712 "List of property/value pairs that can be inherited by any entry.
3713 Valid for the current buffer.
3714 This variable is populated from #+PROPERTY lines.")
3715 (make-variable-buffer-local 'org-file-properties)
3717 (defgroup org-agenda nil
3718 "Options concerning agenda views in Org-mode."
3719 :tag "Org Agenda"
3720 :group 'org)
3722 (defvar org-category nil
3723 "Variable used by org files to set a category for agenda display.
3724 Such files should use a file variable to set it, for example
3726 # -*- mode: org; org-category: \"ELisp\"
3728 or contain a special line
3730 #+CATEGORY: ELisp
3732 If the file does not specify a category, then file's base name
3733 is used instead.")
3734 (make-variable-buffer-local 'org-category)
3735 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3737 (defcustom org-agenda-files nil
3738 "The files to be used for agenda display.
3739 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3740 \\[org-remove-file]. You can also use customize to edit the list.
3742 If an entry is a directory, all files in that directory that are matched by
3743 `org-agenda-file-regexp' will be part of the file list.
3745 If the value of the variable is not a list but a single file name, then
3746 the list of agenda files is actually stored and maintained in that file, one
3747 agenda file per line. In this file paths can be given relative to
3748 `org-directory'. Tilde expansion and environment variable substitution
3749 are also made."
3750 :group 'org-agenda
3751 :type '(choice
3752 (repeat :tag "List of files and directories" file)
3753 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3755 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3756 "Regular expression to match files for `org-agenda-files'.
3757 If any element in the list in that variable contains a directory instead
3758 of a normal file, all files in that directory that are matched by this
3759 regular expression will be included."
3760 :group 'org-agenda
3761 :type 'regexp)
3763 (defcustom org-agenda-text-search-extra-files nil
3764 "List of extra files to be searched by text search commands.
3765 These files will be searched in addition to the agenda files by the
3766 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3767 Note that these files will only be searched for text search commands,
3768 not for the other agenda views like todo lists, tag searches or the weekly
3769 agenda. This variable is intended to list notes and possibly archive files
3770 that should also be searched by these two commands.
3771 In fact, if the first element in the list is the symbol `agenda-archives',
3772 then all archive files of all agenda files will be added to the search
3773 scope."
3774 :group 'org-agenda
3775 :type '(set :greedy t
3776 (const :tag "Agenda Archives" agenda-archives)
3777 (repeat :inline t (file))))
3779 (org-defvaralias 'org-agenda-multi-occur-extra-files
3780 'org-agenda-text-search-extra-files)
3782 (defcustom org-agenda-skip-unavailable-files nil
3783 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3784 A nil value means to remove them, after a query, from the list."
3785 :group 'org-agenda
3786 :type 'boolean)
3788 (defcustom org-calendar-to-agenda-key [?c]
3789 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3790 The command `org-calendar-goto-agenda' will be bound to this key. The
3791 default is the character `c' because then `c' can be used to switch back and
3792 forth between agenda and calendar."
3793 :group 'org-agenda
3794 :type 'sexp)
3796 (defcustom org-calendar-insert-diary-entry-key [?i]
3797 "The key to be installed in `calendar-mode-map' for adding diary entries.
3798 This option is irrelevant until `org-agenda-diary-file' has been configured
3799 to point to an Org-mode file. When that is the case, the command
3800 `org-agenda-diary-entry' will be bound to the key given here, by default
3801 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3802 if you want to continue doing this, you need to change this to a different
3803 key."
3804 :group 'org-agenda
3805 :type 'sexp)
3807 (defcustom org-agenda-diary-file 'diary-file
3808 "File to which to add new entries with the `i' key in agenda and calendar.
3809 When this is the symbol `diary-file', the functionality in the Emacs
3810 calendar will be used to add entries to the `diary-file'. But when this
3811 points to a file, `org-agenda-diary-entry' will be used instead."
3812 :group 'org-agenda
3813 :type '(choice
3814 (const :tag "The standard Emacs diary file" diary-file)
3815 (file :tag "Special Org file diary entries")))
3817 (eval-after-load "calendar"
3818 '(progn
3819 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3820 'org-calendar-goto-agenda)
3821 (add-hook 'calendar-mode-hook
3822 (lambda ()
3823 (unless (eq org-agenda-diary-file 'diary-file)
3824 (define-key calendar-mode-map
3825 org-calendar-insert-diary-entry-key
3826 'org-agenda-diary-entry))))))
3828 (defgroup org-latex nil
3829 "Options for embedding LaTeX code into Org-mode."
3830 :tag "Org LaTeX"
3831 :group 'org)
3833 (defcustom org-format-latex-options
3834 '(:foreground default :background default :scale 1.0
3835 :html-foreground "Black" :html-background "Transparent"
3836 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3837 "Options for creating images from LaTeX fragments.
3838 This is a property list with the following properties:
3839 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3840 `default' means use the foreground of the default face.
3841 `auto' means use the foreground from the text face.
3842 :background the background color, or \"Transparent\".
3843 `default' means use the background of the default face.
3844 `auto' means use the background from the text face.
3845 :scale a scaling factor for the size of the images, to get more pixels
3846 :html-foreground, :html-background, :html-scale
3847 the same numbers for HTML export.
3848 :matchers a list indicating which matchers should be used to
3849 find LaTeX fragments. Valid members of this list are:
3850 \"begin\" find environments
3851 \"$1\" find single characters surrounded by $.$
3852 \"$\" find math expressions surrounded by $...$
3853 \"$$\" find math expressions surrounded by $$....$$
3854 \"\\(\" find math expressions surrounded by \\(...\\)
3855 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3856 :group 'org-latex
3857 :type 'plist)
3859 (defcustom org-format-latex-signal-error t
3860 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3861 When nil, just push out a message."
3862 :group 'org-latex
3863 :version "24.1"
3864 :type 'boolean)
3866 (defcustom org-latex-to-mathml-jar-file nil
3867 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3868 Use this to specify additional executable file say a jar file.
3870 When using MathToWeb as the converter, specify the full-path to
3871 your mathtoweb.jar file."
3872 :group 'org-latex
3873 :version "24.1"
3874 :type '(choice
3875 (const :tag "None" nil)
3876 (file :tag "JAR file" :must-match t)))
3878 (defcustom org-latex-to-mathml-convert-command nil
3879 "Command to convert LaTeX fragments to MathML.
3880 Replace format-specifiers in the command as noted below and use
3881 `shell-command' to convert LaTeX to MathML.
3882 %j: Executable file in fully expanded form as specified by
3883 `org-latex-to-mathml-jar-file'.
3884 %I: Input LaTeX file in fully expanded form
3885 %o: Output MathML file
3886 This command is used by `org-create-math-formula'.
3888 When using MathToWeb as the converter, set this to
3889 \"java -jar %j -unicode -force -df %o %I\"."
3890 :group 'org-latex
3891 :version "24.1"
3892 :type '(choice
3893 (const :tag "None" nil)
3894 (string :tag "\nShell command")))
3896 (defcustom org-latex-create-formula-image-program 'dvipng
3897 "Program to convert LaTeX fragments with.
3899 dvipng Process the LaTeX fragments to dvi file, then convert
3900 dvi files to png files using dvipng.
3901 This will also include processing of non-math environments.
3902 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3903 to convert pdf files to png files"
3904 :group 'org-latex
3905 :version "24.1"
3906 :type '(choice
3907 (const :tag "dvipng" dvipng)
3908 (const :tag "imagemagick" imagemagick)))
3910 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3911 "Path to store latex preview images.
3912 A relative path here creates many directories relative to the
3913 processed org files paths. An absolute path puts all preview
3914 images at the same place."
3915 :group 'org-latex
3916 :version "24.3"
3917 :type 'string)
3919 (defun org-format-latex-mathml-available-p ()
3920 "Return t if `org-latex-to-mathml-convert-command' is usable."
3921 (save-match-data
3922 (when (and (boundp 'org-latex-to-mathml-convert-command)
3923 org-latex-to-mathml-convert-command)
3924 (let ((executable (car (split-string
3925 org-latex-to-mathml-convert-command))))
3926 (when (executable-find executable)
3927 (if (string-match
3928 "%j" org-latex-to-mathml-convert-command)
3929 (file-readable-p org-latex-to-mathml-jar-file)
3930 t))))))
3932 (defcustom org-format-latex-header "\\documentclass{article}
3933 \\usepackage[usenames]{color}
3934 \[PACKAGES]
3935 \[DEFAULT-PACKAGES]
3936 \\pagestyle{empty} % do not remove
3937 % The settings below are copied from fullpage.sty
3938 \\setlength{\\textwidth}{\\paperwidth}
3939 \\addtolength{\\textwidth}{-3cm}
3940 \\setlength{\\oddsidemargin}{1.5cm}
3941 \\addtolength{\\oddsidemargin}{-2.54cm}
3942 \\setlength{\\evensidemargin}{\\oddsidemargin}
3943 \\setlength{\\textheight}{\\paperheight}
3944 \\addtolength{\\textheight}{-\\headheight}
3945 \\addtolength{\\textheight}{-\\headsep}
3946 \\addtolength{\\textheight}{-\\footskip}
3947 \\addtolength{\\textheight}{-3cm}
3948 \\setlength{\\topmargin}{1.5cm}
3949 \\addtolength{\\topmargin}{-2.54cm}"
3950 "The document header used for processing LaTeX fragments.
3951 It is imperative that this header make sure that no page number
3952 appears on the page. The package defined in the variables
3953 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3954 will either replace the placeholder \"[PACKAGES]\" in this
3955 header, or they will be appended."
3956 :group 'org-latex
3957 :type 'string)
3959 (defun org-set-packages-alist (var val)
3960 "Set the packages alist and make sure it has 3 elements per entry."
3961 (set var (mapcar (lambda (x)
3962 (if (and (consp x) (= (length x) 2))
3963 (list (car x) (nth 1 x) t)
3965 val)))
3967 (defun org-get-packages-alist (var)
3968 "Get the packages alist and make sure it has 3 elements per entry."
3969 (mapcar (lambda (x)
3970 (if (and (consp x) (= (length x) 2))
3971 (list (car x) (nth 1 x) t)
3973 (default-value var)))
3975 (defcustom org-latex-default-packages-alist
3976 '(("AUTO" "inputenc" t)
3977 ("T1" "fontenc" t)
3978 ("" "fixltx2e" nil)
3979 ("" "graphicx" t)
3980 ("" "longtable" nil)
3981 ("" "float" nil)
3982 ("" "wrapfig" nil)
3983 ("" "rotating" nil)
3984 ("normalem" "ulem" t)
3985 ("" "amsmath" t)
3986 ("" "textcomp" t)
3987 ("" "marvosym" t)
3988 ("" "wasysym" t)
3989 ("" "amssymb" t)
3990 ("" "hyperref" nil)
3991 "\\tolerance=1000")
3992 "Alist of default packages to be inserted in the header.
3994 Change this only if one of the packages here causes an
3995 incompatibility with another package you are using.
3997 The packages in this list are needed by one part or another of
3998 Org mode to function properly:
4000 - inputenc, fontenc: for basic font and character selection
4001 - fixltx2e: Important patches of LaTeX itself
4002 - graphicx: for including images
4003 - longtable: For multipage tables
4004 - float, wrapfig: for figure placement
4005 - rotating: for sideways figures and tables
4006 - ulem: for underline and strike-through
4007 - amsmath: for subscript and superscript and math environments
4008 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4009 for interpreting the entities in `org-entities'. You can skip
4010 some of these packages if you don't use any of their symbols.
4011 - hyperref: for cross references
4013 Therefore you should not modify this variable unless you know
4014 what you are doing. The one reason to change it anyway is that
4015 you might be loading some other package that conflicts with one
4016 of the default packages. Each cell is of the format
4017 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
4018 the package also needs to be included when compiling LaTeX
4019 snippets into images for inclusion into non-LaTeX output."
4020 :group 'org-latex
4021 :group 'org-export-latex
4022 :set 'org-set-packages-alist
4023 :get 'org-get-packages-alist
4024 :version "24.1"
4025 :type '(repeat
4026 (choice
4027 (list :tag "options/package pair"
4028 (string :tag "options")
4029 (string :tag "package")
4030 (boolean :tag "Snippet"))
4031 (string :tag "A line of LaTeX"))))
4033 (defcustom org-latex-packages-alist nil
4034 "Alist of packages to be inserted in every LaTeX header.
4036 These will be inserted after `org-latex-default-packages-alist'.
4037 Each cell is of the format:
4039 \(\"options\" \"package\" snippet-flag)
4041 SNIPPET-FLAG, when t, indicates that this package is also needed
4042 when turning LaTeX snippets into images for inclusion into
4043 non-LaTeX output.
4045 Make sure that you only list packages here which:
4047 - you want in every file
4048 - do not conflict with the setup in `org-format-latex-header'.
4049 - do not conflict with the default packages in
4050 `org-latex-default-packages-alist'."
4051 :group 'org-latex
4052 :group 'org-export-latex
4053 :set 'org-set-packages-alist
4054 :get 'org-get-packages-alist
4055 :type '(repeat
4056 (choice
4057 (list :tag "options/package pair"
4058 (string :tag "options")
4059 (string :tag "package")
4060 (boolean :tag "Snippet"))
4061 (string :tag "A line of LaTeX"))))
4063 (defgroup org-appearance nil
4064 "Settings for Org-mode appearance."
4065 :tag "Org Appearance"
4066 :group 'org)
4068 (defcustom org-level-color-stars-only nil
4069 "Non-nil means fontify only the stars in each headline.
4070 When nil, the entire headline is fontified.
4071 Changing it requires restart of `font-lock-mode' to become effective
4072 also in regions already fontified."
4073 :group 'org-appearance
4074 :type 'boolean)
4076 (defcustom org-hide-leading-stars nil
4077 "Non-nil means hide the first N-1 stars in a headline.
4078 This works by using the face `org-hide' for these stars. This
4079 face is white for a light background, and black for a dark
4080 background. You may have to customize the face `org-hide' to
4081 make this work.
4082 Changing it requires restart of `font-lock-mode' to become effective
4083 also in regions already fontified.
4084 You may also set this on a per-file basis by adding one of the following
4085 lines to the buffer:
4087 #+STARTUP: hidestars
4088 #+STARTUP: showstars"
4089 :group 'org-appearance
4090 :type 'boolean)
4092 (defcustom org-hidden-keywords nil
4093 "List of symbols corresponding to keywords to be hidden the org buffer.
4094 For example, a value '(title) for this list will make the document's title
4095 appear in the buffer without the initial #+TITLE: keyword."
4096 :group 'org-appearance
4097 :version "24.1"
4098 :type '(set (const :tag "#+AUTHOR" author)
4099 (const :tag "#+DATE" date)
4100 (const :tag "#+EMAIL" email)
4101 (const :tag "#+TITLE" title)))
4103 (defcustom org-custom-properties nil
4104 "List of properties (as strings) with a special meaning.
4105 The default use of these custom properties is to let the user
4106 hide them with `org-toggle-custom-properties-visibility'."
4107 :group 'org-properties
4108 :group 'org-appearance
4109 :version "24.3"
4110 :type '(repeat (string :tag "Property Name")))
4112 (defcustom org-fontify-done-headline nil
4113 "Non-nil means change the face of a headline if it is marked DONE.
4114 Normally, only the TODO/DONE keyword indicates the state of a headline.
4115 When this is non-nil, the headline after the keyword is set to the
4116 `org-headline-done' as an additional indication."
4117 :group 'org-appearance
4118 :type 'boolean)
4120 (defcustom org-fontify-emphasized-text t
4121 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4122 Changing this variable requires a restart of Emacs to take effect."
4123 :group 'org-appearance
4124 :type 'boolean)
4126 (defcustom org-fontify-whole-heading-line nil
4127 "Non-nil means fontify the whole line for headings.
4128 This is useful when setting a background color for the
4129 org-level-* faces."
4130 :group 'org-appearance
4131 :type 'boolean)
4133 (defcustom org-highlight-latex-and-related nil
4134 "Non-nil means highlight LaTeX related syntax in the buffer.
4135 When non nil, the value should be a list containing any of the
4136 following symbols:
4137 `latex' Highlight LaTeX snippets and environments.
4138 `script' Highlight subscript and superscript.
4139 `entities' Highlight entities."
4140 :group 'org-appearance
4141 :version "24.4"
4142 :package-version '(Org . "8.0")
4143 :type '(choice
4144 (const :tag "No highlighting" nil)
4145 (set :greedy t :tag "Highlight"
4146 (const :tag "LaTeX snippets and environments" latex)
4147 (const :tag "Subscript and superscript" script)
4148 (const :tag "Entities" entities))))
4150 (defcustom org-hide-emphasis-markers nil
4151 "Non-nil mean font-lock should hide the emphasis marker characters."
4152 :group 'org-appearance
4153 :type 'boolean)
4155 (defcustom org-pretty-entities nil
4156 "Non-nil means show entities as UTF8 characters.
4157 When nil, the \\name form remains in the buffer."
4158 :group 'org-appearance
4159 :version "24.1"
4160 :type 'boolean)
4162 (defcustom org-pretty-entities-include-sub-superscripts t
4163 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4164 :group 'org-appearance
4165 :version "24.1"
4166 :type 'boolean)
4168 (defvar org-emph-re nil
4169 "Regular expression for matching emphasis.
4170 After a match, the match groups contain these elements:
4171 0 The match of the full regular expression, including the characters
4172 before and after the proper match
4173 1 The character before the proper match, or empty at beginning of line
4174 2 The proper match, including the leading and trailing markers
4175 3 The leading marker like * or /, indicating the type of highlighting
4176 4 The text between the emphasis markers, not including the markers
4177 5 The character after the match, empty at the end of a line")
4178 (defvar org-verbatim-re nil
4179 "Regular expression for matching verbatim text.")
4180 (defvar org-emphasis-regexp-components) ; defined just below
4181 (defvar org-emphasis-alist) ; defined just below
4182 (defun org-set-emph-re (var val)
4183 "Set variable and compute the emphasis regular expression."
4184 (set var val)
4185 (when (and (boundp 'org-emphasis-alist)
4186 (boundp 'org-emphasis-regexp-components)
4187 org-emphasis-alist org-emphasis-regexp-components)
4188 (let* ((e org-emphasis-regexp-components)
4189 (pre (car e))
4190 (post (nth 1 e))
4191 (border (nth 2 e))
4192 (body (nth 3 e))
4193 (nl (nth 4 e))
4194 (body1 (concat body "*?"))
4195 (markers (mapconcat 'car org-emphasis-alist ""))
4196 (vmarkers (mapconcat
4197 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4198 org-emphasis-alist "")))
4199 ;; make sure special characters appear at the right position in the class
4200 (if (string-match "\\^" markers)
4201 (setq markers (concat (replace-match "" t t markers) "^")))
4202 (if (string-match "-" markers)
4203 (setq markers (concat (replace-match "" t t markers) "-")))
4204 (if (string-match "\\^" vmarkers)
4205 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4206 (if (string-match "-" vmarkers)
4207 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4208 (if (> nl 0)
4209 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4210 (int-to-string nl) "\\}")))
4211 ;; Make the regexp
4212 (setq org-emph-re
4213 (concat "\\([" pre "]\\|^\\)"
4214 "\\("
4215 "\\([" markers "]\\)"
4216 "\\("
4217 "[^" border "]\\|"
4218 "[^" border "]"
4219 body1
4220 "[^" border "]"
4221 "\\)"
4222 "\\3\\)"
4223 "\\([" post "]\\|$\\)"))
4224 (setq org-verbatim-re
4225 (concat "\\([" pre "]\\|^\\)"
4226 "\\("
4227 "\\([" vmarkers "]\\)"
4228 "\\("
4229 "[^" border "]\\|"
4230 "[^" border "]"
4231 body1
4232 "[^" border "]"
4233 "\\)"
4234 "\\3\\)"
4235 "\\([" post "]\\|$\\)")))))
4237 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4238 ;; set this option proved cumbersome. See this message/thread:
4239 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4240 (defvar org-emphasis-regexp-components
4241 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4242 "Components used to build the regular expression for emphasis.
4243 This is a list with five entries. Terminology: In an emphasis string
4244 like \" *strong word* \", we call the initial space PREMATCH, the final
4245 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4246 and \"trong wor\" is the body. The different components in this variable
4247 specify what is allowed/forbidden in each part:
4249 pre Chars allowed as prematch. Beginning of line will be allowed too.
4250 post Chars allowed as postmatch. End of line will be allowed too.
4251 border The chars *forbidden* as border characters.
4252 body-regexp A regexp like \".\" to match a body character. Don't use
4253 non-shy groups here, and don't allow newline here.
4254 newline The maximum number of newlines allowed in an emphasis exp.
4256 You need to reload Org or to restart Emacs after customizing this.")
4258 (defcustom org-emphasis-alist
4259 `(("*" bold)
4260 ("/" italic)
4261 ("_" underline)
4262 ("=" org-code verbatim)
4263 ("~" org-verbatim verbatim)
4264 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4265 "Alist of characters and faces to emphasize text.
4266 Text starting and ending with a special character will be emphasized,
4267 for example *bold*, _underlined_ and /italic/. This variable sets the
4268 marker characters and the face to be used by font-lock for highlighting
4269 in Org-mode Emacs buffers.
4271 You need to reload Org or to restart Emacs after customizing this."
4272 :group 'org-appearance
4273 :set 'org-set-emph-re
4274 :version "24.4"
4275 :package-version '(Org . "8.0")
4276 :type '(repeat
4277 (list
4278 (string :tag "Marker character")
4279 (choice
4280 (face :tag "Font-lock-face")
4281 (plist :tag "Face property list"))
4282 (option (const verbatim)))))
4284 (defvar org-protecting-blocks
4285 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4286 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4287 This is needed for font-lock setup.")
4289 ;;; Miscellaneous options
4291 (defgroup org-completion nil
4292 "Completion in Org-mode."
4293 :tag "Org Completion"
4294 :group 'org)
4296 (defcustom org-completion-use-ido nil
4297 "Non-nil means use ido completion wherever possible.
4298 Note that `ido-mode' must be active for this variable to be relevant.
4299 If you decide to turn this variable on, you might well want to turn off
4300 `org-outline-path-complete-in-steps'.
4301 See also `org-completion-use-iswitchb'."
4302 :group 'org-completion
4303 :type 'boolean)
4305 (defcustom org-completion-use-iswitchb nil
4306 "Non-nil means use iswitchb completion wherever possible.
4307 Note that `iswitchb-mode' must be active for this variable to be relevant.
4308 If you decide to turn this variable on, you might well want to turn off
4309 `org-outline-path-complete-in-steps'.
4310 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4311 :group 'org-completion
4312 :type 'boolean)
4314 (defcustom org-completion-fallback-command 'hippie-expand
4315 "The expansion command called by \\[pcomplete] in normal context.
4316 Normal means, no org-mode-specific context."
4317 :group 'org-completion
4318 :type 'function)
4320 ;;; Functions and variables from their packages
4321 ;; Declared here to avoid compiler warnings
4323 ;; XEmacs only
4324 (defvar outline-mode-menu-heading)
4325 (defvar outline-mode-menu-show)
4326 (defvar outline-mode-menu-hide)
4327 (defvar zmacs-regions) ; XEmacs regions
4329 ;; Emacs only
4330 (defvar mark-active)
4332 ;; Various packages
4333 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4334 (declare-function calendar-forward-day "cal-move" (arg))
4335 (declare-function calendar-goto-date "cal-move" (date))
4336 (declare-function calendar-goto-today "cal-move" ())
4337 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4338 (defvar calc-embedded-close-formula)
4339 (defvar calc-embedded-open-formula)
4340 (declare-function cdlatex-tab "ext:cdlatex" ())
4341 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4342 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4343 (defvar font-lock-unfontify-region-function)
4344 (declare-function iswitchb-read-buffer "iswitchb"
4345 (prompt &optional default require-match start matches-set))
4346 (defvar iswitchb-temp-buflist)
4347 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4348 (defvar org-agenda-tags-todo-honor-ignore-options)
4349 (declare-function org-agenda-skip "org-agenda" ())
4350 (declare-function
4351 org-agenda-format-item "org-agenda"
4352 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4353 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4354 (declare-function org-agenda-change-all-lines "org-agenda"
4355 (newhead hdmarker &optional fixface just-this))
4356 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4357 (declare-function org-agenda-maybe-redo "org-agenda" ())
4358 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4359 (beg end))
4360 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4361 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4362 "org-agenda" (&optional end))
4363 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4364 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4365 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4366 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4367 (declare-function org-indent-mode "org-indent" (&optional arg))
4368 (declare-function parse-time-string "parse-time" (string))
4369 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4370 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4371 (defvar remember-data-file)
4372 (defvar texmathp-why)
4373 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4374 (declare-function table--at-cell-p "table" (position &optional object at-column))
4376 ;;;###autoload
4377 (defun turn-on-orgtbl ()
4378 "Unconditionally turn on `orgtbl-mode'."
4379 (require 'org-table)
4380 (orgtbl-mode 1))
4382 (defun org-at-table-p (&optional table-type)
4383 "Return t if the cursor is inside an org-type table.
4384 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4385 (if org-enable-table-editor
4386 (save-excursion
4387 (beginning-of-line 1)
4388 (looking-at (if table-type org-table-any-line-regexp
4389 org-table-line-regexp)))
4390 nil))
4391 (defsubst org-table-p () (org-at-table-p))
4393 (defun org-at-table.el-p ()
4394 "Return t if and only if we are at a table.el table."
4395 (and (org-at-table-p 'any)
4396 (save-excursion
4397 (goto-char (org-table-begin 'any))
4398 (looking-at org-table1-hline-regexp))))
4400 (defun org-table-recognize-table.el ()
4401 "If there is a table.el table nearby, recognize it and move into it."
4402 (if org-table-tab-recognizes-table.el
4403 (if (org-at-table.el-p)
4404 (progn
4405 (beginning-of-line 1)
4406 (if (looking-at org-table-dataline-regexp)
4408 (if (looking-at org-table1-hline-regexp)
4409 (progn
4410 (beginning-of-line 2)
4411 (if (looking-at org-table-any-border-regexp)
4412 (beginning-of-line -1)))))
4413 (if (re-search-forward "|" (org-table-end t) t)
4414 (progn
4415 (require 'table)
4416 (if (table--at-cell-p (point))
4418 (message "recognizing table.el table...")
4419 (table-recognize-table)
4420 (message "recognizing table.el table...done")))
4421 (error "This should not happen"))
4423 nil)
4424 nil))
4426 (defun org-at-table-hline-p ()
4427 "Return t if the cursor is inside a hline in a table."
4428 (if org-enable-table-editor
4429 (save-excursion
4430 (beginning-of-line 1)
4431 (looking-at org-table-hline-regexp))
4432 nil))
4434 (defun org-table-map-tables (function &optional quietly)
4435 "Apply FUNCTION to the start of all tables in the buffer."
4436 (save-excursion
4437 (save-restriction
4438 (widen)
4439 (goto-char (point-min))
4440 (while (re-search-forward org-table-any-line-regexp nil t)
4441 (unless quietly
4442 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4443 (beginning-of-line 1)
4444 (when (and (looking-at org-table-line-regexp)
4445 ;; Exclude tables in src/example/verbatim/clocktable blocks
4446 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4447 (save-excursion (funcall function))
4448 (or (looking-at org-table-line-regexp)
4449 (forward-char 1)))
4450 (re-search-forward org-table-any-border-regexp nil 1))))
4451 (unless quietly (message "Mapping tables: done")))
4453 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4454 (declare-function org-clock-update-mode-line "org-clock" ())
4455 (declare-function org-resolve-clocks "org-clock"
4456 (&optional also-non-dangling-p prompt last-valid))
4458 (defun org-at-TBLFM-p (&optional pos)
4459 "Return t when point (or POS) is in #+TBLFM line."
4460 (save-excursion
4461 (let ((pos pos)))
4462 (goto-char (or pos (point)))
4463 (beginning-of-line 1)
4464 (looking-at org-TBLFM-regexp)))
4466 (defvar org-clock-start-time)
4467 (defvar org-clock-marker (make-marker)
4468 "Marker recording the last clock-in.")
4469 (defvar org-clock-hd-marker (make-marker)
4470 "Marker recording the last clock-in, but the headline position.")
4471 (defvar org-clock-heading ""
4472 "The heading of the current clock entry.")
4473 (defun org-clock-is-active ()
4474 "Return the buffer where the clock is currently running.
4475 Return nil if no clock is running."
4476 (marker-buffer org-clock-marker))
4478 (defun org-check-running-clock ()
4479 "Check if the current buffer contains the running clock.
4480 If yes, offer to stop it and to save the buffer with the changes."
4481 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4482 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4483 (buffer-name))))
4484 (org-clock-out)
4485 (when (y-or-n-p "Save changed buffer?")
4486 (save-buffer))))
4488 (defun org-clocktable-try-shift (dir n)
4489 "Check if this line starts a clock table, if yes, shift the time block."
4490 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4491 (org-clocktable-shift dir n)))
4493 ;;;###autoload
4494 (defun org-clock-persistence-insinuate ()
4495 "Set up hooks for clock persistence."
4496 (require 'org-clock)
4497 (add-hook 'org-mode-hook 'org-clock-load)
4498 (add-hook 'kill-emacs-hook 'org-clock-save))
4500 (defgroup org-archive nil
4501 "Options concerning archiving in Org-mode."
4502 :tag "Org Archive"
4503 :group 'org-structure)
4505 (defcustom org-archive-location "%s_archive::"
4506 "The location where subtrees should be archived.
4508 The value of this variable is a string, consisting of two parts,
4509 separated by a double-colon. The first part is a filename and
4510 the second part is a headline.
4512 When the filename is omitted, archiving happens in the same file.
4513 %s in the filename will be replaced by the current file
4514 name (without the directory part). Archiving to a different file
4515 is useful to keep archived entries from contributing to the
4516 Org-mode Agenda.
4518 The archived entries will be filed as subtrees of the specified
4519 headline. When the headline is omitted, the subtrees are simply
4520 filed away at the end of the file, as top-level entries. Also in
4521 the heading you can use %s to represent the file name, this can be
4522 useful when using the same archive for a number of different files.
4524 Here are a few examples:
4525 \"%s_archive::\"
4526 If the current file is Projects.org, archive in file
4527 Projects.org_archive, as top-level trees. This is the default.
4529 \"::* Archived Tasks\"
4530 Archive in the current file, under the top-level headline
4531 \"* Archived Tasks\".
4533 \"~/org/archive.org::\"
4534 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4536 \"~/org/archive.org::* From %s\"
4537 Archive in file ~/org/archive.org (absolute path), under headlines
4538 \"From FILENAME\" where file name is the current file name.
4540 \"~/org/datetree.org::datetree/* Finished Tasks\"
4541 The \"datetree/\" string is special, signifying to archive
4542 items to the datetree. Items are placed in either the CLOSED
4543 date of the item, or the current date if there is no CLOSED date.
4544 The heading will be a subentry to the current date. There doesn't
4545 need to be a heading, but there always needs to be a slash after
4546 datetree. For example, to store archived items directly in the
4547 datetree, use \"~/org/datetree.org::datetree/\".
4549 \"basement::** Finished Tasks\"
4550 Archive in file ./basement (relative path), as level 3 trees
4551 below the level 2 heading \"** Finished Tasks\".
4553 You may set this option on a per-file basis by adding to the buffer a
4554 line like
4556 #+ARCHIVE: basement::** Finished Tasks
4558 You may also define it locally for a subtree by setting an ARCHIVE property
4559 in the entry. If such a property is found in an entry, or anywhere up
4560 the hierarchy, it will be used."
4561 :group 'org-archive
4562 :type 'string)
4564 (defcustom org-agenda-skip-archived-trees t
4565 "Non-nil means the agenda will skip any items located in archived trees.
4566 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4567 variable is no longer recommended, you should leave it at the value t.
4568 Instead, use the key `v' to cycle the archives-mode in the agenda."
4569 :group 'org-archive
4570 :group 'org-agenda-skip
4571 :type 'boolean)
4573 (defcustom org-columns-skip-archived-trees t
4574 "Non-nil means ignore archived trees when creating column view."
4575 :group 'org-archive
4576 :group 'org-properties
4577 :type 'boolean)
4579 (defcustom org-cycle-open-archived-trees nil
4580 "Non-nil means `org-cycle' will open archived trees.
4581 An archived tree is a tree marked with the tag ARCHIVE.
4582 When nil, archived trees will stay folded. You can still open them with
4583 normal outline commands like `show-all', but not with the cycling commands."
4584 :group 'org-archive
4585 :group 'org-cycle
4586 :type 'boolean)
4588 (defcustom org-sparse-tree-open-archived-trees nil
4589 "Non-nil means sparse tree construction shows matches in archived trees.
4590 When nil, matches in these trees are highlighted, but the trees are kept in
4591 collapsed state."
4592 :group 'org-archive
4593 :group 'org-sparse-trees
4594 :type 'boolean)
4596 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4597 "The default date type when building a sparse tree.
4598 When this is nil, a date is a scheduled or a deadline timestamp.
4599 Otherwise, these types are allowed:
4601 all: all timestamps
4602 active: only active timestamps (<...>)
4603 inactive: only inactive timestamps (<...)
4604 scheduled: only scheduled timestamps
4605 deadline: only deadline timestamps"
4606 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4607 (const :tag "All timestamps" all)
4608 (const :tag "Only active timestamps" active)
4609 (const :tag "Only inactive timestamps" inactive)
4610 (const :tag "Only scheduled timestamps" scheduled)
4611 (const :tag "Only deadline timestamps" deadline)
4612 (const :tag "Only closed timestamps" closed))
4613 :version "24.3"
4614 :group 'org-sparse-trees)
4616 (defun org-cycle-hide-archived-subtrees (state)
4617 "Re-hide all archived subtrees after a visibility state change."
4618 (when (and (not org-cycle-open-archived-trees)
4619 (not (memq state '(overview folded))))
4620 (save-excursion
4621 (let* ((globalp (memq state '(contents all)))
4622 (beg (if globalp (point-min) (point)))
4623 (end (if globalp (point-max) (org-end-of-subtree t))))
4624 (org-hide-archived-subtrees beg end)
4625 (goto-char beg)
4626 (if (looking-at (concat ".*:" org-archive-tag ":"))
4627 (message "%s" (substitute-command-keys
4628 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4630 (defun org-force-cycle-archived ()
4631 "Cycle subtree even if it is archived."
4632 (interactive)
4633 (setq this-command 'org-cycle)
4634 (let ((org-cycle-open-archived-trees t))
4635 (call-interactively 'org-cycle)))
4637 (defun org-hide-archived-subtrees (beg end)
4638 "Re-hide all archived subtrees after a visibility state change."
4639 (save-excursion
4640 (let* ((re (concat ":" org-archive-tag ":")))
4641 (goto-char beg)
4642 (while (re-search-forward re end t)
4643 (when (org-at-heading-p)
4644 (org-flag-subtree t)
4645 (org-end-of-subtree t))))))
4647 (declare-function outline-end-of-heading "outline" ())
4648 (declare-function outline-flag-region "outline" (from to flag))
4649 (defun org-flag-subtree (flag)
4650 (save-excursion
4651 (org-back-to-heading t)
4652 (outline-end-of-heading)
4653 (outline-flag-region (point)
4654 (progn (org-end-of-subtree t) (point))
4655 flag)))
4657 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4659 ;; Declare Column View Code
4661 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4662 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4663 (declare-function org-columns-compute "org-colview" (property))
4665 ;; Declare ID code
4667 (declare-function org-id-store-link "org-id")
4668 (declare-function org-id-locations-load "org-id")
4669 (declare-function org-id-locations-save "org-id")
4670 (defvar org-id-track-globally)
4672 ;;; Variables for pre-computed regular expressions, all buffer local
4674 (defvar org-todo-regexp nil
4675 "Matches any of the TODO state keywords.")
4676 (make-variable-buffer-local 'org-todo-regexp)
4677 (defvar org-not-done-regexp nil
4678 "Matches any of the TODO state keywords except the last one.")
4679 (make-variable-buffer-local 'org-not-done-regexp)
4680 (defvar org-not-done-heading-regexp nil
4681 "Matches a TODO headline that is not done.")
4682 (make-variable-buffer-local 'org-not-done-regexp)
4683 (defvar org-todo-line-regexp nil
4684 "Matches a headline and puts TODO state into group 2 if present.")
4685 (make-variable-buffer-local 'org-todo-line-regexp)
4686 (defvar org-complex-heading-regexp nil
4687 "Matches a headline and puts everything into groups:
4688 group 1: the stars
4689 group 2: The todo keyword, maybe
4690 group 3: Priority cookie
4691 group 4: True headline
4692 group 5: Tags")
4693 (make-variable-buffer-local 'org-complex-heading-regexp)
4694 (defvar org-complex-heading-regexp-format nil
4695 "Printf format to make regexp to match an exact headline.
4696 This regexp will match the headline of any node which has the
4697 exact headline text that is put into the format, but may have any
4698 TODO state, priority and tags.")
4699 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4700 (defvar org-todo-line-tags-regexp nil
4701 "Matches a headline and puts TODO state into group 2 if present.
4702 Also put tags into group 4 if tags are present.")
4703 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4704 (defvar org-ds-keyword-length 12
4705 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4706 (make-variable-buffer-local 'org-ds-keyword-length)
4707 (defvar org-deadline-regexp nil
4708 "Matches the DEADLINE keyword.")
4709 (make-variable-buffer-local 'org-deadline-regexp)
4710 (defvar org-deadline-time-regexp nil
4711 "Matches the DEADLINE keyword together with a time stamp.")
4712 (make-variable-buffer-local 'org-deadline-time-regexp)
4713 (defvar org-deadline-time-hour-regexp nil
4714 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4715 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4716 (defvar org-deadline-line-regexp nil
4717 "Matches the DEADLINE keyword and the rest of the line.")
4718 (make-variable-buffer-local 'org-deadline-line-regexp)
4719 (defvar org-scheduled-regexp nil
4720 "Matches the SCHEDULED keyword.")
4721 (make-variable-buffer-local 'org-scheduled-regexp)
4722 (defvar org-scheduled-time-regexp nil
4723 "Matches the SCHEDULED keyword together with a time stamp.")
4724 (make-variable-buffer-local 'org-scheduled-time-regexp)
4725 (defvar org-scheduled-time-hour-regexp nil
4726 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4727 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4728 (defvar org-closed-time-regexp nil
4729 "Matches the CLOSED keyword together with a time stamp.")
4730 (make-variable-buffer-local 'org-closed-time-regexp)
4732 (defvar org-keyword-time-regexp nil
4733 "Matches any of the 4 keywords, together with the time stamp.")
4734 (make-variable-buffer-local 'org-keyword-time-regexp)
4735 (defvar org-keyword-time-not-clock-regexp nil
4736 "Matches any of the 3 keywords, together with the time stamp.")
4737 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4738 (defvar org-maybe-keyword-time-regexp nil
4739 "Matches a timestamp, possibly preceded by a keyword.")
4740 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4741 (defvar org-all-time-keywords nil
4742 "List of time keywords.")
4743 (make-variable-buffer-local 'org-all-time-keywords)
4745 (defconst org-plain-time-of-day-regexp
4746 (concat
4747 "\\(\\<[012]?[0-9]"
4748 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4749 "\\(--?"
4750 "\\(\\<[012]?[0-9]"
4751 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4752 "\\)?")
4753 "Regular expression to match a plain time or time range.
4754 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4755 groups carry important information:
4756 0 the full match
4757 1 the first time, range or not
4758 8 the second time, if it is a range.")
4760 (defconst org-plain-time-extension-regexp
4761 (concat
4762 "\\(\\<[012]?[0-9]"
4763 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4764 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4765 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4766 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4767 groups carry important information:
4768 0 the full match
4769 7 hours of duration
4770 9 minutes of duration")
4772 (defconst org-stamp-time-of-day-regexp
4773 (concat
4774 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4775 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4776 "\\(--?"
4777 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4778 "Regular expression to match a timestamp time or time range.
4779 After a match, the following groups carry important information:
4780 0 the full match
4781 1 date plus weekday, for back referencing to make sure both times are on the same day
4782 2 the first time, range or not
4783 4 the second time, if it is a range.")
4785 (defconst org-startup-options
4786 '(("fold" org-startup-folded t)
4787 ("overview" org-startup-folded t)
4788 ("nofold" org-startup-folded nil)
4789 ("showall" org-startup-folded nil)
4790 ("showeverything" org-startup-folded showeverything)
4791 ("content" org-startup-folded content)
4792 ("indent" org-startup-indented t)
4793 ("noindent" org-startup-indented nil)
4794 ("hidestars" org-hide-leading-stars t)
4795 ("showstars" org-hide-leading-stars nil)
4796 ("odd" org-odd-levels-only t)
4797 ("oddeven" org-odd-levels-only nil)
4798 ("align" org-startup-align-all-tables t)
4799 ("noalign" org-startup-align-all-tables nil)
4800 ("inlineimages" org-startup-with-inline-images t)
4801 ("noinlineimages" org-startup-with-inline-images nil)
4802 ("latexpreview" org-startup-with-latex-preview t)
4803 ("nolatexpreview" org-startup-with-latex-preview nil)
4804 ("customtime" org-display-custom-times t)
4805 ("logdone" org-log-done time)
4806 ("lognotedone" org-log-done note)
4807 ("nologdone" org-log-done nil)
4808 ("lognoteclock-out" org-log-note-clock-out t)
4809 ("nolognoteclock-out" org-log-note-clock-out nil)
4810 ("logrepeat" org-log-repeat state)
4811 ("lognoterepeat" org-log-repeat note)
4812 ("logdrawer" org-log-into-drawer t)
4813 ("nologdrawer" org-log-into-drawer nil)
4814 ("logstatesreversed" org-log-states-order-reversed t)
4815 ("nologstatesreversed" org-log-states-order-reversed nil)
4816 ("nologrepeat" org-log-repeat nil)
4817 ("logreschedule" org-log-reschedule time)
4818 ("lognotereschedule" org-log-reschedule note)
4819 ("nologreschedule" org-log-reschedule nil)
4820 ("logredeadline" org-log-redeadline time)
4821 ("lognoteredeadline" org-log-redeadline note)
4822 ("nologredeadline" org-log-redeadline nil)
4823 ("logrefile" org-log-refile time)
4824 ("lognoterefile" org-log-refile note)
4825 ("nologrefile" org-log-refile nil)
4826 ("fninline" org-footnote-define-inline t)
4827 ("nofninline" org-footnote-define-inline nil)
4828 ("fnlocal" org-footnote-section nil)
4829 ("fnauto" org-footnote-auto-label t)
4830 ("fnprompt" org-footnote-auto-label nil)
4831 ("fnconfirm" org-footnote-auto-label confirm)
4832 ("fnplain" org-footnote-auto-label plain)
4833 ("fnadjust" org-footnote-auto-adjust t)
4834 ("nofnadjust" org-footnote-auto-adjust nil)
4835 ("constcgs" constants-unit-system cgs)
4836 ("constSI" constants-unit-system SI)
4837 ("noptag" org-tag-persistent-alist nil)
4838 ("hideblocks" org-hide-block-startup t)
4839 ("nohideblocks" org-hide-block-startup nil)
4840 ("beamer" org-startup-with-beamer-mode t)
4841 ("entitiespretty" org-pretty-entities t)
4842 ("entitiesplain" org-pretty-entities nil))
4843 "Variable associated with STARTUP options for org-mode.
4844 Each element is a list of three items: the startup options (as written
4845 in the #+STARTUP line), the corresponding variable, and the value to set
4846 this variable to if the option is found. An optional forth element PUSH
4847 means to push this value onto the list in the variable.")
4849 (defun org-update-property-plist (key val props)
4850 "Update PROPS with KEY and VAL."
4851 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4852 (key (if appending (substring key 0 (- (length key) 1)) key))
4853 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4854 (previous (cdr (assoc key props))))
4855 (if appending
4856 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4857 (cons (cons key val) remainder))))
4859 (defcustom org-group-tags t
4860 "When non-nil (the default), use group tags.
4861 This can be turned on/off through `org-toggle-tags-groups'."
4862 :group 'org-tags
4863 :group 'org-startup
4864 :type 'boolean)
4866 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4868 (defun org-toggle-tags-groups ()
4869 "Toggle support for group tags.
4870 Support for group tags is controlled by the option
4871 `org-group-tags', which is non-nil by default."
4872 (interactive)
4873 (setq org-group-tags (not org-group-tags))
4874 (cond ((and (derived-mode-p 'org-agenda-mode)
4875 org-group-tags)
4876 (org-agenda-redo))
4877 ((derived-mode-p 'org-mode)
4878 (let ((org-inhibit-startup t)) (org-mode))))
4879 (message "Groups tags support has been turned %s"
4880 (if org-group-tags "on" "off")))
4882 (defun org-set-regexps-and-options-for-tags ()
4883 "Precompute variables used for tags."
4884 (when (derived-mode-p 'org-mode)
4885 (org-set-local 'org-file-tags nil)
4886 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4887 (splitre "[ \t]+")
4888 (start 0)
4889 tags ftags key value)
4890 (save-excursion
4891 (save-restriction
4892 (widen)
4893 (goto-char (point-min))
4894 (while (re-search-forward re nil t)
4895 (setq key (upcase (org-match-string-no-properties 1))
4896 value (org-match-string-no-properties 2))
4897 (if (stringp value) (setq value (org-trim value)))
4898 (cond
4899 ((equal key "TAGS")
4900 (setq tags (append tags (if tags '("\\n") nil)
4901 (org-split-string value splitre))))
4902 ((equal key "FILETAGS")
4903 (when (string-match "\\S-" value)
4904 (setq ftags
4905 (append
4906 ftags
4907 (apply 'append
4908 (mapcar (lambda (x) (org-split-string x ":"))
4909 (org-split-string value)))))))))))
4910 ;; Process the file tags.
4911 (and ftags (org-set-local 'org-file-tags
4912 (mapcar 'org-add-prop-inherited ftags)))
4913 (org-set-local 'org-tag-groups-alist nil)
4914 ;; Process the tags.
4915 (when (and (not tags) org-tag-alist)
4916 (setq tags
4917 (mapcar
4918 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4919 ((eq (car tg) :endgroup) "}")
4920 ((eq (car tg) :grouptags) ":")
4921 ((eq (car tg) :newline) "\n")
4922 (t (concat (car tg)
4923 (if (characterp (cdr tg))
4924 (format "(%s)" (char-to-string (cdr tg))) "")))))
4925 org-tag-alist)))
4926 (let (e tgs g)
4927 (while (setq e (pop tags))
4928 (cond
4929 ((equal e "{")
4930 (progn (push '(:startgroup) tgs)
4931 (when (equal (nth 1 tags) ":")
4932 (push (list (replace-regexp-in-string
4933 "(.+)$" "" (nth 0 tags)))
4934 org-tag-groups-alist)
4935 (setq g 0))))
4936 ((equal e ":") (push '(:grouptags) tgs))
4937 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4938 ((equal e "\\n") (push '(:newline) tgs))
4939 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4940 (push (cons (match-string 1 e)
4941 (string-to-char (match-string 2 e))) tgs)
4942 (if (and g (> g 0))
4943 (setcar org-tag-groups-alist
4944 (append (car org-tag-groups-alist)
4945 (list (match-string 1 e)))))
4946 (if g (setq g (1+ g))))
4947 (t (push (list e) tgs)
4948 (if (and g (> g 0))
4949 (setcar org-tag-groups-alist
4950 (append (car org-tag-groups-alist) (list e))))
4951 (if g (setq g (1+ g))))))
4952 (org-set-local 'org-tag-alist nil)
4953 (while (setq e (pop tgs))
4954 (or (and (stringp (car e))
4955 (assoc (car e) org-tag-alist))
4956 (push e org-tag-alist)))
4957 ;; Return a list with tag variables
4958 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4960 (defvar org-ota nil)
4961 (defun org-set-regexps-and-options ()
4962 "Precompute regular expressions used in the current buffer."
4963 (when (derived-mode-p 'org-mode)
4964 (org-set-local 'org-todo-kwd-alist nil)
4965 (org-set-local 'org-todo-key-alist nil)
4966 (org-set-local 'org-todo-key-trigger nil)
4967 (org-set-local 'org-todo-keywords-1 nil)
4968 (org-set-local 'org-done-keywords nil)
4969 (org-set-local 'org-todo-heads nil)
4970 (org-set-local 'org-todo-sets nil)
4971 (org-set-local 'org-todo-log-states nil)
4972 (org-set-local 'org-file-properties nil)
4973 (let ((re (org-make-options-regexp
4974 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4975 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4976 "SETUPFILE" "OPTIONS")
4977 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4978 (splitre "[ \t]+")
4979 (scripts org-use-sub-superscripts)
4980 kwds kws0 kwsa key log value cat arch const links hw dws
4981 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4982 (start 0))
4983 (save-excursion
4984 (save-restriction
4985 (widen)
4986 (goto-char (point-min))
4987 (while
4988 (or (and
4989 ext-setup-or-nil
4990 (not org-ota)
4991 (let (ret)
4992 (with-temp-buffer
4993 (insert ext-setup-or-nil)
4994 (let ((major-mode 'org-mode) org-ota)
4995 (setq ret (save-match-data
4996 (org-set-regexps-and-options-for-tags)))))
4997 ;; Append setupfile tags to existing tags
4998 (setq org-ota t)
4999 (setq org-file-tags
5000 (delq nil (append org-file-tags (nth 0 ret)))
5001 org-tag-alist
5002 (delq nil (append org-tag-alist (nth 1 ret)))
5003 org-tag-groups-alist
5004 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
5005 (and ext-setup-or-nil
5006 (string-match re ext-setup-or-nil start)
5007 (setq start (match-end 0)))
5008 (and (setq ext-setup-or-nil nil start 0)
5009 (re-search-forward re nil t)))
5010 (setq key (upcase (match-string 1 ext-setup-or-nil))
5011 value (org-match-string-no-properties 2 ext-setup-or-nil))
5012 (if (stringp value) (setq value (org-trim value)))
5013 (cond
5014 ((equal key "CATEGORY")
5015 (setq cat value))
5016 ((member key '("SEQ_TODO" "TODO"))
5017 (push (cons 'sequence (org-split-string value splitre)) kwds))
5018 ((equal key "TYP_TODO")
5019 (push (cons 'type (org-split-string value splitre)) kwds))
5020 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
5021 ;; general TODO-like setup
5022 (push (cons (intern (downcase (match-string 1 key)))
5023 (org-split-string value splitre)) kwds))
5024 ((equal key "COLUMNS")
5025 (org-set-local 'org-columns-default-format value))
5026 ((equal key "LINK")
5027 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5028 (push (cons (match-string 1 value)
5029 (org-trim (match-string 2 value)))
5030 links)))
5031 ((equal key "PRIORITIES")
5032 (setq prio (org-split-string value " +")))
5033 ((equal key "PROPERTY")
5034 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5035 (setq props (org-update-property-plist (match-string 1 value)
5036 (match-string 2 value)
5037 props))))
5038 ((equal key "CONSTANTS")
5039 (org-table-set-constants))
5040 ((equal key "STARTUP")
5041 (let ((opts (org-split-string value splitre))
5042 l var val)
5043 (while (setq l (pop opts))
5044 (when (setq l (assoc l org-startup-options))
5045 (setq var (nth 1 l) val (nth 2 l))
5046 (if (not (nth 3 l))
5047 (set (make-local-variable var) val)
5048 (if (not (listp (symbol-value var)))
5049 (set (make-local-variable var) nil))
5050 (set (make-local-variable var) (symbol-value var))
5051 (add-to-list var val))))))
5052 ((equal key "ARCHIVE")
5053 (setq arch value)
5054 (remove-text-properties 0 (length arch)
5055 '(face t fontified t) arch))
5056 ((equal key "OPTIONS")
5057 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5058 (setq scripts (read (match-string 2 value)))))
5059 ((and (equal key "SETUPFILE")
5060 ;; Prevent checking in Gnus messages
5061 (not buffer-read-only))
5062 (setq setup-contents (org-file-contents
5063 (expand-file-name
5064 (org-remove-double-quotes value))
5065 'noerror))
5066 (if (not ext-setup-or-nil)
5067 (setq ext-setup-or-nil setup-contents start 0)
5068 (setq ext-setup-or-nil
5069 (concat (substring ext-setup-or-nil 0 start)
5070 "\n" setup-contents "\n"
5071 (substring ext-setup-or-nil start)))))))
5072 ;; search for property blocks
5073 (goto-char (point-min))
5074 (while (re-search-forward org-block-regexp nil t)
5075 (when (equal "PROPERTY" (upcase (match-string 1)))
5076 (setq value (replace-regexp-in-string
5077 "[\n\r]" " " (match-string 4)))
5078 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5079 (setq props (org-update-property-plist (match-string 1 value)
5080 (match-string 2 value)
5081 props)))))))
5082 (org-set-local 'org-use-sub-superscripts scripts)
5083 (when cat
5084 (org-set-local 'org-category (intern cat))
5085 (push (cons "CATEGORY" cat) props))
5086 (when prio
5087 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5088 (setq prio (mapcar 'string-to-char prio))
5089 (org-set-local 'org-highest-priority (nth 0 prio))
5090 (org-set-local 'org-lowest-priority (nth 1 prio))
5091 (org-set-local 'org-default-priority (nth 2 prio)))
5092 (and props (org-set-local 'org-file-properties (nreverse props)))
5093 (and arch (org-set-local 'org-archive-location arch))
5094 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5095 ;; Process the TODO keywords
5096 (unless kwds
5097 ;; Use the global values as if they had been given locally.
5098 (setq kwds (default-value 'org-todo-keywords))
5099 (if (stringp (car kwds))
5100 (setq kwds (list (cons org-todo-interpretation
5101 (default-value 'org-todo-keywords)))))
5102 (setq kwds (reverse kwds)))
5103 (setq kwds (nreverse kwds))
5104 (let (inter kws kw)
5105 (while (setq kws (pop kwds))
5106 (let ((kws (or
5107 (run-hook-with-args-until-success
5108 'org-todo-setup-filter-hook kws)
5109 kws)))
5110 (setq inter (pop kws) sep (member "|" kws)
5111 kws0 (delete "|" (copy-sequence kws))
5112 kwsa nil
5113 kws1 (mapcar
5114 (lambda (x)
5115 ;; 1 2
5116 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5117 (progn
5118 (setq kw (match-string 1 x)
5119 key (and (match-end 2) (match-string 2 x))
5120 log (org-extract-log-state-settings x))
5121 (push (cons kw (and key (string-to-char key))) kwsa)
5122 (and log (push log org-todo-log-states))
5124 (error "Invalid TODO keyword %s" x)))
5125 kws0)
5126 kwsa (if kwsa (append '((:startgroup))
5127 (nreverse kwsa)
5128 '((:endgroup))))
5129 hw (car kws1)
5130 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5131 tail (list inter hw (car dws) (org-last dws))))
5132 (add-to-list 'org-todo-heads hw 'append)
5133 (push kws1 org-todo-sets)
5134 (setq org-done-keywords (append org-done-keywords dws nil))
5135 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5136 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5137 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5138 (setq org-todo-sets (nreverse org-todo-sets)
5139 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5140 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5141 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5142 ;; Compute the regular expressions and other local variables.
5143 ;; Using `org-outline-regexp-bol' would complicate them much,
5144 ;; because of the fixed white space at the end of that string.
5145 (if (not org-done-keywords)
5146 (setq org-done-keywords (and org-todo-keywords-1
5147 (list (org-last org-todo-keywords-1)))))
5148 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5149 (length org-scheduled-string)
5150 (length org-clock-string)
5151 (length org-closed-string)))
5152 org-not-done-keywords
5153 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5154 org-todo-regexp
5155 (concat "\\("
5156 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5157 "\\)")
5158 org-not-done-regexp
5159 (concat "\\("
5160 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5161 "\\)")
5162 org-not-done-heading-regexp
5163 (format org-heading-keyword-regexp-format org-not-done-regexp)
5164 org-todo-line-regexp
5165 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5166 org-complex-heading-regexp
5167 (concat "^\\(\\*+\\)"
5168 "\\(?: +" org-todo-regexp "\\)?"
5169 "\\(?: +\\(\\[#.\\]\\)\\)?"
5170 "\\(?: +\\(.*?\\)\\)??"
5171 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5172 "[ \t]*$")
5173 org-complex-heading-regexp-format
5174 (concat "^\\(\\*+\\)"
5175 "\\(?: +" org-todo-regexp "\\)?"
5176 "\\(?: +\\(\\[#.\\]\\)\\)?"
5177 "\\(?: +"
5178 ;; Stats cookies can be stuck to body.
5179 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5180 "\\(%s\\)"
5181 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5182 "\\)"
5183 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5184 "[ \t]*$")
5185 org-todo-line-tags-regexp
5186 (concat "^\\(\\*+\\)"
5187 "\\(?: +" org-todo-regexp "\\)?"
5188 "\\(?: +\\(.*?\\)\\)??"
5189 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5190 "[ \t]*$")
5191 org-deadline-regexp (concat "\\<" org-deadline-string)
5192 org-deadline-time-regexp
5193 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5194 org-deadline-time-hour-regexp
5195 (concat "\\<" org-deadline-string
5196 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5197 org-deadline-line-regexp
5198 (concat "\\<\\(" org-deadline-string "\\).*")
5199 org-scheduled-regexp
5200 (concat "\\<" org-scheduled-string)
5201 org-scheduled-time-regexp
5202 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5203 org-scheduled-time-hour-regexp
5204 (concat "\\<" org-scheduled-string
5205 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5206 org-closed-time-regexp
5207 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5208 org-keyword-time-regexp
5209 (concat "\\<\\(" org-scheduled-string
5210 "\\|" org-deadline-string
5211 "\\|" org-closed-string
5212 "\\|" org-clock-string "\\)"
5213 " *[[<]\\([^]>]+\\)[]>]")
5214 org-keyword-time-not-clock-regexp
5215 (concat "\\<\\(" org-scheduled-string
5216 "\\|" org-deadline-string
5217 "\\|" org-closed-string
5218 "\\)"
5219 " *[[<]\\([^]>]+\\)[]>]")
5220 org-maybe-keyword-time-regexp
5221 (concat "\\(\\<\\(" org-scheduled-string
5222 "\\|" org-deadline-string
5223 "\\|" org-closed-string
5224 "\\|" org-clock-string "\\)\\)?"
5225 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5226 org-all-time-keywords
5227 (mapcar (lambda (w) (substring w 0 -1))
5228 (list org-scheduled-string org-deadline-string
5229 org-clock-string org-closed-string)))
5230 (setq org-ota nil)
5231 (org-compute-latex-and-related-regexp))))
5233 (defun org-file-contents (file &optional noerror)
5234 "Return the contents of FILE, as a string."
5235 (if (or (not file)
5236 (not (file-readable-p file)))
5237 (if noerror
5238 (message "Cannot read file \"%s\"" file)
5239 (error "Cannot read file \"%s\"" file))
5240 (with-temp-buffer
5241 (insert-file-contents file)
5242 (buffer-string))))
5244 (defun org-extract-log-state-settings (x)
5245 "Extract the log state setting from a TODO keyword string.
5246 This will extract info from a string like \"WAIT(w@/!)\"."
5247 (let (kw key log1 log2)
5248 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5249 (setq kw (match-string 1 x)
5250 key (and (match-end 2) (match-string 2 x))
5251 log1 (and (match-end 3) (match-string 3 x))
5252 log2 (and (match-end 4) (match-string 4 x)))
5253 (and (or log1 log2)
5254 (list kw
5255 (and log1 (if (equal log1 "!") 'time 'note))
5256 (and log2 (if (equal log2 "!") 'time 'note)))))))
5258 (defun org-remove-keyword-keys (list)
5259 "Remove a pair of parenthesis at the end of each string in LIST."
5260 (mapcar (lambda (x)
5261 (if (string-match "(.*)$" x)
5262 (substring x 0 (match-beginning 0))
5264 list))
5266 (defun org-assign-fast-keys (alist)
5267 "Assign fast keys to a keyword-key alist.
5268 Respect keys that are already there."
5269 (let (new e (alt ?0))
5270 (while (setq e (pop alist))
5271 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5272 (cdr e)) ;; Key already assigned.
5273 (push e new)
5274 (let ((clist (string-to-list (downcase (car e))))
5275 (used (append new alist)))
5276 (when (= (car clist) ?@)
5277 (pop clist))
5278 (while (and clist (rassoc (car clist) used))
5279 (pop clist))
5280 (unless clist
5281 (while (rassoc alt used)
5282 (incf alt)))
5283 (push (cons (car e) (or (car clist) alt)) new))))
5284 (nreverse new)))
5286 ;;; Some variables used in various places
5288 (defvar org-window-configuration nil
5289 "Used in various places to store a window configuration.")
5290 (defvar org-selected-window nil
5291 "Used in various places to store a window configuration.")
5292 (defvar org-finish-function nil
5293 "Function to be called when `C-c C-c' is used.
5294 This is for getting out of special buffers like capture.")
5297 ;; FIXME: Occasionally check by commenting these, to make sure
5298 ;; no other functions uses these, forgetting to let-bind them.
5299 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5300 (defvar org-last-state)
5301 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5303 ;; Defined somewhere in this file, but used before definition.
5304 (defvar org-entities) ;; defined in org-entities.el
5305 (defvar org-struct-menu)
5306 (defvar org-org-menu)
5307 (defvar org-tbl-menu)
5309 ;;;; Define the Org-mode
5311 ;; We use a before-change function to check if a table might need
5312 ;; an update.
5313 (defvar org-table-may-need-update t
5314 "Indicates that a table might need an update.
5315 This variable is set by `org-before-change-function'.
5316 `org-table-align' sets it back to nil.")
5317 (defun org-before-change-function (beg end)
5318 "Every change indicates that a table might need an update."
5319 (setq org-table-may-need-update t))
5320 (defvar org-mode-map)
5321 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5322 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5323 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5324 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5325 (defvar org-table-buffer-is-an nil)
5327 (defvar bidi-paragraph-direction)
5328 (defvar buffer-face-mode-face)
5330 (require 'outline)
5331 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5332 (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"))
5333 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5335 ;; Other stuff we need.
5336 (require 'time-date)
5337 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5338 (require 'easymenu)
5339 (require 'overlay)
5341 ;; (require 'org-macs) moved higher up in the file before it is first used
5342 (require 'org-entities)
5343 ;; (require 'org-compat) moved higher up in the file before it is first used
5344 (require 'org-faces)
5345 (require 'org-list)
5346 (require 'org-pcomplete)
5347 (require 'org-src)
5348 (require 'org-footnote)
5349 (require 'org-macro)
5351 ;; babel
5352 (require 'ob)
5354 ;;;###autoload
5355 (define-derived-mode org-mode outline-mode "Org"
5356 "Outline-based notes management and organizer, alias
5357 \"Carsten's outline-mode for keeping track of everything.\"
5359 Org-mode develops organizational tasks around a NOTES file which
5360 contains information about projects as plain text. Org-mode is
5361 implemented on top of outline-mode, which is ideal to keep the content
5362 of large files well structured. It supports ToDo items, deadlines and
5363 time stamps, which magically appear in the diary listing of the Emacs
5364 calendar. Tables are easily created with a built-in table editor.
5365 Plain text URL-like links connect to websites, emails (VM), Usenet
5366 messages (Gnus), BBDB entries, and any files related to the project.
5367 For printing and sharing of notes, an Org-mode file (or a part of it)
5368 can be exported as a structured ASCII or HTML file.
5370 The following commands are available:
5372 \\{org-mode-map}"
5374 ;; Get rid of Outline menus, they are not needed
5375 ;; Need to do this here because define-derived-mode sets up
5376 ;; the keymap so late. Still, it is a waste to call this each time
5377 ;; we switch another buffer into org-mode.
5378 (if (featurep 'xemacs)
5379 (when (boundp 'outline-mode-menu-heading)
5380 ;; Assume this is Greg's port, it uses easymenu
5381 (easy-menu-remove outline-mode-menu-heading)
5382 (easy-menu-remove outline-mode-menu-show)
5383 (easy-menu-remove outline-mode-menu-hide))
5384 (define-key org-mode-map [menu-bar headings] 'undefined)
5385 (define-key org-mode-map [menu-bar hide] 'undefined)
5386 (define-key org-mode-map [menu-bar show] 'undefined))
5388 (org-load-modules-maybe)
5389 (easy-menu-add org-org-menu)
5390 (easy-menu-add org-tbl-menu)
5391 (org-install-agenda-files-menu)
5392 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5393 (add-to-invisibility-spec '(org-cwidth))
5394 (add-to-invisibility-spec '(org-hide-block . t))
5395 (when (featurep 'xemacs)
5396 (org-set-local 'line-move-ignore-invisible t))
5397 (org-set-local 'outline-regexp org-outline-regexp)
5398 (org-set-local 'outline-level 'org-outline-level)
5399 (setq bidi-paragraph-direction 'left-to-right)
5400 (when (and org-ellipsis
5401 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5402 (fboundp 'make-glyph-code))
5403 (unless org-display-table
5404 (setq org-display-table (make-display-table)))
5405 (set-display-table-slot
5406 org-display-table 4
5407 (vconcat (mapcar
5408 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5409 org-ellipsis)))
5410 (if (stringp org-ellipsis) org-ellipsis "..."))))
5411 (setq buffer-display-table org-display-table))
5412 (org-set-regexps-and-options-for-tags)
5413 (org-set-regexps-and-options)
5414 (org-set-font-lock-defaults)
5415 (when (and org-tag-faces (not org-tags-special-faces-re))
5416 ;; tag faces set outside customize.... force initialization.
5417 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5418 ;; Calc embedded
5419 (org-set-local 'calc-embedded-open-mode "# ")
5420 ;; Modify a few syntax entries
5421 (modify-syntax-entry ?@ "w")
5422 (modify-syntax-entry ?\" "\"")
5423 (if org-startup-truncated (setq truncate-lines t))
5424 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5425 (org-set-local 'font-lock-unfontify-region-function
5426 'org-unfontify-region)
5427 ;; Activate before-change-function
5428 (org-set-local 'org-table-may-need-update t)
5429 (org-add-hook 'before-change-functions 'org-before-change-function nil
5430 'local)
5431 ;; Check for running clock before killing a buffer
5432 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5433 ;; Initialize macros templates.
5434 (org-macro-initialize-templates)
5435 ;; Initialize radio targets.
5436 (org-update-radio-target-regexp)
5437 ;; Indentation.
5438 (org-set-local 'indent-line-function 'org-indent-line)
5439 (org-set-local 'indent-region-function 'org-indent-region)
5440 ;; Filling and auto-filling.
5441 (org-setup-filling)
5442 ;; Comments.
5443 (org-setup-comments-handling)
5444 ;; Initialize cache.
5445 (org-element-cache-reset)
5446 ;; Beginning/end of defun
5447 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5448 (org-set-local 'end-of-defun-function 'org-forward-element)
5449 ;; Next error for sparse trees
5450 (org-set-local 'next-error-function 'org-occur-next-match)
5451 ;; Make sure dependence stuff works reliably, even for users who set it
5452 ;; too late :-(
5453 (if org-enforce-todo-dependencies
5454 (add-hook 'org-blocker-hook
5455 'org-block-todo-from-children-or-siblings-or-parent)
5456 (remove-hook 'org-blocker-hook
5457 'org-block-todo-from-children-or-siblings-or-parent))
5458 (if org-enforce-todo-checkbox-dependencies
5459 (add-hook 'org-blocker-hook
5460 'org-block-todo-from-checkboxes)
5461 (remove-hook 'org-blocker-hook
5462 'org-block-todo-from-checkboxes))
5464 ;; Align options lines
5465 (org-set-local
5466 'align-mode-rules-list
5467 '((org-in-buffer-settings
5468 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5469 (modes . '(org-mode)))))
5471 ;; Imenu
5472 (org-set-local 'imenu-create-index-function
5473 'org-imenu-get-tree)
5475 ;; Make isearch reveal context
5476 (if (or (featurep 'xemacs)
5477 (not (boundp 'outline-isearch-open-invisible-function)))
5478 ;; Emacs 21 and XEmacs make use of the hook
5479 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5480 ;; Emacs 22 deals with this through a special variable
5481 (org-set-local 'outline-isearch-open-invisible-function
5482 (lambda (&rest ignore) (org-show-context 'isearch)))
5483 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5485 ;; Setup the pcomplete hooks
5486 (set (make-local-variable 'pcomplete-command-completion-function)
5487 'org-pcomplete-initial)
5488 (set (make-local-variable 'pcomplete-command-name-function)
5489 'org-command-at-point)
5490 (set (make-local-variable 'pcomplete-default-completion-function)
5491 'ignore)
5492 (set (make-local-variable 'pcomplete-parse-arguments-function)
5493 'org-parse-arguments)
5494 (set (make-local-variable 'pcomplete-termination-string) "")
5495 (when (>= emacs-major-version 23)
5496 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5498 ;; If empty file that did not turn on org-mode automatically, make it to.
5499 (if (and org-insert-mode-line-in-empty-file
5500 (org-called-interactively-p 'any)
5501 (= (point-min) (point-max)))
5502 (insert "# -*- mode: org -*-\n\n"))
5503 (unless org-inhibit-startup
5504 (org-unmodified
5505 (and org-startup-with-beamer-mode (org-beamer-mode))
5506 (when org-startup-align-all-tables
5507 (org-table-map-tables 'org-table-align 'quietly))
5508 (when org-startup-with-inline-images
5509 (org-display-inline-images))
5510 (when org-startup-with-latex-preview
5511 (org-preview-latex-fragment))
5512 (unless org-inhibit-startup-visibility-stuff
5513 (org-set-startup-visibility))))
5514 ;; Try to set org-hide correctly
5515 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5517 ;; Update `customize-package-emacs-version-alist'
5518 (add-to-list 'customize-package-emacs-version-alist
5519 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5520 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5521 ("8.2.6" . "24.4")))
5523 (defvar org-mode-transpose-word-syntax-table
5524 (let ((st (make-syntax-table)))
5525 (mapc (lambda(c) (modify-syntax-entry
5526 (string-to-char (car c)) "w p" st))
5527 org-emphasis-alist)
5528 st))
5530 (when (fboundp 'abbrev-table-put)
5531 (abbrev-table-put org-mode-abbrev-table
5532 :parents (list text-mode-abbrev-table)))
5534 (defsubst org-fix-ellipsis-at-bol ()
5535 (save-excursion (goto-char (window-start)) (recenter 0)))
5537 (defun org-find-invisible-foreground ()
5538 (let ((candidates (remove
5539 "unspecified-bg"
5540 (nconc
5541 (list (face-background 'default)
5542 (face-background 'org-default))
5543 (mapcar
5544 (lambda (alist)
5545 (when (boundp alist)
5546 (cdr (assoc 'background-color (symbol-value alist)))))
5547 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5548 (list (face-foreground 'org-hide))))))
5549 (car (remove nil candidates))))
5551 (defun org-current-time (&optional rounding-minutes past)
5552 "Current time, possibly rounded to ROUNDING-MINUTES.
5553 When ROUNDING-MINUTES is not an integer, fall back on the car of
5554 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5555 the rounding returns a past time."
5556 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5557 (car org-time-stamp-rounding-minutes)))
5558 (time (decode-time)) res)
5559 (if (< r 1)
5560 (current-time)
5561 (setq res
5562 (apply 'encode-time
5563 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5564 (nthcdr 2 time))))
5565 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5566 (seconds-to-time (- (org-float-time res) (* r 60)))
5567 res))))
5569 (defun org-today ()
5570 "Return today date, considering `org-extend-today-until'."
5571 (time-to-days
5572 (time-subtract (current-time)
5573 (list 0 (* 3600 org-extend-today-until) 0))))
5575 ;;;; Font-Lock stuff, including the activators
5577 (defvar org-mouse-map (make-sparse-keymap))
5578 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5579 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5580 (when org-mouse-1-follows-link
5581 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5582 (when org-tab-follows-link
5583 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5584 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5586 (require 'font-lock)
5588 (defconst org-non-link-chars "]\t\n\r<>")
5589 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5590 "shell" "elisp" "doi" "message"))
5591 (defvar org-link-types-re nil
5592 "Matches a link that has a url-like prefix like \"http:\"")
5593 (defvar org-link-re-with-space nil
5594 "Matches a link with spaces, optional angular brackets around it.")
5595 (defvar org-link-re-with-space2 nil
5596 "Matches a link with spaces, optional angular brackets around it.")
5597 (defvar org-link-re-with-space3 nil
5598 "Matches a link with spaces, only for internal part in bracket links.")
5599 (defvar org-angle-link-re nil
5600 "Matches link with angular brackets, spaces are allowed.")
5601 (defvar org-plain-link-re nil
5602 "Matches plain link, without spaces.")
5603 (defvar org-bracket-link-regexp nil
5604 "Matches a link in double brackets.")
5605 (defvar org-bracket-link-analytic-regexp nil
5606 "Regular expression used to analyze links.
5607 Here is what the match groups contain after a match:
5608 1: http:
5609 2: http
5610 3: path
5611 4: [desc]
5612 5: desc")
5613 (defvar org-bracket-link-analytic-regexp++ nil
5614 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5615 (defvar org-any-link-re nil
5616 "Regular expression matching any link.")
5618 (defconst org-match-sexp-depth 3
5619 "Number of stacked braces for sub/superscript matching.")
5621 (defun org-create-multibrace-regexp (left right n)
5622 "Create a regular expression which will match a balanced sexp.
5623 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5624 as single character strings.
5625 The regexp returned will match the entire expression including the
5626 delimiters. It will also define a single group which contains the
5627 match except for the outermost delimiters. The maximum depth of
5628 stacked delimiters is N. Escaping delimiters is not possible."
5629 (let* ((nothing (concat "[^" left right "]*?"))
5630 (or "\\|")
5631 (re nothing)
5632 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5633 (while (> n 1)
5634 (setq n (1- n)
5635 re (concat re or next)
5636 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5637 (concat left "\\(" re "\\)" right)))
5639 (defconst org-match-substring-regexp
5640 (concat
5641 "\\(\\S-\\)\\([_^]\\)\\("
5642 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5643 "\\|"
5644 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5645 "\\|"
5646 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5647 "The regular expression matching a sub- or superscript.")
5649 (defconst org-match-substring-with-braces-regexp
5650 (concat
5651 "\\(\\S-\\)\\([_^]\\)"
5652 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5653 "The regular expression matching a sub- or superscript, forcing braces.")
5655 (defun org-make-link-regexps ()
5656 "Update the link regular expressions.
5657 This should be called after the variable `org-link-types' has changed."
5658 (setq org-link-types-re
5659 (concat
5660 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5661 org-link-re-with-space
5662 (concat
5663 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5664 "\\([^" org-non-link-chars " ]"
5665 "[^" org-non-link-chars "]*"
5666 "[^" org-non-link-chars " ]\\)>?")
5667 org-link-re-with-space2
5668 (concat
5669 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5670 "\\([^" org-non-link-chars " ]"
5671 "[^\t\n\r]*"
5672 "[^" org-non-link-chars " ]\\)>?")
5673 org-link-re-with-space3
5674 (concat
5675 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5676 "\\([^" org-non-link-chars " ]"
5677 "[^\t\n\r]*\\)")
5678 org-angle-link-re
5679 (concat
5680 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5681 "\\([^" org-non-link-chars " ]"
5682 "[^" org-non-link-chars "]*"
5683 "\\)>")
5684 org-plain-link-re
5685 (concat
5686 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5687 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5688 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5689 org-bracket-link-regexp
5690 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5691 org-bracket-link-analytic-regexp
5692 (concat
5693 "\\[\\["
5694 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5695 "\\([^]]+\\)"
5696 "\\]"
5697 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5698 "\\]")
5699 org-bracket-link-analytic-regexp++
5700 (concat
5701 "\\[\\["
5702 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5703 "\\([^]]+\\)"
5704 "\\]"
5705 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5706 "\\]")
5707 org-any-link-re
5708 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5709 org-angle-link-re "\\)\\|\\("
5710 org-plain-link-re "\\)")))
5712 (org-make-link-regexps)
5714 (defvar org-emph-face nil)
5716 (defun org-do-emphasis-faces (limit)
5717 "Run through the buffer and add overlays to emphasized strings."
5718 (let (rtn a)
5719 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5720 (if (not (= (char-after (match-beginning 3))
5721 (char-after (match-beginning 4))))
5722 (progn
5723 (setq rtn t)
5724 (setq a (assoc (match-string 3) org-emphasis-alist))
5725 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5726 'face
5727 (nth 1 a))
5728 (and (nth 2 a)
5729 (org-remove-flyspell-overlays-in
5730 (match-beginning 0) (match-end 0)))
5731 (add-text-properties (match-beginning 2) (match-end 2)
5732 '(font-lock-multiline t org-emphasis t))
5733 (when org-hide-emphasis-markers
5734 (add-text-properties (match-end 4) (match-beginning 5)
5735 '(invisible org-link))
5736 (add-text-properties (match-beginning 3) (match-end 3)
5737 '(invisible org-link)))))
5738 (goto-char (1+ (match-beginning 0))))
5739 rtn))
5741 (defun org-emphasize (&optional char)
5742 "Insert or change an emphasis, i.e. a font like bold or italic.
5743 If there is an active region, change that region to a new emphasis.
5744 If there is no region, just insert the marker characters and position
5745 the cursor between them.
5746 CHAR should be the marker character. If it is a space, it means to
5747 remove the emphasis of the selected region.
5748 If CHAR is not given (for example in an interactive call) it will be
5749 prompted for."
5750 (interactive)
5751 (let ((erc org-emphasis-regexp-components)
5752 (prompt "")
5753 (string "") beg end move c s)
5754 (if (org-region-active-p)
5755 (setq beg (region-beginning) end (region-end)
5756 string (buffer-substring beg end))
5757 (setq move t))
5759 (unless char
5760 (message "Emphasis marker or tag: [%s]"
5761 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5762 (setq char (read-char-exclusive)))
5763 (if (equal char ?\ )
5764 (setq s "" move nil)
5765 (unless (assoc (char-to-string char) org-emphasis-alist)
5766 (user-error "No such emphasis marker: \"%c\"" char))
5767 (setq s (char-to-string char)))
5768 (while (and (> (length string) 1)
5769 (equal (substring string 0 1) (substring string -1))
5770 (assoc (substring string 0 1) org-emphasis-alist))
5771 (setq string (substring string 1 -1)))
5772 (setq string (concat s string s))
5773 (if beg (delete-region beg end))
5774 (unless (or (bolp)
5775 (string-match (concat "[" (nth 0 erc) "\n]")
5776 (char-to-string (char-before (point)))))
5777 (insert " "))
5778 (unless (or (eobp)
5779 (string-match (concat "[" (nth 1 erc) "\n]")
5780 (char-to-string (char-after (point)))))
5781 (insert " ") (backward-char 1))
5782 (insert string)
5783 (and move (backward-char 1))))
5785 (defconst org-nonsticky-props
5786 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5788 (defsubst org-rear-nonsticky-at (pos)
5789 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5791 (defun org-activate-plain-links (limit)
5792 "Run through the buffer and add overlays to links."
5793 (let (f hl)
5794 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5795 (not (org-in-src-block-p)))
5796 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5797 (setq f (get-text-property (match-beginning 0) 'face))
5798 (setq hl (org-match-string-no-properties 0))
5799 (if (or (eq f 'org-tag)
5800 (and (listp f) (memq 'org-tag f)))
5802 (add-text-properties (match-beginning 0) (match-end 0)
5803 (list 'mouse-face 'highlight
5804 'face 'org-link
5805 'htmlize-link `(:uri ,hl)
5806 'keymap org-mouse-map))
5807 (org-rear-nonsticky-at (match-end 0)))
5808 t)))
5810 (defun org-activate-code (limit)
5811 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5812 (progn
5813 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5814 (remove-text-properties (match-beginning 0) (match-end 0)
5815 '(display t invisible t intangible t))
5816 t)))
5818 (defcustom org-src-fontify-natively t
5819 "When non-nil, fontify code in code blocks."
5820 :type 'boolean
5821 :version "24.4"
5822 :package-version '(Org . "8.3")
5823 :group 'org-appearance
5824 :group 'org-babel)
5826 (defcustom org-allow-promoting-top-level-subtree nil
5827 "When non-nil, allow promoting a top level subtree.
5828 The leading star of the top level headline will be replaced
5829 by a #."
5830 :type 'boolean
5831 :version "24.1"
5832 :group 'org-appearance)
5834 (defun org-fontify-meta-lines-and-blocks (limit)
5835 (condition-case nil
5836 (org-fontify-meta-lines-and-blocks-1 limit)
5837 (error (message "org-mode fontification error"))))
5839 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5840 "Fontify #+ lines and blocks."
5841 (let ((case-fold-search t))
5842 (if (re-search-forward
5843 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5844 limit t)
5845 (let ((beg (match-beginning 0))
5846 (block-start (match-end 0))
5847 (block-end nil)
5848 (lang (match-string 7))
5849 (beg1 (line-beginning-position 2))
5850 (dc1 (downcase (match-string 2)))
5851 (dc3 (downcase (match-string 3)))
5852 end end1 quoting block-type ovl)
5853 (cond
5854 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5855 ;; a single line of backend-specific content
5856 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5857 (remove-text-properties (match-beginning 0) (match-end 0)
5858 '(display t invisible t intangible t))
5859 (add-text-properties (match-beginning 1) (match-end 3)
5860 '(font-lock-fontified t face org-meta-line))
5861 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5862 '(font-lock-fontified t face org-block))
5863 ; for backend-specific code
5865 ((and (match-end 4) (equal dc3 "+begin"))
5866 ;; Truly a block
5867 (setq block-type (downcase (match-string 5))
5868 quoting (member block-type org-protecting-blocks))
5869 (when (re-search-forward
5870 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5871 nil t) ;; on purpose, we look further than LIMIT
5872 (setq end (min (point-max) (match-end 0))
5873 end1 (min (point-max) (1- (match-beginning 0))))
5874 (setq block-end (match-beginning 0))
5875 (when quoting
5876 (org-remove-flyspell-overlays-in beg1 end1)
5877 (remove-text-properties beg end
5878 '(display t invisible t intangible t)))
5879 (add-text-properties
5880 beg end '(font-lock-fontified t font-lock-multiline t))
5881 (add-text-properties beg beg1 '(face org-meta-line))
5882 (org-remove-flyspell-overlays-in beg beg1)
5883 (add-text-properties ; For end_src
5884 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5885 (org-remove-flyspell-overlays-in end1 end)
5886 (cond
5887 ((and lang (not (string= lang "")) org-src-fontify-natively)
5888 (org-src-font-lock-fontify-block lang block-start block-end)
5889 ;; remove old background overlays
5890 (mapc (lambda (ov)
5891 (if (eq (overlay-get ov 'face) 'org-block-background)
5892 (delete-overlay ov)))
5893 (overlays-at (/ (+ beg1 block-end) 2)))
5894 ;; add a background overlay
5895 (setq ovl (make-overlay beg1 block-end))
5896 (overlay-put ovl 'face 'org-block-background)
5897 (overlay-put ovl 'evaporate t)) ; make it go away when empty
5898 (quoting
5899 (add-text-properties beg1 (min (point-max) (1+ end1))
5900 '(face org-block))) ; end of source block
5901 ((not org-fontify-quote-and-verse-blocks))
5902 ((string= block-type "quote")
5903 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5904 ((string= block-type "verse")
5905 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5906 (add-text-properties beg beg1 '(face org-block-begin-line))
5907 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5908 '(face org-block-end-line))
5910 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5911 (org-remove-flyspell-overlays-in
5912 (match-beginning 0)
5913 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5914 (add-text-properties
5915 beg (match-end 3)
5916 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5917 '(font-lock-fontified t invisible t)
5918 '(font-lock-fontified t face org-document-info-keyword)))
5919 (add-text-properties
5920 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5921 (if (string-equal dc1 "+title:")
5922 '(font-lock-fontified t face org-document-title)
5923 '(font-lock-fontified t face org-document-info))))
5924 ((or (equal dc1 "+results")
5925 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5926 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5927 "+call:" "+header:" "+headers:" "+name:"))
5928 (and (match-end 4) (equal dc3 "+attr")))
5929 (org-remove-flyspell-overlays-in
5930 (match-beginning 0)
5931 (if (equal "+caption:" dc1) (match-end 2) (match-end 0)))
5932 (add-text-properties
5933 beg (match-end 0)
5934 '(font-lock-fontified t face org-meta-line))
5936 ((member dc3 '(" " ""))
5937 (org-remove-flyspell-overlays-in beg (match-end 0))
5938 (add-text-properties
5939 beg (match-end 0)
5940 '(font-lock-fontified t face font-lock-comment-face)))
5941 ((not (member (char-after beg) '(?\ ?\t)))
5942 ;; just any other in-buffer setting, but not indented
5943 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5944 (add-text-properties
5945 beg (match-end 0)
5946 '(font-lock-fontified t face org-meta-line))
5948 (t nil))))))
5950 (defun org-fontify-drawers (limit)
5951 "Fontify drawers."
5952 (when (re-search-forward org-drawer-regexp limit t)
5953 (add-text-properties
5954 (match-beginning 0) (match-end 0)
5955 '(font-lock-fontified t face org-special-keyword))
5956 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5959 (defun org-activate-angle-links (limit)
5960 "Run through the buffer and add overlays to links."
5961 (if (and (re-search-forward org-angle-link-re limit t)
5962 (not (org-in-src-block-p)))
5963 (progn
5964 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5965 (add-text-properties (match-beginning 0) (match-end 0)
5966 (list 'mouse-face 'highlight
5967 'keymap org-mouse-map))
5968 (org-rear-nonsticky-at (match-end 0))
5969 t)))
5971 (defun org-activate-footnote-links (limit)
5972 "Run through the buffer and add overlays to footnotes."
5973 (let ((fn (org-footnote-next-reference-or-definition limit)))
5974 (when fn
5975 (let* ((beg (nth 1 fn))
5976 (end (nth 2 fn))
5977 (label (car fn))
5978 (referencep (/= (line-beginning-position) beg)))
5979 (when (and referencep (nth 3 fn))
5980 (save-excursion
5981 (goto-char beg)
5982 (search-forward (or label "fn:"))
5983 (org-remove-flyspell-overlays-in beg (match-end 0))))
5984 (add-text-properties beg end
5985 (list 'mouse-face 'highlight
5986 'keymap org-mouse-map
5987 'help-echo
5988 (if referencep "Footnote reference"
5989 "Footnote definition")
5990 'font-lock-fontified t
5991 'font-lock-multiline t
5992 'face 'org-footnote))))))
5994 (defun org-activate-bracket-links (limit)
5995 "Run through the buffer and add overlays to bracketed links."
5996 (if (and (re-search-forward org-bracket-link-regexp limit t)
5997 (not (org-in-src-block-p)))
5998 (let* ((hl (org-match-string-no-properties 1))
5999 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6000 (ip (org-maybe-intangible
6001 (list 'invisible 'org-link
6002 'keymap org-mouse-map 'mouse-face 'highlight
6003 'font-lock-multiline t 'help-echo help
6004 'htmlize-link `(:uri ,hl))))
6005 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6006 'font-lock-multiline t 'help-echo help
6007 'htmlize-link `(:uri ,hl))))
6008 ;; We need to remove the invisible property here. Table narrowing
6009 ;; may have made some of this invisible.
6010 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6011 (remove-text-properties (match-beginning 0) (match-end 0)
6012 '(invisible nil))
6013 (if (match-end 3)
6014 (progn
6015 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6016 (org-rear-nonsticky-at (match-beginning 3))
6017 (add-text-properties (match-beginning 3) (match-end 3) vp)
6018 (org-rear-nonsticky-at (match-end 3))
6019 (add-text-properties (match-end 3) (match-end 0) ip)
6020 (org-rear-nonsticky-at (match-end 0)))
6021 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6022 (org-rear-nonsticky-at (match-beginning 1))
6023 (add-text-properties (match-beginning 1) (match-end 1) vp)
6024 (org-rear-nonsticky-at (match-end 1))
6025 (add-text-properties (match-end 1) (match-end 0) ip)
6026 (org-rear-nonsticky-at (match-end 0)))
6027 t)))
6029 (defun org-activate-dates (limit)
6030 "Run through the buffer and add overlays to dates."
6031 (if (and (re-search-forward org-tsr-regexp-both limit t)
6032 (not (equal (char-before (match-beginning 0)) 91)))
6033 (progn
6034 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6035 (add-text-properties (match-beginning 0) (match-end 0)
6036 (list 'mouse-face 'highlight
6037 'keymap org-mouse-map))
6038 (org-rear-nonsticky-at (match-end 0))
6039 (when org-display-custom-times
6040 (if (match-end 3)
6041 (org-display-custom-time (match-beginning 3) (match-end 3)))
6042 (org-display-custom-time (match-beginning 1) (match-end 1)))
6043 t)))
6045 (defvar org-target-link-regexp nil
6046 "Regular expression matching radio targets in plain text.")
6047 (make-variable-buffer-local 'org-target-link-regexp)
6048 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
6049 "Regular expression matching a link target.")
6050 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
6051 "Regular expression matching a radio target.")
6052 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
6053 "Regular expression matching any target.")
6055 (defun org-activate-target-links (limit)
6056 "Run through the buffer and add overlays to target matches."
6057 (when org-target-link-regexp
6058 (let ((case-fold-search t))
6059 (if (re-search-forward org-target-link-regexp limit t)
6060 (progn
6061 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6062 (add-text-properties (match-beginning 0) (match-end 0)
6063 (list 'mouse-face 'highlight
6064 'keymap org-mouse-map
6065 'help-echo "Radio target link"
6066 'org-linked-text t))
6067 (org-rear-nonsticky-at (match-end 0))
6068 t)))))
6070 (defun org-update-radio-target-regexp ()
6071 "Find all radio targets in this file and update the regular expression."
6072 (interactive)
6073 (when (memq 'radio org-activate-links)
6074 (setq org-target-link-regexp
6075 (org-make-target-link-regexp (org-all-targets 'radio)))
6076 (org-restart-font-lock)))
6078 (defun org-hide-wide-columns (limit)
6079 (let (s e)
6080 (setq s (text-property-any (point) (or limit (point-max))
6081 'org-cwidth t))
6082 (when s
6083 (setq e (next-single-property-change s 'org-cwidth))
6084 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6085 (goto-char e)
6086 t)))
6088 (defvar org-latex-and-related-regexp nil
6089 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6091 (defun org-compute-latex-and-related-regexp ()
6092 "Compute regular expression for LaTeX, entities and sub/superscript.
6093 Result depends on variable `org-highlight-latex-and-related'."
6094 (org-set-local
6095 'org-latex-and-related-regexp
6096 (let* ((re-sub
6097 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6098 ((eq org-use-sub-superscripts '{})
6099 (list org-match-substring-with-braces-regexp))
6100 (org-use-sub-superscripts (list org-match-substring-regexp))))
6101 (re-latex
6102 (when (memq 'latex org-highlight-latex-and-related)
6103 (let ((matchers (plist-get org-format-latex-options :matchers)))
6104 (delq nil
6105 (mapcar (lambda (x)
6106 (and (member (car x) matchers) (nth 1 x)))
6107 org-latex-regexps)))))
6108 (re-entities
6109 (when (memq 'entities org-highlight-latex-and-related)
6110 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6111 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6113 (defun org-do-latex-and-related (limit)
6114 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6115 LIMIT bounds the search for syntax to highlight. Stop at first
6116 highlighted object, if any. Return t if some highlighting was
6117 done, nil otherwise."
6118 (when (org-string-nw-p org-latex-and-related-regexp)
6119 (catch 'found
6120 (while (re-search-forward org-latex-and-related-regexp limit t)
6121 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6122 'face))
6123 '(org-code org-verbatim underline))
6124 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6125 '(?_ ?^))
6127 0)))
6128 (font-lock-prepend-text-property
6129 (+ offset (match-beginning 0)) (match-end 0)
6130 'face 'org-latex-and-related)
6131 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6132 '(font-lock-multiline t)))
6133 (throw 'found t)))
6134 nil)))
6136 (defun org-restart-font-lock ()
6137 "Restart `font-lock-mode', to force refontification."
6138 (when (and (boundp 'font-lock-mode) font-lock-mode)
6139 (font-lock-mode -1)
6140 (font-lock-mode 1)))
6142 (defun org-all-targets (&optional radio)
6143 "Return a list of all targets in this file.
6144 When optional argument RADIO is non-nil, only find radio
6145 targets."
6146 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6147 (save-excursion
6148 (goto-char (point-min))
6149 (while (re-search-forward re nil t)
6150 ;; Make sure point is really within the object.
6151 (backward-char)
6152 (let ((obj (org-element-context)))
6153 (when (memq (org-element-type obj) '(radio-target target))
6154 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6155 rtn)))
6157 (defun org-make-target-link-regexp (targets)
6158 "Make regular expression matching all strings in TARGETS.
6159 The regular expression finds the targets also if there is a line break
6160 between words."
6161 (and targets
6162 (concat
6163 "\\<\\("
6164 (mapconcat
6165 (lambda (x)
6166 (setq x (regexp-quote x))
6167 (while (string-match " +" x)
6168 (setq x (replace-match "\\s-+" t t x)))
6170 targets
6171 "\\|")
6172 "\\)\\>")))
6174 (defun org-activate-tags (limit)
6175 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6176 (progn
6177 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6178 (add-text-properties (match-beginning 1) (match-end 1)
6179 (list 'mouse-face 'highlight
6180 'keymap org-mouse-map))
6181 (org-rear-nonsticky-at (match-end 1))
6182 t)))
6184 (defun org-outline-level ()
6185 "Compute the outline level of the heading at point.
6186 If this is called at a normal headline, the level is the number of stars.
6187 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6188 (save-excursion
6189 (if (not (condition-case nil
6190 (org-back-to-heading t)
6191 (error nil)))
6193 (looking-at org-outline-regexp)
6194 (1- (- (match-end 0) (match-beginning 0))))))
6196 (defvar org-font-lock-keywords nil)
6198 (defsubst org-re-property (property &optional literal)
6199 "Return a regexp matching a PROPERTY line.
6200 Match group 3 will be set to the value if it exists."
6201 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6202 (if literal property (regexp-quote property))
6203 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6205 (defconst org-property-re
6206 (org-re-property ".*?" 'literal)
6207 "Regular expression matching a property line.
6208 There are four matching groups:
6209 1: :PROPKEY: including the leading and trailing colon,
6210 2: PROPKEY without the leading and trailing colon,
6211 3: PROPVAL without leading or trailing spaces,
6212 4: the indentation of the current line,
6213 5: trailing whitespace.")
6215 (defvar org-font-lock-hook nil
6216 "Functions to be called for special font lock stuff.")
6218 (defvar org-font-lock-set-keywords-hook nil
6219 "Functions that can manipulate `org-font-lock-extra-keywords'.
6220 This is called after `org-font-lock-extra-keywords' is defined, but before
6221 it is installed to be used by font lock. This can be useful if something
6222 needs to be inserted at a specific position in the font-lock sequence.")
6224 (defun org-font-lock-hook (limit)
6225 "Run `org-font-lock-hook' within LIMIT."
6226 (run-hook-with-args 'org-font-lock-hook limit))
6228 (defun org-set-font-lock-defaults ()
6229 "Set font lock defaults for the current buffer."
6230 (let* ((em org-fontify-emphasized-text)
6231 (lk org-activate-links)
6232 (org-font-lock-extra-keywords
6233 (list
6234 ;; Call the hook
6235 '(org-font-lock-hook)
6236 ;; Headlines
6237 `(,(if org-fontify-whole-heading-line
6238 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6239 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6240 (1 (org-get-level-face 1))
6241 (2 (org-get-level-face 2))
6242 (3 (org-get-level-face 3)))
6243 ;; Table lines
6244 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6245 (1 'org-table t))
6246 ;; Table internals
6247 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6248 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6249 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6250 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6251 ;; Drawers
6252 '(org-fontify-drawers)
6253 ;; Properties
6254 (list org-property-re
6255 '(1 'org-special-keyword t)
6256 '(3 'org-property-value t))
6257 ;; Links
6258 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6259 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6260 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6261 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6262 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6263 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6264 (if (memq 'footnote lk) '(org-activate-footnote-links))
6265 ;; Targets.
6266 (list org-any-target-regexp '(0 'org-target t))
6267 ;; Diary sexps.
6268 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6269 ;; Macro
6270 '("{{{.+?}}}" (0 'org-macro t))
6271 '(org-hide-wide-columns (0 nil append))
6272 ;; TODO keyword
6273 (list (format org-heading-keyword-regexp-format
6274 org-todo-regexp)
6275 '(2 (org-get-todo-face 2) t))
6276 ;; DONE
6277 (if org-fontify-done-headline
6278 (list (format org-heading-keyword-regexp-format
6279 (concat
6280 "\\(?:"
6281 (mapconcat 'regexp-quote org-done-keywords "\\|")
6282 "\\)"))
6283 '(2 'org-headline-done t))
6284 nil)
6285 ;; Priorities
6286 '(org-font-lock-add-priority-faces)
6287 ;; Tags
6288 '(org-font-lock-add-tag-faces)
6289 ;; Tags groups
6290 (if (and org-group-tags org-tag-groups-alist)
6291 (list (concat org-outline-regexp-bol ".+\\(:"
6292 (regexp-opt (mapcar 'car org-tag-groups-alist))
6293 ":\\).*$")
6294 '(1 'org-tag-group prepend)))
6295 ;; Special keywords
6296 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6297 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6298 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6299 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6300 ;; Emphasis
6301 (if em
6302 (if (featurep 'xemacs)
6303 '(org-do-emphasis-faces (0 nil append))
6304 '(org-do-emphasis-faces)))
6305 ;; Checkboxes
6306 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6307 1 'org-checkbox prepend)
6308 (if (cdr (assq 'checkbox org-list-automatic-rules))
6309 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6310 (0 (org-get-checkbox-statistics-face) t)))
6311 ;; Description list items
6312 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6313 1 'org-list-dt prepend)
6314 ;; ARCHIVEd headings
6315 (list (concat
6316 org-outline-regexp-bol
6317 "\\(.*:" org-archive-tag ":.*\\)")
6318 '(1 'org-archived prepend))
6319 ;; Specials
6320 '(org-do-latex-and-related)
6321 '(org-fontify-entities)
6322 '(org-raise-scripts)
6323 ;; Code
6324 '(org-activate-code (1 'org-code t))
6325 ;; COMMENT
6326 (list (format org-heading-keyword-regexp-format
6327 (concat "\\("
6328 org-comment-string "\\|" org-quote-string
6329 "\\)"))
6330 '(2 'org-special-keyword t))
6331 ;; Blocks and meta lines
6332 '(org-fontify-meta-lines-and-blocks))))
6333 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6334 (run-hooks 'org-font-lock-set-keywords-hook)
6335 ;; Now set the full font-lock-keywords
6336 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6337 (org-set-local 'font-lock-defaults
6338 '(org-font-lock-keywords t nil nil backward-paragraph))
6339 (kill-local-variable 'font-lock-keywords) nil))
6341 (defun org-toggle-pretty-entities ()
6342 "Toggle the composition display of entities as UTF8 characters."
6343 (interactive)
6344 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6345 (org-restart-font-lock)
6346 (if org-pretty-entities
6347 (message "Entities are now displayed as UTF8 characters")
6348 (save-restriction
6349 (widen)
6350 (org-decompose-region (point-min) (point-max))
6351 (message "Entities are now displayed as plain text"))))
6353 (defvar org-custom-properties-overlays nil
6354 "List of overlays used for custom properties.")
6355 (make-variable-buffer-local 'org-custom-properties-overlays)
6357 (defun org-toggle-custom-properties-visibility ()
6358 "Display or hide properties in `org-custom-properties'."
6359 (interactive)
6360 (if org-custom-properties-overlays
6361 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6362 (setq org-custom-properties-overlays nil))
6363 (unless (not org-custom-properties)
6364 (save-excursion
6365 (save-restriction
6366 (widen)
6367 (goto-char (point-min))
6368 (while (re-search-forward org-property-re nil t)
6369 (mapc (lambda(p)
6370 (when (equal p (substring (match-string 1) 1 -1))
6371 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6372 (overlay-put o 'invisible t)
6373 (overlay-put o 'org-custom-property t)
6374 (push o org-custom-properties-overlays))))
6375 org-custom-properties)))))))
6377 (defun org-fontify-entities (limit)
6378 "Find an entity to fontify."
6379 (let (ee)
6380 (when org-pretty-entities
6381 (catch 'match
6382 (while (re-search-forward
6383 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6384 limit t)
6385 (if (and (not (org-in-indented-comment-line))
6386 (setq ee (org-entity-get (match-string 1)))
6387 (= (length (nth 6 ee)) 1))
6388 (let*
6389 ((end (if (equal (match-string 2) "{}")
6390 (match-end 2)
6391 (match-end 1))))
6392 (add-text-properties
6393 (match-beginning 0) end
6394 (list 'font-lock-fontified t))
6395 (compose-region (match-beginning 0) end
6396 (nth 6 ee) nil)
6397 (backward-char 1)
6398 (throw 'match t))))
6399 nil))))
6401 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6402 "Fontify string S like in Org-mode."
6403 (with-temp-buffer
6404 (insert s)
6405 (let ((org-odd-levels-only odd-levels))
6406 (org-mode)
6407 (font-lock-fontify-buffer)
6408 (buffer-string))))
6410 (defvar org-m nil)
6411 (defvar org-l nil)
6412 (defvar org-f nil)
6413 (defun org-get-level-face (n)
6414 "Get the right face for match N in font-lock matching of headlines."
6415 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6416 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6417 (if org-cycle-level-faces
6418 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6419 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6420 (cond
6421 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6422 ((eq n 2) org-f)
6423 (t (if org-level-color-stars-only nil org-f))))
6426 (defun org-get-todo-face (kwd)
6427 "Get the right face for a TODO keyword KWD.
6428 If KWD is a number, get the corresponding match group."
6429 (if (numberp kwd) (setq kwd (match-string kwd)))
6430 (or (org-face-from-face-or-color
6431 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6432 (and (member kwd org-done-keywords) 'org-done)
6433 'org-todo))
6435 (defun org-face-from-face-or-color (context inherit face-or-color)
6436 "Create a face list that inherits INHERIT, but sets the foreground color.
6437 When FACE-OR-COLOR is not a string, just return it."
6438 (if (stringp face-or-color)
6439 (list :inherit inherit
6440 (cdr (assoc context org-faces-easy-properties))
6441 face-or-color)
6442 face-or-color))
6444 (defun org-font-lock-add-tag-faces (limit)
6445 "Add the special tag faces."
6446 (when (and org-tag-faces org-tags-special-faces-re)
6447 (while (re-search-forward org-tags-special-faces-re limit t)
6448 (add-text-properties (match-beginning 1) (match-end 1)
6449 (list 'face (org-get-tag-face 1)
6450 'font-lock-fontified t))
6451 (backward-char 1))))
6453 (defun org-font-lock-add-priority-faces (limit)
6454 "Add the special priority faces."
6455 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6456 (when (save-match-data (org-at-heading-p))
6457 (add-text-properties
6458 (match-beginning 0) (match-end 0)
6459 (list 'face (or (org-face-from-face-or-color
6460 'priority 'org-priority
6461 (cdr (assoc (char-after (match-beginning 1))
6462 org-priority-faces)))
6463 'org-priority)
6464 'font-lock-fontified t)))))
6466 (defun org-get-tag-face (kwd)
6467 "Get the right face for a TODO keyword KWD.
6468 If KWD is a number, get the corresponding match group."
6469 (if (numberp kwd) (setq kwd (match-string kwd)))
6470 (or (org-face-from-face-or-color
6471 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6472 'org-tag))
6474 (defun org-unfontify-region (beg end &optional maybe_loudly)
6475 "Remove fontification and activation overlays from links."
6476 (font-lock-default-unfontify-region beg end)
6477 (let* ((buffer-undo-list t)
6478 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6479 (inhibit-modification-hooks t)
6480 deactivate-mark buffer-file-name buffer-file-truename)
6481 (org-decompose-region beg end)
6482 (remove-text-properties beg end
6483 '(mouse-face t keymap t org-linked-text t
6484 invisible t intangible t
6485 org-emphasis t))
6486 (org-remove-font-lock-display-properties beg end)))
6488 (defconst org-script-display '(((raise -0.3) (height 0.7))
6489 ((raise 0.3) (height 0.7))
6490 ((raise -0.5))
6491 ((raise 0.5)))
6492 "Display properties for showing superscripts and subscripts.")
6494 (defun org-remove-font-lock-display-properties (beg end)
6495 "Remove specific display properties that have been added by font lock.
6496 The will remove the raise properties that are used to show superscripts
6497 and subscripts."
6498 (let (next prop)
6499 (while (< beg end)
6500 (setq next (next-single-property-change beg 'display nil end)
6501 prop (get-text-property beg 'display))
6502 (if (member prop org-script-display)
6503 (put-text-property beg next 'display nil))
6504 (setq beg next))))
6506 (defun org-raise-scripts (limit)
6507 "Add raise properties to sub/superscripts."
6508 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6509 (if (re-search-forward
6510 (if (eq org-use-sub-superscripts t)
6511 org-match-substring-regexp
6512 org-match-substring-with-braces-regexp)
6513 limit t)
6514 (let* ((pos (point)) table-p comment-p
6515 (mpos (match-beginning 3))
6516 (emph-p (get-text-property mpos 'org-emphasis))
6517 (link-p (get-text-property mpos 'mouse-face))
6518 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6519 (goto-char (point-at-bol))
6520 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6521 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6522 (goto-char pos)
6523 ;; Handle a_b^c
6524 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6525 (if (or comment-p emph-p link-p keyw-p)
6527 (put-text-property (match-beginning 3) (match-end 0)
6528 'display
6529 (if (equal (char-after (match-beginning 2)) ?^)
6530 (nth (if table-p 3 1) org-script-display)
6531 (nth (if table-p 2 0) org-script-display)))
6532 (add-text-properties (match-beginning 2) (match-end 2)
6533 (list 'invisible t
6534 'org-dwidth t 'org-dwidth-n 1))
6535 (if (and (eq (char-after (match-beginning 3)) ?{)
6536 (eq (char-before (match-end 3)) ?}))
6537 (progn
6538 (add-text-properties
6539 (match-beginning 3) (1+ (match-beginning 3))
6540 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6541 (add-text-properties
6542 (1- (match-end 3)) (match-end 3)
6543 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6544 t)))))
6546 ;;;; Visibility cycling, including org-goto and indirect buffer
6548 ;;; Cycling
6550 (defvar org-cycle-global-status nil)
6551 (make-variable-buffer-local 'org-cycle-global-status)
6552 (put 'org-cycle-global-status 'org-state t)
6553 (defvar org-cycle-subtree-status nil)
6554 (make-variable-buffer-local 'org-cycle-subtree-status)
6555 (put 'org-cycle-subtree-status 'org-state t)
6557 (defvar org-inlinetask-min-level)
6559 (defun org-unlogged-message (&rest args)
6560 "Display a message, but avoid logging it in the *Messages* buffer."
6561 (let ((message-log-max nil))
6562 (apply 'message args)))
6564 ;;;###autoload
6565 (defun org-cycle (&optional arg)
6566 "TAB-action and visibility cycling for Org-mode.
6568 This is the command invoked in Org-mode by the TAB key. Its main purpose
6569 is outline visibility cycling, but it also invokes other actions
6570 in special contexts.
6572 - When this function is called with a prefix argument, rotate the entire
6573 buffer through 3 states (global cycling)
6574 1. OVERVIEW: Show only top-level headlines.
6575 2. CONTENTS: Show all headlines of all levels, but no body text.
6576 3. SHOW ALL: Show everything.
6577 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6578 determined by the variable `org-startup-folded', and by any VISIBILITY
6579 properties in the buffer.
6580 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6581 including any drawers.
6583 - When inside a table, re-align the table and move to the next field.
6585 - When point is at the beginning of a headline, rotate the subtree started
6586 by this line through 3 different states (local cycling)
6587 1. FOLDED: Only the main headline is shown.
6588 2. CHILDREN: The main headline and the direct children are shown.
6589 From this state, you can move to one of the children
6590 and zoom in further.
6591 3. SUBTREE: Show the entire subtree, including body text.
6592 If there is no subtree, switch directly from CHILDREN to FOLDED.
6594 - When point is at the beginning of an empty headline and the variable
6595 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6596 of the headline by demoting and promoting it to likely levels. This
6597 speeds up creation document structure by pressing TAB once or several
6598 times right after creating a new headline.
6600 - When there is a numeric prefix, go up to a heading with level ARG, do
6601 a `show-subtree' and return to the previous cursor position. If ARG
6602 is negative, go up that many levels.
6604 - When point is not at the beginning of a headline, execute the global
6605 binding for TAB, which is re-indenting the line. See the option
6606 `org-cycle-emulate-tab' for details.
6608 - Special case: if point is at the beginning of the buffer and there is
6609 no headline in line 1, this function will act as if called with prefix arg
6610 (C-u TAB, same as S-TAB) also when called without prefix arg.
6611 But only if also the variable `org-cycle-global-at-bob' is t."
6612 (interactive "P")
6613 (org-load-modules-maybe)
6614 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6615 (and org-cycle-level-after-item/entry-creation
6616 (or (org-cycle-level)
6617 (org-cycle-item-indentation))))
6618 (let* ((limit-level
6619 (or org-cycle-max-level
6620 (and (boundp 'org-inlinetask-min-level)
6621 org-inlinetask-min-level
6622 (1- org-inlinetask-min-level))))
6623 (nstars (and limit-level
6624 (if org-odd-levels-only
6625 (and limit-level (1- (* limit-level 2)))
6626 limit-level)))
6627 (org-outline-regexp
6628 (if (not (derived-mode-p 'org-mode))
6629 outline-regexp
6630 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6631 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6632 (not (looking-at org-outline-regexp))))
6633 (org-cycle-hook
6634 (if bob-special
6635 (delq 'org-optimize-window-after-visibility-change
6636 (copy-sequence org-cycle-hook))
6637 org-cycle-hook))
6638 (pos (point)))
6640 (if (or bob-special (equal arg '(4)))
6641 ;; special case: use global cycling
6642 (setq arg t))
6644 (cond
6646 ((equal arg '(16))
6647 (setq last-command 'dummy)
6648 (org-set-startup-visibility)
6649 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6651 ((equal arg '(64))
6652 (show-all)
6653 (org-unlogged-message "Entire buffer visible, including drawers"))
6655 ;; Table: enter it or move to the next field.
6656 ((org-at-table-p 'any)
6657 (if (org-at-table.el-p)
6658 (message "Use C-c ' to edit table.el tables")
6659 (if arg (org-table-edit-field t)
6660 (org-table-justify-field-maybe)
6661 (call-interactively 'org-table-next-field))))
6663 ((run-hook-with-args-until-success
6664 'org-tab-after-check-for-table-hook))
6666 ;; Global cycling: delegate to `org-cycle-internal-global'.
6667 ((eq arg t) (org-cycle-internal-global))
6669 ;; Drawers: delegate to `org-flag-drawer'.
6670 ((save-excursion
6671 (beginning-of-line 1)
6672 (looking-at org-drawer-regexp))
6673 (org-flag-drawer ; toggle block visibility
6674 (not (get-char-property (match-end 0) 'invisible))))
6676 ;; Show-subtree, ARG levels up from here.
6677 ((integerp arg)
6678 (save-excursion
6679 (org-back-to-heading)
6680 (outline-up-heading (if (< arg 0) (- arg)
6681 (- (funcall outline-level) arg)))
6682 (org-show-subtree)))
6684 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6685 ((and (featurep 'org-inlinetask)
6686 (org-inlinetask-at-task-p)
6687 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6688 (org-inlinetask-toggle-visibility))
6690 ((org-try-cdlatex-tab))
6692 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6693 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6694 (save-excursion (beginning-of-line 1)
6695 (looking-at org-outline-regexp)))
6696 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6697 (org-cycle-internal-local))
6699 ;; From there: TAB emulation and template completion.
6700 (buffer-read-only (org-back-to-heading))
6702 ((run-hook-with-args-until-success
6703 'org-tab-after-check-for-cycling-hook))
6705 ((org-try-structure-completion))
6707 ((run-hook-with-args-until-success
6708 'org-tab-before-tab-emulation-hook))
6710 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6711 (or (not (bolp))
6712 (not (looking-at org-outline-regexp))))
6713 (call-interactively (global-key-binding "\t")))
6715 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6716 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6717 (or (and (eq org-cycle-emulate-tab 'white)
6718 (= (match-end 0) (point-at-eol)))
6719 (and (eq org-cycle-emulate-tab 'whitestart)
6720 (>= (match-end 0) pos))))
6722 (eq org-cycle-emulate-tab t))
6723 (call-interactively (global-key-binding "\t")))
6725 (t (save-excursion
6726 (org-back-to-heading)
6727 (org-cycle)))))))
6729 (defun org-cycle-internal-global ()
6730 "Do the global cycling action."
6731 ;; Hack to avoid display of messages for .org attachments in Gnus
6732 (let ((ga (string-match "\\*fontification" (buffer-name))))
6733 (cond
6734 ((and (eq last-command this-command)
6735 (eq org-cycle-global-status 'overview))
6736 ;; We just created the overview - now do table of contents
6737 ;; This can be slow in very large buffers, so indicate action
6738 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6739 (unless ga (org-unlogged-message "CONTENTS..."))
6740 (org-content)
6741 (unless ga (org-unlogged-message "CONTENTS...done"))
6742 (setq org-cycle-global-status 'contents)
6743 (run-hook-with-args 'org-cycle-hook 'contents))
6745 ((and (eq last-command this-command)
6746 (eq org-cycle-global-status 'contents))
6747 ;; We just showed the table of contents - now show everything
6748 (run-hook-with-args 'org-pre-cycle-hook 'all)
6749 (show-all)
6750 (unless ga (org-unlogged-message "SHOW ALL"))
6751 (setq org-cycle-global-status 'all)
6752 (run-hook-with-args 'org-cycle-hook 'all))
6755 ;; Default action: go to overview
6756 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6757 (org-overview)
6758 (unless ga (org-unlogged-message "OVERVIEW"))
6759 (setq org-cycle-global-status 'overview)
6760 (run-hook-with-args 'org-cycle-hook 'overview)))))
6762 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6764 (defun org-cycle-internal-local ()
6765 "Do the local cycling action."
6766 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6767 ;; First, determine end of headline (EOH), end of subtree or item
6768 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6769 (save-excursion
6770 (if (org-at-item-p)
6771 (progn
6772 (beginning-of-line)
6773 (setq struct (org-list-struct))
6774 (setq eoh (point-at-eol))
6775 (setq eos (org-list-get-item-end-before-blank (point) struct))
6776 (setq has-children (org-list-has-child-p (point) struct)))
6777 (org-back-to-heading)
6778 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6779 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6780 (setq has-children
6781 (or (save-excursion
6782 (let ((level (funcall outline-level)))
6783 (outline-next-heading)
6784 (and (org-at-heading-p t)
6785 (> (funcall outline-level) level))))
6786 (save-excursion
6787 (org-list-search-forward (org-item-beginning-re) eos t)))))
6788 ;; Determine end invisible part of buffer (EOL)
6789 (beginning-of-line 2)
6790 ;; XEmacs doesn't have `next-single-char-property-change'
6791 (if (featurep 'xemacs)
6792 (while (and (not (eobp)) ;; this is like `next-line'
6793 (get-char-property (1- (point)) 'invisible))
6794 (beginning-of-line 2))
6795 (while (and (not (eobp)) ;; this is like `next-line'
6796 (get-char-property (1- (point)) 'invisible))
6797 (goto-char (next-single-char-property-change (point) 'invisible))
6798 (and (eolp) (beginning-of-line 2))))
6799 (setq eol (point)))
6800 ;; Find out what to do next and set `this-command'
6801 (cond
6802 ((= eos eoh)
6803 ;; Nothing is hidden behind this heading
6804 (unless (org-before-first-heading-p)
6805 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6806 (org-unlogged-message "EMPTY ENTRY")
6807 (setq org-cycle-subtree-status nil)
6808 (save-excursion
6809 (goto-char eos)
6810 (outline-next-heading)
6811 (if (outline-invisible-p) (org-flag-heading nil))))
6812 ((and (or (>= eol eos)
6813 (not (string-match "\\S-" (buffer-substring eol eos))))
6814 (or has-children
6815 (not (setq children-skipped
6816 org-cycle-skip-children-state-if-no-children))))
6817 ;; Entire subtree is hidden in one line: children view
6818 (unless (org-before-first-heading-p)
6819 (run-hook-with-args 'org-pre-cycle-hook 'children))
6820 (if (org-at-item-p)
6821 (org-list-set-item-visibility (point-at-bol) struct 'children)
6822 (org-show-entry)
6823 (org-with-limited-levels (show-children))
6824 ;; FIXME: This slows down the func way too much.
6825 ;; How keep drawers hidden in subtree anyway?
6826 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6827 ;; (org-cycle-hide-drawers 'subtree))
6829 ;; Fold every list in subtree to top-level items.
6830 (when (eq org-cycle-include-plain-lists 'integrate)
6831 (save-excursion
6832 (org-back-to-heading)
6833 (while (org-list-search-forward (org-item-beginning-re) eos t)
6834 (beginning-of-line 1)
6835 (let* ((struct (org-list-struct))
6836 (prevs (org-list-prevs-alist struct))
6837 (end (org-list-get-bottom-point struct)))
6838 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6839 (org-list-get-all-items (point) struct prevs))
6840 (goto-char (if (< end eos) end eos)))))))
6841 (org-unlogged-message "CHILDREN")
6842 (save-excursion
6843 (goto-char eos)
6844 (outline-next-heading)
6845 (if (outline-invisible-p) (org-flag-heading nil)))
6846 (setq org-cycle-subtree-status 'children)
6847 (unless (org-before-first-heading-p)
6848 (run-hook-with-args 'org-cycle-hook 'children)))
6849 ((or children-skipped
6850 (and (eq last-command this-command)
6851 (eq org-cycle-subtree-status 'children)))
6852 ;; We just showed the children, or no children are there,
6853 ;; now show everything.
6854 (unless (org-before-first-heading-p)
6855 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6856 (outline-flag-region eoh eos nil)
6857 (org-unlogged-message
6858 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6859 (setq org-cycle-subtree-status 'subtree)
6860 (unless (org-before-first-heading-p)
6861 (run-hook-with-args 'org-cycle-hook 'subtree)))
6863 ;; Default action: hide the subtree.
6864 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6865 (outline-flag-region eoh eos t)
6866 (org-unlogged-message "FOLDED")
6867 (setq org-cycle-subtree-status 'folded)
6868 (unless (org-before-first-heading-p)
6869 (run-hook-with-args 'org-cycle-hook 'folded))))))
6871 ;;;###autoload
6872 (defun org-global-cycle (&optional arg)
6873 "Cycle the global visibility. For details see `org-cycle'.
6874 With \\[universal-argument] prefix arg, switch to startup visibility.
6875 With a numeric prefix, show all headlines up to that level."
6876 (interactive "P")
6877 (let ((org-cycle-include-plain-lists
6878 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6879 (cond
6880 ((integerp arg)
6881 (show-all)
6882 (hide-sublevels arg)
6883 (setq org-cycle-global-status 'contents))
6884 ((equal arg '(4))
6885 (org-set-startup-visibility)
6886 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6888 (org-cycle '(4))))))
6890 (defun org-set-startup-visibility ()
6891 "Set the visibility required by startup options and properties."
6892 (cond
6893 ((eq org-startup-folded t)
6894 (org-overview))
6895 ((eq org-startup-folded 'content)
6896 (org-content))
6897 ((or (eq org-startup-folded 'showeverything)
6898 (eq org-startup-folded nil))
6899 (show-all)))
6900 (unless (eq org-startup-folded 'showeverything)
6901 (if org-hide-block-startup (org-hide-block-all))
6902 (org-set-visibility-according-to-property 'no-cleanup)
6903 (org-cycle-hide-archived-subtrees 'all)
6904 (org-cycle-hide-drawers 'all)
6905 (org-cycle-show-empty-lines t)))
6907 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6908 "Switch subtree visibilities according to :VISIBILITY: property."
6909 (interactive)
6910 (let (org-show-entry-below state)
6911 (save-excursion
6912 (goto-char (point-min))
6913 (while (re-search-forward
6914 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6915 nil t)
6916 (setq state (match-string 1))
6917 (save-excursion
6918 (org-back-to-heading t)
6919 (hide-subtree)
6920 (org-reveal)
6921 (cond
6922 ((equal state '("fold" "folded"))
6923 (hide-subtree))
6924 ((equal state "children")
6925 (org-show-hidden-entry)
6926 (show-children))
6927 ((equal state "content")
6928 (save-excursion
6929 (save-restriction
6930 (org-narrow-to-subtree)
6931 (org-content))))
6932 ((member state '("all" "showall"))
6933 (show-subtree)))))
6934 (unless no-cleanup
6935 (org-cycle-hide-archived-subtrees 'all)
6936 (org-cycle-hide-drawers 'all)
6937 (org-cycle-show-empty-lines 'all)))))
6939 ;; This function uses outline-regexp instead of the more fundamental
6940 ;; org-outline-regexp so that org-cycle-global works outside of Org
6941 ;; buffers, where outline-regexp is needed.
6942 (defun org-overview ()
6943 "Switch to overview mode, showing only top-level headlines.
6944 Really, this shows all headlines with level equal or greater than the level
6945 of the first headline in the buffer. This is important, because if the
6946 first headline is not level one, then (hide-sublevels 1) gives confusing
6947 results."
6948 (interactive)
6949 (let ((pos (point))
6950 (level (save-excursion
6951 (goto-char (point-min))
6952 (if (re-search-forward (concat "^" outline-regexp) nil t)
6953 (progn
6954 (goto-char (match-beginning 0))
6955 (funcall outline-level))))))
6956 (and level (hide-sublevels level))
6957 (recenter '(4))
6958 (goto-char pos)))
6960 (defun org-content (&optional arg)
6961 "Show all headlines in the buffer, like a table of contents.
6962 With numerical argument N, show content up to level N."
6963 (interactive "P")
6964 (save-excursion
6965 ;; Visit all headings and show their offspring
6966 (and (integerp arg) (org-overview))
6967 (goto-char (point-max))
6968 (catch 'exit
6969 (while (and (progn (condition-case nil
6970 (outline-previous-visible-heading 1)
6971 (error (goto-char (point-min))))
6973 (looking-at org-outline-regexp))
6974 (if (integerp arg)
6975 (show-children (1- arg))
6976 (show-branches))
6977 (if (bobp) (throw 'exit nil))))))
6979 (defun org-optimize-window-after-visibility-change (state)
6980 "Adjust the window after a change in outline visibility.
6981 This function is the default value of the hook `org-cycle-hook'."
6982 (when (get-buffer-window (current-buffer))
6983 (cond
6984 ((eq state 'content) nil)
6985 ((eq state 'all) nil)
6986 ((eq state 'folded) nil)
6987 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6988 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6990 (defun org-remove-empty-overlays-at (pos)
6991 "Remove outline overlays that do not contain non-white stuff."
6992 (mapc
6993 (lambda (o)
6994 (and (eq 'outline (overlay-get o 'invisible))
6995 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6996 (overlay-end o))))
6997 (delete-overlay o)))
6998 (overlays-at pos)))
7000 (defun org-clean-visibility-after-subtree-move ()
7001 "Fix visibility issues after moving a subtree."
7002 ;; First, find a reasonable region to look at:
7003 ;; Start two siblings above, end three below
7004 (let* ((beg (save-excursion
7005 (and (org-get-last-sibling)
7006 (org-get-last-sibling))
7007 (point)))
7008 (end (save-excursion
7009 (and (org-get-next-sibling)
7010 (org-get-next-sibling)
7011 (org-get-next-sibling))
7012 (if (org-at-heading-p)
7013 (point-at-eol)
7014 (point))))
7015 (level (looking-at "\\*+"))
7016 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7017 (save-excursion
7018 (save-restriction
7019 (narrow-to-region beg end)
7020 (when re
7021 ;; Properly fold already folded siblings
7022 (goto-char (point-min))
7023 (while (re-search-forward re nil t)
7024 (if (and (not (outline-invisible-p))
7025 (save-excursion
7026 (goto-char (point-at-eol)) (outline-invisible-p)))
7027 (hide-entry))))
7028 (org-cycle-show-empty-lines 'overview)
7029 (org-cycle-hide-drawers 'overview)))))
7031 (defun org-cycle-show-empty-lines (state)
7032 "Show empty lines above all visible headlines.
7033 The region to be covered depends on STATE when called through
7034 `org-cycle-hook'. Lisp program can use t for STATE to get the
7035 entire buffer covered. Note that an empty line is only shown if there
7036 are at least `org-cycle-separator-lines' empty lines before the headline."
7037 (when (not (= org-cycle-separator-lines 0))
7038 (save-excursion
7039 (let* ((n (abs org-cycle-separator-lines))
7040 (re (cond
7041 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7042 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7043 (t (let ((ns (number-to-string (- n 2))))
7044 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7045 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7046 beg end b e)
7047 (cond
7048 ((memq state '(overview contents t))
7049 (setq beg (point-min) end (point-max)))
7050 ((memq state '(children folded))
7051 (setq beg (point) end (progn (org-end-of-subtree t t)
7052 (beginning-of-line 2)
7053 (point)))))
7054 (when beg
7055 (goto-char beg)
7056 (while (re-search-forward re end t)
7057 (unless (get-char-property (match-end 1) 'invisible)
7058 (setq e (match-end 1))
7059 (if (< org-cycle-separator-lines 0)
7060 (setq b (save-excursion
7061 (goto-char (match-beginning 0))
7062 (org-back-over-empty-lines)
7063 (if (save-excursion
7064 (goto-char (max (point-min) (1- (point))))
7065 (org-at-heading-p))
7066 (1- (point))
7067 (point))))
7068 (setq b (match-beginning 1)))
7069 (outline-flag-region b e nil)))))))
7070 ;; Never hide empty lines at the end of the file.
7071 (save-excursion
7072 (goto-char (point-max))
7073 (outline-previous-heading)
7074 (outline-end-of-heading)
7075 (if (and (looking-at "[ \t\n]+")
7076 (= (match-end 0) (point-max)))
7077 (outline-flag-region (point) (match-end 0) nil))))
7079 (defun org-show-empty-lines-in-parent ()
7080 "Move to the parent and re-show empty lines before visible headlines."
7081 (save-excursion
7082 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7083 (org-cycle-show-empty-lines context))))
7085 (defun org-files-list ()
7086 "Return `org-agenda-files' list, plus all open org-mode files.
7087 This is useful for operations that need to scan all of a user's
7088 open and agenda-wise Org files."
7089 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7090 (dolist (buf (buffer-list))
7091 (with-current-buffer buf
7092 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7093 (let ((file (expand-file-name (buffer-file-name))))
7094 (unless (member file files)
7095 (push file files))))))
7096 files))
7098 (defsubst org-entry-beginning-position ()
7099 "Return the beginning position of the current entry."
7100 (save-excursion (outline-back-to-heading t) (point)))
7102 (defsubst org-entry-end-position ()
7103 "Return the end position of the current entry."
7104 (save-excursion (outline-next-heading) (point)))
7106 (defun org-cycle-hide-drawers (state &optional exceptions)
7107 "Re-hide all drawers after a visibility state change.
7108 When non-nil, optional argument EXCEPTIONS is a list of strings
7109 specifying which drawers should not be hidden."
7110 (when (and (derived-mode-p 'org-mode)
7111 (not (memq state '(overview folded contents))))
7112 (save-excursion
7113 (let* ((globalp (memq state '(contents all)))
7114 (beg (if globalp (point-min) (point)))
7115 (end (if globalp (point-max)
7116 (if (eq state 'children)
7117 (save-excursion (outline-next-heading) (point))
7118 (org-end-of-subtree t)))))
7119 (goto-char beg)
7120 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7121 (unless (member-ignore-case (match-string 1) exceptions)
7122 (let ((drawer (org-element-at-point)))
7123 (when (memq (org-element-type drawer) '(drawer property-drawer))
7124 (org-flag-drawer t drawer)
7125 ;; Make sure to skip drawer entirely or we might flag
7126 ;; it another time when matching its ending line with
7127 ;; `org-drawer-regexp'.
7128 (goto-char (org-element-property :end drawer))))))))))
7130 (defun org-cycle-hide-inline-tasks (state)
7131 "Re-hide inline tasks when switching to 'contents or 'children
7132 visibility state."
7133 (case state
7134 (contents
7135 (when (org-bound-and-true-p org-inlinetask-min-level)
7136 (hide-sublevels (1- org-inlinetask-min-level))))
7137 (children
7138 (when (featurep 'org-inlinetask)
7139 (save-excursion
7140 (while (and (outline-next-heading)
7141 (org-inlinetask-at-task-p))
7142 (org-inlinetask-toggle-visibility)
7143 (org-inlinetask-goto-end)))))))
7145 (defun org-flag-drawer (flag &optional element)
7146 "When FLAG is non-nil, hide the drawer we are at.
7147 Otherwise make it visible. When optional argument ELEMENT is
7148 a parsed drawer, as returned by `org-element-at-point', hide or
7149 show that drawer instead."
7150 (let ((drawer (or element (org-element-at-point))))
7151 (when (memq (org-element-type drawer) '(drawer property-drawer))
7152 (save-excursion
7153 (goto-char (org-element-property :post-affiliated drawer))
7154 (outline-flag-region
7155 (line-end-position)
7156 (progn (goto-char (org-element-property :end drawer))
7157 (skip-chars-backward " \r\t\n")
7158 (line-end-position))
7159 flag)))))
7161 (defun org-subtree-end-visible-p ()
7162 "Is the end of the current subtree visible?"
7163 (pos-visible-in-window-p
7164 (save-excursion (org-end-of-subtree t) (point))))
7166 (defun org-first-headline-recenter (&optional N)
7167 "Move cursor to the first headline and recenter the headline.
7168 Optional argument N means put the headline into the Nth line of the window."
7169 (goto-char (point-min))
7170 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7171 (beginning-of-line)
7172 (recenter (prefix-numeric-value N))))
7174 ;;; Saving and restoring visibility
7176 (defun org-outline-overlay-data (&optional use-markers)
7177 "Return a list of the locations of all outline overlays.
7178 These are overlays with the `invisible' property value `outline'.
7179 The return value is a list of cons cells, with start and stop
7180 positions for each overlay.
7181 If USE-MARKERS is set, return the positions as markers."
7182 (let (beg end)
7183 (save-excursion
7184 (save-restriction
7185 (widen)
7186 (delq nil
7187 (mapcar (lambda (o)
7188 (when (eq (overlay-get o 'invisible) 'outline)
7189 (setq beg (overlay-start o)
7190 end (overlay-end o))
7191 (and beg end (> end beg)
7192 (if use-markers
7193 (cons (copy-marker beg)
7194 (copy-marker end t))
7195 (cons beg end)))))
7196 (overlays-in (point-min) (point-max))))))))
7198 (defun org-set-outline-overlay-data (data)
7199 "Create visibility overlays for all positions in DATA.
7200 DATA should have been made by `org-outline-overlay-data'."
7201 (let (o)
7202 (save-excursion
7203 (save-restriction
7204 (widen)
7205 (show-all)
7206 (mapc (lambda (c)
7207 (outline-flag-region (car c) (cdr c) t))
7208 data)))))
7210 ;;; Folding of blocks
7212 (defvar org-hide-block-overlays nil
7213 "Overlays hiding blocks.")
7214 (make-variable-buffer-local 'org-hide-block-overlays)
7216 (defun org-block-map (function &optional start end)
7217 "Call FUNCTION at the head of all source blocks in the current buffer.
7218 Optional arguments START and END can be used to limit the range."
7219 (let ((start (or start (point-min)))
7220 (end (or end (point-max))))
7221 (save-excursion
7222 (goto-char start)
7223 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7224 (save-excursion
7225 (save-match-data
7226 (goto-char (match-beginning 0))
7227 (funcall function)))))))
7229 (defun org-hide-block-toggle-all ()
7230 "Toggle the visibility of all blocks in the current buffer."
7231 (org-block-map #'org-hide-block-toggle))
7233 (defun org-hide-block-all ()
7234 "Fold all blocks in the current buffer."
7235 (interactive)
7236 (org-show-block-all)
7237 (org-block-map #'org-hide-block-toggle-maybe))
7239 (defun org-show-block-all ()
7240 "Unfold all blocks in the current buffer."
7241 (interactive)
7242 (mapc 'delete-overlay org-hide-block-overlays)
7243 (setq org-hide-block-overlays nil))
7245 (defun org-hide-block-toggle-maybe ()
7246 "Toggle visibility of block at point."
7247 (interactive)
7248 (let ((case-fold-search t))
7249 (if (save-excursion
7250 (beginning-of-line 1)
7251 (looking-at org-block-regexp))
7252 (progn (org-hide-block-toggle)
7253 t) ;; to signal that we took action
7254 nil))) ;; to signal that we did not
7256 (defun org-hide-block-toggle (&optional force)
7257 "Toggle the visibility of the current block."
7258 (interactive)
7259 (save-excursion
7260 (beginning-of-line)
7261 (if (re-search-forward org-block-regexp nil t)
7262 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7263 (end (match-end 0)) ;; end of entire body
7265 (if (memq t (mapcar (lambda (overlay)
7266 (eq (overlay-get overlay 'invisible)
7267 'org-hide-block))
7268 (overlays-at start)))
7269 (if (or (not force) (eq force 'off))
7270 (mapc (lambda (ov)
7271 (when (member ov org-hide-block-overlays)
7272 (setq org-hide-block-overlays
7273 (delq ov org-hide-block-overlays)))
7274 (when (eq (overlay-get ov 'invisible)
7275 'org-hide-block)
7276 (delete-overlay ov)))
7277 (overlays-at start)))
7278 (setq ov (make-overlay start end))
7279 (overlay-put ov 'invisible 'org-hide-block)
7280 ;; make the block accessible to isearch
7281 (overlay-put
7282 ov 'isearch-open-invisible
7283 (lambda (ov)
7284 (when (member ov org-hide-block-overlays)
7285 (setq org-hide-block-overlays
7286 (delq ov org-hide-block-overlays)))
7287 (when (eq (overlay-get ov 'invisible)
7288 'org-hide-block)
7289 (delete-overlay ov))))
7290 (push ov org-hide-block-overlays)))
7291 (user-error "Not looking at a source block"))))
7293 ;; org-tab-after-check-for-cycling-hook
7294 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7295 ;; Remove overlays when changing major mode
7296 (add-hook 'org-mode-hook
7297 (lambda () (org-add-hook 'change-major-mode-hook
7298 'org-show-block-all 'append 'local)))
7300 ;;; Org-goto
7302 (defvar org-goto-window-configuration nil)
7303 (defvar org-goto-marker nil)
7304 (defvar org-goto-map)
7305 (defun org-goto-map ()
7306 "Set the keymap `org-goto'."
7307 (setq org-goto-map
7308 (let ((map (make-sparse-keymap)))
7309 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7310 mouse-drag-region universal-argument org-occur))
7311 cmd)
7312 (while (setq cmd (pop cmds))
7313 (substitute-key-definition cmd cmd map global-map)))
7314 (suppress-keymap map)
7315 (org-defkey map "\C-m" 'org-goto-ret)
7316 (org-defkey map [(return)] 'org-goto-ret)
7317 (org-defkey map [(left)] 'org-goto-left)
7318 (org-defkey map [(right)] 'org-goto-right)
7319 (org-defkey map [(control ?g)] 'org-goto-quit)
7320 (org-defkey map "\C-i" 'org-cycle)
7321 (org-defkey map [(tab)] 'org-cycle)
7322 (org-defkey map [(down)] 'outline-next-visible-heading)
7323 (org-defkey map [(up)] 'outline-previous-visible-heading)
7324 (if org-goto-auto-isearch
7325 (if (fboundp 'define-key-after)
7326 (define-key-after map [t] 'org-goto-local-auto-isearch)
7327 nil)
7328 (org-defkey map "q" 'org-goto-quit)
7329 (org-defkey map "n" 'outline-next-visible-heading)
7330 (org-defkey map "p" 'outline-previous-visible-heading)
7331 (org-defkey map "f" 'outline-forward-same-level)
7332 (org-defkey map "b" 'outline-backward-same-level)
7333 (org-defkey map "u" 'outline-up-heading))
7334 (org-defkey map "/" 'org-occur)
7335 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7336 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7337 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7338 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7339 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7340 map)))
7342 (defconst org-goto-help
7343 "Browse buffer copy, to find location or copy text.%s
7344 RET=jump to location C-g=quit and return to previous location
7345 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7347 (defvar org-goto-start-pos) ; dynamically scoped parameter
7349 (defun org-goto (&optional alternative-interface)
7350 "Look up a different location in the current file, keeping current visibility.
7352 When you want look-up or go to a different location in a
7353 document, the fastest way is often to fold the entire buffer and
7354 then dive into the tree. This method has the disadvantage, that
7355 the previous location will be folded, which may not be what you
7356 want.
7358 This command works around this by showing a copy of the current
7359 buffer in an indirect buffer, in overview mode. You can dive
7360 into the tree in that copy, use org-occur and incremental search
7361 to find a location. When pressing RET or `Q', the command
7362 returns to the original buffer in which the visibility is still
7363 unchanged. After RET it will also jump to the location selected
7364 in the indirect buffer and expose the headline hierarchy above.
7366 With a prefix argument, use the alternative interface: e.g. if
7367 `org-goto-interface' is 'outline use 'outline-path-completion."
7368 (interactive "P")
7369 (org-goto-map)
7370 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7371 (org-refile-use-outline-path t)
7372 (org-refile-target-verify-function nil)
7373 (interface
7374 (if (not alternative-interface)
7375 org-goto-interface
7376 (if (eq org-goto-interface 'outline)
7377 'outline-path-completion
7378 'outline)))
7379 (org-goto-start-pos (point))
7380 (selected-point
7381 (if (eq interface 'outline)
7382 (car (org-get-location (current-buffer) org-goto-help))
7383 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7384 (org-refile-check-position pa)
7385 (nth 3 pa)))))
7386 (if selected-point
7387 (progn
7388 (org-mark-ring-push org-goto-start-pos)
7389 (goto-char selected-point)
7390 (if (or (outline-invisible-p) (org-invisible-p2))
7391 (org-show-context 'org-goto)))
7392 (message "Quit"))))
7394 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7395 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7396 (defvar org-goto-local-auto-isearch-map) ; defined below
7398 (defun org-get-location (buf help)
7399 "Let the user select a location in the Org-mode buffer BUF.
7400 This function uses a recursive edit. It returns the selected position
7401 or nil."
7402 (org-no-popups
7403 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7404 (isearch-hide-immediately nil)
7405 (isearch-search-fun-function
7406 (lambda () 'org-goto-local-search-headings))
7407 (org-goto-selected-point org-goto-exit-command))
7408 (save-excursion
7409 (save-window-excursion
7410 (delete-other-windows)
7411 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7412 (org-pop-to-buffer-same-window
7413 (condition-case nil
7414 (make-indirect-buffer (current-buffer) "*org-goto*")
7415 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7416 (with-output-to-temp-buffer "*Org Help*"
7417 (princ (format help (if org-goto-auto-isearch
7418 " Just type for auto-isearch."
7419 " n/p/f/b/u to navigate, q to quit."))))
7420 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7421 (setq buffer-read-only nil)
7422 (let ((org-startup-truncated t)
7423 (org-startup-folded nil)
7424 (org-startup-align-all-tables nil))
7425 (org-mode)
7426 (org-overview))
7427 (setq buffer-read-only t)
7428 (if (and (boundp 'org-goto-start-pos)
7429 (integer-or-marker-p org-goto-start-pos))
7430 (let ((org-show-hierarchy-above t)
7431 (org-show-siblings t)
7432 (org-show-following-heading t))
7433 (goto-char org-goto-start-pos)
7434 (and (outline-invisible-p) (org-show-context)))
7435 (goto-char (point-min)))
7436 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7437 (message "Select location and press RET")
7438 (use-local-map org-goto-map)
7439 (recursive-edit)))
7440 (kill-buffer "*org-goto*")
7441 (cons org-goto-selected-point org-goto-exit-command))))
7443 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7444 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7445 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7446 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7448 (defun org-goto-local-search-headings (string bound noerror)
7449 "Search and make sure that any matches are in headlines."
7450 (catch 'return
7451 (while (if isearch-forward
7452 (search-forward string bound noerror)
7453 (search-backward string bound noerror))
7454 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7455 (and (member :headline context)
7456 (not (member :tags context))))
7457 (throw 'return (point))))))
7459 (defun org-goto-local-auto-isearch ()
7460 "Start isearch."
7461 (interactive)
7462 (goto-char (point-min))
7463 (let ((keys (this-command-keys)))
7464 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7465 (isearch-mode t)
7466 (isearch-process-search-char (string-to-char keys)))))
7468 (defun org-goto-ret (&optional arg)
7469 "Finish `org-goto' by going to the new location."
7470 (interactive "P")
7471 (setq org-goto-selected-point (point)
7472 org-goto-exit-command 'return)
7473 (throw 'exit nil))
7475 (defun org-goto-left ()
7476 "Finish `org-goto' by going to the new location."
7477 (interactive)
7478 (if (org-at-heading-p)
7479 (progn
7480 (beginning-of-line 1)
7481 (setq org-goto-selected-point (point)
7482 org-goto-exit-command 'left)
7483 (throw 'exit nil))
7484 (user-error "Not on a heading")))
7486 (defun org-goto-right ()
7487 "Finish `org-goto' by going to the new location."
7488 (interactive)
7489 (if (org-at-heading-p)
7490 (progn
7491 (setq org-goto-selected-point (point)
7492 org-goto-exit-command 'right)
7493 (throw 'exit nil))
7494 (user-error "Not on a heading")))
7496 (defun org-goto-quit ()
7497 "Finish `org-goto' without cursor motion."
7498 (interactive)
7499 (setq org-goto-selected-point nil)
7500 (setq org-goto-exit-command 'quit)
7501 (throw 'exit nil))
7503 ;;; Indirect buffer display of subtrees
7505 (defvar org-indirect-dedicated-frame nil
7506 "This is the frame being used for indirect tree display.")
7507 (defvar org-last-indirect-buffer nil)
7509 (defun org-tree-to-indirect-buffer (&optional arg)
7510 "Create indirect buffer and narrow it to current subtree.
7511 With a numerical prefix ARG, go up to this level and then take that tree.
7512 If ARG is negative, go up that many levels.
7514 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7515 indirect buffer previously made with this command, to avoid proliferation of
7516 indirect buffers. However, when you call the command with a \
7517 \\[universal-argument] prefix, or
7518 when `org-indirect-buffer-display' is `new-frame', the last buffer
7519 is kept so that you can work with several indirect buffers at the same time.
7520 If `org-indirect-buffer-display' is `dedicated-frame', the \
7521 \\[universal-argument] prefix also
7522 requests that a new frame be made for the new buffer, so that the dedicated
7523 frame is not changed."
7524 (interactive "P")
7525 (let ((cbuf (current-buffer))
7526 (cwin (selected-window))
7527 (pos (point))
7528 beg end level heading ibuf)
7529 (save-excursion
7530 (org-back-to-heading t)
7531 (when (numberp arg)
7532 (setq level (org-outline-level))
7533 (if (< arg 0) (setq arg (+ level arg)))
7534 (while (> (setq level (org-outline-level)) arg)
7535 (org-up-heading-safe)))
7536 (setq beg (point)
7537 heading (org-get-heading))
7538 (org-end-of-subtree t t)
7539 (if (org-at-heading-p) (backward-char 1))
7540 (setq end (point)))
7541 (if (and (buffer-live-p org-last-indirect-buffer)
7542 (not (eq org-indirect-buffer-display 'new-frame))
7543 (not arg))
7544 (kill-buffer org-last-indirect-buffer))
7545 (setq ibuf (org-get-indirect-buffer cbuf heading)
7546 org-last-indirect-buffer ibuf)
7547 (cond
7548 ((or (eq org-indirect-buffer-display 'new-frame)
7549 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7550 (select-frame (make-frame))
7551 (delete-other-windows)
7552 (org-pop-to-buffer-same-window ibuf)
7553 (org-set-frame-title heading))
7554 ((eq org-indirect-buffer-display 'dedicated-frame)
7555 (raise-frame
7556 (select-frame (or (and org-indirect-dedicated-frame
7557 (frame-live-p org-indirect-dedicated-frame)
7558 org-indirect-dedicated-frame)
7559 (setq org-indirect-dedicated-frame (make-frame)))))
7560 (delete-other-windows)
7561 (org-pop-to-buffer-same-window ibuf)
7562 (org-set-frame-title (concat "Indirect: " heading)))
7563 ((eq org-indirect-buffer-display 'current-window)
7564 (org-pop-to-buffer-same-window ibuf))
7565 ((eq org-indirect-buffer-display 'other-window)
7566 (pop-to-buffer ibuf))
7567 (t (error "Invalid value")))
7568 (if (featurep 'xemacs)
7569 (save-excursion (org-mode) (turn-on-font-lock)))
7570 (narrow-to-region beg end)
7571 (show-all)
7572 (goto-char pos)
7573 (run-hook-with-args 'org-cycle-hook 'all)
7574 (and (window-live-p cwin) (select-window cwin))))
7576 (defun org-get-indirect-buffer (&optional buffer heading)
7577 (setq buffer (or buffer (current-buffer)))
7578 (let ((n 1) (base (buffer-name buffer)) bname)
7579 (while (buffer-live-p
7580 (get-buffer
7581 (setq bname
7582 (concat base "-"
7583 (if heading (concat heading "-" (number-to-string n))
7584 (number-to-string n))))))
7585 (setq n (1+ n)))
7586 (condition-case nil
7587 (make-indirect-buffer buffer bname 'clone)
7588 (error (make-indirect-buffer buffer bname)))))
7590 (defun org-set-frame-title (title)
7591 "Set the title of the current frame to the string TITLE."
7592 ;; FIXME: how to name a single frame in XEmacs???
7593 (unless (featurep 'xemacs)
7594 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7596 ;;;; Structure editing
7598 ;;; Inserting headlines
7600 (defun org-previous-line-empty-p (&optional next)
7601 "Is the previous line a blank line?
7602 When NEXT is non-nil, check the next line instead."
7603 (save-excursion
7604 (and (not (bobp))
7605 (or (beginning-of-line (if next 2 0)) t)
7606 (save-match-data
7607 (looking-at "[ \t]*$")))))
7609 (defun org-insert-heading (&optional arg invisible-ok)
7610 "Insert a new heading or item with same depth at point.
7611 If point is in a plain list and ARG is nil, create a new list item.
7612 With one universal prefix argument, insert a heading even in lists.
7613 With two universal prefix arguments, insert the heading at the end
7614 of the parent subtree.
7616 If point is at the beginning of a headline, insert a sibling before
7617 the current headline. If point is not at the beginning, split the line
7618 and create a new headline with the text in the current line after point
7619 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7621 If point is at the beginning of a normal line, turn this line into
7622 a heading.
7624 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7625 This is important for non-interactive uses of the command."
7626 (interactive "P")
7627 (if (org-called-interactively-p 'any) (org-reveal))
7628 (let ((itemp (org-in-item-p))
7629 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7630 (respect-content (or org-insert-heading-respect-content
7631 (equal arg '(16))))
7632 (initial-content "")
7633 (adjust-empty-lines t))
7635 (cond
7637 ((or (= (buffer-size) 0)
7638 (and (not (save-excursion
7639 (and (ignore-errors (org-back-to-heading invisible-ok))
7640 (org-at-heading-p))))
7641 (or arg (not itemp))))
7642 ;; At beginning of buffer or so high up that only a heading
7643 ;; makes sense.
7644 (insert
7645 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7646 (if (org-in-src-block-p) ",* " "* "))
7647 (run-hooks 'org-insert-heading-hook))
7649 ((and itemp (not (equal arg '(4))))
7650 ;; Insert an item
7651 (org-insert-item))
7654 ;; Insert a heading
7655 (save-restriction
7656 (widen)
7657 (let* ((level nil)
7658 (on-heading (org-at-heading-p))
7659 (empty-line-p (if on-heading
7660 (org-previous-line-empty-p)
7661 ;; We will decide later
7662 nil))
7663 ;; Get a level string to fall back on
7664 (fix-level
7665 (save-excursion
7666 (org-back-to-heading t)
7667 (if (org-previous-line-empty-p) (setq empty-line-p t))
7668 (looking-at org-outline-regexp)
7669 (make-string (1- (length (match-string 0))) ?*)))
7670 (stars
7671 (save-excursion
7672 (condition-case nil
7673 (progn
7674 (org-back-to-heading invisible-ok)
7675 (when (and (not on-heading)
7676 (featurep 'org-inlinetask)
7677 (integerp org-inlinetask-min-level)
7678 (>= (length (match-string 0))
7679 org-inlinetask-min-level))
7680 ;; Find a heading level before the inline task
7681 (while (and (setq level (org-up-heading-safe))
7682 (>= level org-inlinetask-min-level)))
7683 (if (org-at-heading-p)
7684 (org-back-to-heading invisible-ok)
7685 (error "This should not happen")))
7686 (unless (and (save-excursion
7687 (save-match-data
7688 (org-backward-heading-same-level
7689 1 invisible-ok))
7690 (= (point) (match-beginning 0)))
7691 (not (org-previous-line-empty-p t)))
7692 (setq empty-line-p (or empty-line-p
7693 (org-previous-line-empty-p))))
7694 (match-string 0))
7695 (error (or fix-level "* ")))))
7696 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7697 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7698 pos hide-previous previous-pos)
7700 ;; If we insert after content, move there and clean up whitespace
7701 (when respect-content
7702 (org-end-of-subtree nil t)
7703 (skip-chars-backward " \r\n")
7704 (and (looking-at "[ \t]+") (replace-match ""))
7705 (unless (eobp) (forward-char 1))
7706 (when (looking-at "^\\*")
7707 (unless (bobp) (backward-char 1))
7708 (insert "\n")))
7710 ;; If we are splitting, grab the text that should be moved to the new headline
7711 (when may-split
7712 (if (org-on-heading-p)
7713 ;; This is a heading, we split intelligently (keeping tags)
7714 (let ((pos (point)))
7715 (goto-char (point-at-bol))
7716 (unless (looking-at org-complex-heading-regexp)
7717 (error "This should not happen"))
7718 (when (and (match-beginning 4)
7719 (> pos (match-beginning 4))
7720 (< pos (match-end 4)))
7721 (setq initial-content (buffer-substring pos (match-end 4)))
7722 (goto-char pos)
7723 (delete-region (point) (match-end 4))
7724 (if (looking-at "[ \t]*$")
7725 (replace-match "")
7726 (insert (make-string (length initial-content) ?\ )))
7727 (setq initial-content (org-trim initial-content)))
7728 (goto-char pos))
7729 ;; a normal line
7730 (unless (bolp)
7731 (setq initial-content (buffer-substring (point) (point-at-eol)))
7732 (delete-region (point) (point-at-eol))
7733 (setq initial-content (org-trim initial-content)))))
7735 ;; If we are at the beginning of the line, insert before it. Else after
7736 (cond
7737 ((and (bolp) (looking-at "[ \t]*$")))
7738 ((and (bolp) (not (looking-at "[ \t]*$")))
7739 (open-line 1))
7741 (goto-char (point-at-eol))
7742 (insert "\n")))
7744 ;; Insert the new heading
7745 (insert stars)
7746 (just-one-space)
7747 (insert initial-content)
7748 (when adjust-empty-lines
7749 (if (or (not blank)
7750 (and blank (not (org-previous-line-empty-p))))
7751 (org-N-empty-lines-before-current (if blank 1 0))))
7752 (run-hooks 'org-insert-heading-hook)))))))
7754 (defun org-N-empty-lines-before-current (N)
7755 "Make the number of empty lines before current exactly N.
7756 So this will delete or add empty lines."
7757 (save-excursion
7758 (goto-char (point-at-bol))
7759 (if (looking-back "\\s-+" nil 'greedy)
7760 (replace-match ""))
7761 (or (bobp) (insert "\n"))
7762 (while (> N 0)
7763 (insert "\n")
7764 (setq N (1- N)))))
7766 (defun org-get-heading (&optional no-tags no-todo)
7767 "Return the heading of the current entry, without the stars.
7768 When NO-TAGS is non-nil, don't include tags.
7769 When NO-TODO is non-nil, don't include TODO keywords."
7770 (save-excursion
7771 (org-back-to-heading t)
7772 (cond
7773 ((and no-tags no-todo)
7774 (looking-at org-complex-heading-regexp)
7775 (match-string 4))
7776 (no-tags
7777 (looking-at (concat org-outline-regexp
7778 "\\(.*?\\)"
7779 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7780 (match-string 1))
7781 (no-todo
7782 (looking-at org-todo-line-regexp)
7783 (match-string 3))
7784 (t (looking-at org-heading-regexp)
7785 (match-string 2)))))
7787 (defvar orgstruct-mode) ; defined below
7789 (defun org-heading-components ()
7790 "Return the components of the current heading.
7791 This is a list with the following elements:
7792 - the level as an integer
7793 - the reduced level, different if `org-odd-levels-only' is set.
7794 - the TODO keyword, or nil
7795 - the priority character, like ?A, or nil if no priority is given
7796 - the headline text itself, or the tags string if no headline text
7797 - the tags string, or nil."
7798 (save-excursion
7799 (org-back-to-heading t)
7800 (if (let (case-fold-search)
7801 (looking-at
7802 (if orgstruct-mode
7803 org-heading-regexp
7804 org-complex-heading-regexp)))
7805 (if orgstruct-mode
7806 (list (length (match-string 1))
7807 (org-reduced-level (length (match-string 1)))
7810 (match-string 2)
7811 nil)
7812 (list (length (match-string 1))
7813 (org-reduced-level (length (match-string 1)))
7814 (org-match-string-no-properties 2)
7815 (and (match-end 3) (aref (match-string 3) 2))
7816 (org-match-string-no-properties 4)
7817 (org-match-string-no-properties 5))))))
7819 (defun org-get-entry ()
7820 "Get the entry text, after heading, entire subtree."
7821 (save-excursion
7822 (org-back-to-heading t)
7823 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7825 (defun org-insert-heading-after-current ()
7826 "Insert a new heading with same level as current, after current subtree."
7827 (interactive)
7828 (org-back-to-heading)
7829 (org-insert-heading)
7830 (org-move-subtree-down)
7831 (end-of-line 1))
7833 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7834 "Insert heading with `org-insert-heading-respect-content' set to t."
7835 (interactive "P")
7836 (let ((org-insert-heading-respect-content t))
7837 (org-insert-heading '(4) invisible-ok)))
7839 (defun org-insert-todo-heading-respect-content (&optional force-state)
7840 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7841 (interactive "P")
7842 (let ((org-insert-heading-respect-content t))
7843 (org-insert-todo-heading force-state '(4))))
7845 (defun org-insert-todo-heading (arg &optional force-heading)
7846 "Insert a new heading with the same level and TODO state as current heading.
7847 If the heading has no TODO state, or if the state is DONE, use the first
7848 state (TODO by default). Also one prefix arg, force first state. With two
7849 prefix args, force inserting at the end of the parent subtree."
7850 (interactive "P")
7851 (when (or force-heading (not (org-insert-item 'checkbox)))
7852 (org-insert-heading (or (and (equal arg '(16)) '(16))
7853 force-heading))
7854 (save-excursion
7855 (org-back-to-heading)
7856 (outline-previous-heading)
7857 (looking-at org-todo-line-regexp))
7858 (let*
7859 ((new-mark-x
7860 (if (or arg
7861 (not (match-beginning 2))
7862 (member (match-string 2) org-done-keywords))
7863 (car org-todo-keywords-1)
7864 (match-string 2)))
7865 (new-mark
7867 (run-hook-with-args-until-success
7868 'org-todo-get-default-hook new-mark-x nil)
7869 new-mark-x)))
7870 (beginning-of-line 1)
7871 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7872 (if org-treat-insert-todo-heading-as-state-change
7873 (org-todo new-mark)
7874 (insert new-mark " "))))
7875 (when org-provide-todo-statistics
7876 (org-update-parent-todo-statistics))))
7878 (defun org-insert-subheading (arg)
7879 "Insert a new subheading and demote it.
7880 Works for outline headings and for plain lists alike."
7881 (interactive "P")
7882 (org-insert-heading arg)
7883 (cond
7884 ((org-at-heading-p) (org-do-demote))
7885 ((org-at-item-p) (org-indent-item))))
7887 (defun org-insert-todo-subheading (arg)
7888 "Insert a new subheading with TODO keyword or checkbox and demote it.
7889 Works for outline headings and for plain lists alike."
7890 (interactive "P")
7891 (org-insert-todo-heading arg)
7892 (cond
7893 ((org-at-heading-p) (org-do-demote))
7894 ((org-at-item-p) (org-indent-item))))
7896 ;;; Promotion and Demotion
7898 (defvar org-after-demote-entry-hook nil
7899 "Hook run after an entry has been demoted.
7900 The cursor will be at the beginning of the entry.
7901 When a subtree is being demoted, the hook will be called for each node.")
7903 (defvar org-after-promote-entry-hook nil
7904 "Hook run after an entry has been promoted.
7905 The cursor will be at the beginning of the entry.
7906 When a subtree is being promoted, the hook will be called for each node.")
7908 (defun org-promote-subtree ()
7909 "Promote the entire subtree.
7910 See also `org-promote'."
7911 (interactive)
7912 (save-excursion
7913 (org-with-limited-levels (org-map-tree 'org-promote)))
7914 (org-fix-position-after-promote))
7916 (defun org-demote-subtree ()
7917 "Demote the entire subtree. See `org-demote'.
7918 See also `org-promote'."
7919 (interactive)
7920 (save-excursion
7921 (org-with-limited-levels (org-map-tree 'org-demote)))
7922 (org-fix-position-after-promote))
7925 (defun org-do-promote ()
7926 "Promote the current heading higher up the tree.
7927 If the region is active in `transient-mark-mode', promote all headings
7928 in the region."
7929 (interactive)
7930 (save-excursion
7931 (if (org-region-active-p)
7932 (org-map-region 'org-promote (region-beginning) (region-end))
7933 (org-promote)))
7934 (org-fix-position-after-promote))
7936 (defun org-do-demote ()
7937 "Demote the current heading lower down the tree.
7938 If the region is active in `transient-mark-mode', demote all headings
7939 in the region."
7940 (interactive)
7941 (save-excursion
7942 (if (org-region-active-p)
7943 (org-map-region 'org-demote (region-beginning) (region-end))
7944 (org-demote)))
7945 (org-fix-position-after-promote))
7947 (defun org-fix-position-after-promote ()
7948 "Make sure that after pro/demotion cursor position is right."
7949 (let ((pos (point)))
7950 (when (save-excursion
7951 (beginning-of-line 1)
7952 (looking-at org-todo-line-regexp)
7953 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7954 (cond ((eobp) (insert " "))
7955 ((eolp) (insert " "))
7956 ((equal (char-after) ?\ ) (forward-char 1))))))
7958 (defun org-current-level ()
7959 "Return the level of the current entry, or nil if before the first headline.
7960 The level is the number of stars at the beginning of the headline."
7961 (save-excursion
7962 (org-with-limited-levels
7963 (if (ignore-errors (org-back-to-heading t))
7964 (funcall outline-level)))))
7966 (defun org-get-previous-line-level ()
7967 "Return the outline depth of the last headline before the current line.
7968 Returns 0 for the first headline in the buffer, and nil if before the
7969 first headline."
7970 (and (org-current-level)
7971 (or (and (/= (line-beginning-position) (point-min))
7972 (save-excursion (beginning-of-line 0) (org-current-level)))
7973 0)))
7975 (defun org-reduced-level (l)
7976 "Compute the effective level of a heading.
7977 This takes into account the setting of `org-odd-levels-only'."
7978 (cond
7979 ((zerop l) 0)
7980 (org-odd-levels-only (1+ (floor (/ l 2))))
7981 (t l)))
7983 (defun org-level-increment ()
7984 "Return the number of stars that will be added or removed at a
7985 time to headlines when structure editing, based on the value of
7986 `org-odd-levels-only'."
7987 (if org-odd-levels-only 2 1))
7989 (defun org-get-valid-level (level &optional change)
7990 "Rectify a level change under the influence of `org-odd-levels-only'
7991 LEVEL is a current level, CHANGE is by how much the level should be
7992 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7993 even level numbers will become the next higher odd number."
7994 (if org-odd-levels-only
7995 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7996 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7997 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7998 (max 1 (+ level (or change 0)))))
8000 (if (boundp 'define-obsolete-function-alias)
8001 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8002 (define-obsolete-function-alias 'org-get-legal-level
8003 'org-get-valid-level)
8004 (define-obsolete-function-alias 'org-get-legal-level
8005 'org-get-valid-level "23.1")))
8007 (defun org-promote ()
8008 "Promote the current heading higher up the tree.
8009 If the region is active in `transient-mark-mode', promote all headings
8010 in the region."
8011 (org-back-to-heading t)
8012 (let* ((level (save-match-data (funcall outline-level)))
8013 (after-change-functions (remove 'flyspell-after-change-function
8014 after-change-functions))
8015 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8016 (diff (abs (- level (length up-head) -1))))
8017 (cond ((and (= level 1) org-called-with-limited-levels
8018 org-allow-promoting-top-level-subtree)
8019 (replace-match "# " nil t))
8020 ((= level 1)
8021 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8022 (t (replace-match up-head nil t)))
8023 ;; Fixup tag positioning
8024 (unless (= level 1)
8025 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8026 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8027 (run-hooks 'org-after-promote-entry-hook)))
8029 (defun org-demote ()
8030 "Demote the current heading lower down the tree.
8031 If the region is active in `transient-mark-mode', demote all headings
8032 in the region."
8033 (org-back-to-heading t)
8034 (let* ((level (save-match-data (funcall outline-level)))
8035 (after-change-functions (remove 'flyspell-after-change-function
8036 after-change-functions))
8037 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8038 (diff (abs (- level (length down-head) -1))))
8039 (replace-match down-head nil t)
8040 ;; Fixup tag positioning
8041 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8042 (if org-adapt-indentation (org-fixup-indentation diff))
8043 (run-hooks 'org-after-demote-entry-hook)))
8045 (defun org-cycle-level ()
8046 "Cycle the level of an empty headline through possible states.
8047 This goes first to child, then to parent, level, then up the hierarchy.
8048 After top level, it switches back to sibling level."
8049 (interactive)
8050 (let ((org-adapt-indentation nil))
8051 (when (org-point-at-end-of-empty-headline)
8052 (setq this-command 'org-cycle-level) ; Only needed for caching
8053 (let ((cur-level (org-current-level))
8054 (prev-level (org-get-previous-line-level)))
8055 (cond
8056 ;; If first headline in file, promote to top-level.
8057 ((= prev-level 0)
8058 (loop repeat (/ (- cur-level 1) (org-level-increment))
8059 do (org-do-promote)))
8060 ;; If same level as prev, demote one.
8061 ((= prev-level cur-level)
8062 (org-do-demote))
8063 ;; If parent is top-level, promote to top level if not already.
8064 ((= prev-level 1)
8065 (loop repeat (/ (- cur-level 1) (org-level-increment))
8066 do (org-do-promote)))
8067 ;; If top-level, return to prev-level.
8068 ((= cur-level 1)
8069 (loop repeat (/ (- prev-level 1) (org-level-increment))
8070 do (org-do-demote)))
8071 ;; If less than prev-level, promote one.
8072 ((< cur-level prev-level)
8073 (org-do-promote))
8074 ;; If deeper than prev-level, promote until higher than
8075 ;; prev-level.
8076 ((> cur-level prev-level)
8077 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8078 do (org-do-promote))))
8079 t))))
8081 (defun org-map-tree (fun)
8082 "Call FUN for every heading underneath the current one."
8083 (org-back-to-heading)
8084 (let ((level (funcall outline-level)))
8085 (save-excursion
8086 (funcall fun)
8087 (while (and (progn
8088 (outline-next-heading)
8089 (> (funcall outline-level) level))
8090 (not (eobp)))
8091 (funcall fun)))))
8093 (defun org-map-region (fun beg end)
8094 "Call FUN for every heading between BEG and END."
8095 (let ((org-ignore-region t))
8096 (save-excursion
8097 (setq end (copy-marker end))
8098 (goto-char beg)
8099 (if (and (re-search-forward org-outline-regexp-bol nil t)
8100 (< (point) end))
8101 (funcall fun))
8102 (while (and (progn
8103 (outline-next-heading)
8104 (< (point) end))
8105 (not (eobp)))
8106 (funcall fun)))))
8108 (defvar org-property-end-re) ; silence byte-compiler
8109 (defun org-fixup-indentation (diff)
8110 "Change the indentation in the current entry by DIFF.
8111 However, if any line in the current entry has no indentation, or if it
8112 would end up with no indentation after the change, nothing at all is done."
8113 (save-excursion
8114 (let ((end (save-excursion (outline-next-heading)
8115 (point-marker)))
8116 (prohibit (if (> diff 0)
8117 "^\\S-"
8118 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8119 col)
8120 (unless (save-excursion (end-of-line 1)
8121 (re-search-forward prohibit end t))
8122 (while (and (< (point) end)
8123 (re-search-forward "^[ \t]+" end t))
8124 (goto-char (match-end 0))
8125 (setq col (current-column))
8126 (if (< diff 0) (replace-match ""))
8127 (org-indent-to-column (+ diff col))))
8128 (move-marker end nil))))
8130 (defun org-convert-to-odd-levels ()
8131 "Convert an org-mode file with all levels allowed to one with odd levels.
8132 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8133 level 5 etc."
8134 (interactive)
8135 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8136 (let ((outline-level 'org-outline-level)
8137 (org-odd-levels-only nil) n)
8138 (save-excursion
8139 (goto-char (point-min))
8140 (while (re-search-forward "^\\*\\*+ " nil t)
8141 (setq n (- (length (match-string 0)) 2))
8142 (while (>= (setq n (1- n)) 0)
8143 (org-demote))
8144 (end-of-line 1))))))
8146 (defun org-convert-to-oddeven-levels ()
8147 "Convert an org-mode file with only odd levels to one with odd/even levels.
8148 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8149 file contains a section with an even level, conversion would
8150 destroy the structure of the file. An error is signaled in this
8151 case."
8152 (interactive)
8153 (goto-char (point-min))
8154 ;; First check if there are no even levels
8155 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8156 (org-show-context t)
8157 (error "Not all levels are odd in this file. Conversion not possible"))
8158 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8159 (let ((outline-regexp org-outline-regexp)
8160 (outline-level 'org-outline-level)
8161 (org-odd-levels-only nil) n)
8162 (save-excursion
8163 (goto-char (point-min))
8164 (while (re-search-forward "^\\*\\*+ " nil t)
8165 (setq n (/ (1- (length (match-string 0))) 2))
8166 (while (>= (setq n (1- n)) 0)
8167 (org-promote))
8168 (end-of-line 1))))))
8170 (defun org-tr-level (n)
8171 "Make N odd if required."
8172 (if org-odd-levels-only (1+ (/ n 2)) n))
8174 ;;; Vertical tree motion, cutting and pasting of subtrees
8176 (defun org-move-subtree-up (&optional arg)
8177 "Move the current subtree up past ARG headlines of the same level."
8178 (interactive "p")
8179 (org-move-subtree-down (- (prefix-numeric-value arg))))
8181 (defun org-move-subtree-down (&optional arg)
8182 "Move the current subtree down past ARG headlines of the same level."
8183 (interactive "p")
8184 (setq arg (prefix-numeric-value arg))
8185 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8186 'org-get-last-sibling))
8187 (ins-point (make-marker))
8188 (cnt (abs arg))
8189 (col (current-column))
8190 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8191 ;; Select the tree
8192 (org-back-to-heading)
8193 (setq beg0 (point))
8194 (save-excursion
8195 (setq ne-beg (org-back-over-empty-lines))
8196 (setq beg (point)))
8197 (save-match-data
8198 (save-excursion (outline-end-of-heading)
8199 (setq folded (outline-invisible-p)))
8200 (outline-end-of-subtree))
8201 (outline-next-heading)
8202 (setq ne-end (org-back-over-empty-lines))
8203 (setq end (point))
8204 (goto-char beg0)
8205 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8206 ;; include less whitespace
8207 (save-excursion
8208 (goto-char beg)
8209 (forward-line (- ne-beg ne-end))
8210 (setq beg (point))))
8211 ;; Find insertion point, with error handling
8212 (while (> cnt 0)
8213 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8214 (progn (goto-char beg0)
8215 (user-error "Cannot move past superior level or buffer limit")))
8216 (setq cnt (1- cnt)))
8217 (if (> arg 0)
8218 ;; Moving forward - still need to move over subtree
8219 (progn (org-end-of-subtree t t)
8220 (save-excursion
8221 (org-back-over-empty-lines)
8222 (or (bolp) (newline)))))
8223 (setq ne-ins (org-back-over-empty-lines))
8224 (move-marker ins-point (point))
8225 (setq txt (buffer-substring beg end))
8226 (org-save-markers-in-region beg end)
8227 (delete-region beg end)
8228 (org-remove-empty-overlays-at beg)
8229 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8230 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8231 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8232 (let ((bbb (point)))
8233 (insert-before-markers txt)
8234 (org-reinstall-markers-in-region bbb)
8235 (move-marker ins-point bbb))
8236 (or (bolp) (insert "\n"))
8237 (setq ins-end (point))
8238 (goto-char ins-point)
8239 (org-skip-whitespace)
8240 (when (and (< arg 0)
8241 (org-first-sibling-p)
8242 (> ne-ins ne-beg))
8243 ;; Move whitespace back to beginning
8244 (save-excursion
8245 (goto-char ins-end)
8246 (let ((kill-whole-line t))
8247 (kill-line (- ne-ins ne-beg)) (point)))
8248 (insert (make-string (- ne-ins ne-beg) ?\n)))
8249 (move-marker ins-point nil)
8250 (if folded
8251 (hide-subtree)
8252 (org-show-entry)
8253 (show-children)
8254 (org-cycle-hide-drawers 'children))
8255 (org-clean-visibility-after-subtree-move)
8256 ;; move back to the initial column we were at
8257 (move-to-column col)))
8259 (defvar org-subtree-clip ""
8260 "Clipboard for cut and paste of subtrees.
8261 This is actually only a copy of the kill, because we use the normal kill
8262 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8264 (defvar org-subtree-clip-folded nil
8265 "Was the last copied subtree folded?
8266 This is used to fold the tree back after pasting.")
8268 (defun org-cut-subtree (&optional n)
8269 "Cut the current subtree into the clipboard.
8270 With prefix arg N, cut this many sequential subtrees.
8271 This is a short-hand for marking the subtree and then cutting it."
8272 (interactive "p")
8273 (org-copy-subtree n 'cut))
8275 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8276 "Copy the current subtree it in the clipboard.
8277 With prefix arg N, copy this many sequential subtrees.
8278 This is a short-hand for marking the subtree and then copying it.
8279 If CUT is non-nil, actually cut the subtree.
8280 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8281 of some markers in the region, even if CUT is non-nil. This is
8282 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8283 (interactive "p")
8284 (let (beg end folded (beg0 (point)))
8285 (if (org-called-interactively-p 'any)
8286 (org-back-to-heading nil) ; take what looks like a subtree
8287 (org-back-to-heading t)) ; take what is really there
8288 (setq beg (point))
8289 (skip-chars-forward " \t\r\n")
8290 (save-match-data
8291 (if nosubtrees
8292 (outline-next-heading)
8293 (save-excursion (outline-end-of-heading)
8294 (setq folded (outline-invisible-p)))
8295 (condition-case nil
8296 (org-forward-heading-same-level (1- n) t)
8297 (error nil))
8298 (org-end-of-subtree t t)))
8299 (setq end (point))
8300 (goto-char beg0)
8301 (when (> end beg)
8302 (setq org-subtree-clip-folded folded)
8303 (when (or cut force-store-markers)
8304 (org-save-markers-in-region beg end))
8305 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8306 (setq org-subtree-clip (current-kill 0))
8307 (message "%s: Subtree(s) with %d characters"
8308 (if cut "Cut" "Copied")
8309 (length org-subtree-clip)))))
8311 (defun org-paste-subtree (&optional level tree for-yank)
8312 "Paste the clipboard as a subtree, with modification of headline level.
8313 The entire subtree is promoted or demoted in order to match a new headline
8314 level.
8316 If the cursor is at the beginning of a headline, the same level as
8317 that headline is used to paste the tree.
8319 If not, the new level is derived from the *visible* headings
8320 before and after the insertion point, and taken to be the inferior headline
8321 level of the two. So if the previous visible heading is level 3 and the
8322 next is level 4 (or vice versa), level 4 will be used for insertion.
8323 This makes sure that the subtree remains an independent subtree and does
8324 not swallow low level entries.
8326 You can also force a different level, either by using a numeric prefix
8327 argument, or by inserting the heading marker by hand. For example, if the
8328 cursor is after \"*****\", then the tree will be shifted to level 5.
8330 If optional TREE is given, use this text instead of the kill ring.
8332 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8333 move back over whitespace before inserting, and move point to the end of
8334 the inserted text when done."
8335 (interactive "P")
8336 (setq tree (or tree (and kill-ring (current-kill 0))))
8337 (unless (org-kill-is-subtree-p tree)
8338 (user-error "%s"
8339 (substitute-command-keys
8340 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8341 (org-with-limited-levels
8342 (let* ((visp (not (outline-invisible-p)))
8343 (txt tree)
8344 (^re_ "\\(\\*+\\)[ \t]*")
8345 (old-level (if (string-match org-outline-regexp-bol txt)
8346 (- (match-end 0) (match-beginning 0) 1)
8347 -1))
8348 (force-level (cond (level (prefix-numeric-value level))
8349 ((and (looking-at "[ \t]*$")
8350 (string-match
8351 "^\\*+$" (buffer-substring
8352 (point-at-bol) (point))))
8353 (- (match-end 1) (match-beginning 1)))
8354 ((and (bolp)
8355 (looking-at org-outline-regexp))
8356 (- (match-end 0) (point) 1))))
8357 (previous-level (save-excursion
8358 (condition-case nil
8359 (progn
8360 (outline-previous-visible-heading 1)
8361 (if (looking-at ^re_)
8362 (- (match-end 0) (match-beginning 0) 1)
8364 (error 1))))
8365 (next-level (save-excursion
8366 (condition-case nil
8367 (progn
8368 (or (looking-at org-outline-regexp)
8369 (outline-next-visible-heading 1))
8370 (if (looking-at ^re_)
8371 (- (match-end 0) (match-beginning 0) 1)
8373 (error 1))))
8374 (new-level (or force-level (max previous-level next-level)))
8375 (shift (if (or (= old-level -1)
8376 (= new-level -1)
8377 (= old-level new-level))
8379 (- new-level old-level)))
8380 (delta (if (> shift 0) -1 1))
8381 (func (if (> shift 0) 'org-demote 'org-promote))
8382 (org-odd-levels-only nil)
8383 beg end newend)
8384 ;; Remove the forced level indicator
8385 (if force-level
8386 (delete-region (point-at-bol) (point)))
8387 ;; Paste
8388 (beginning-of-line (if (bolp) 1 2))
8389 (setq beg (point))
8390 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8391 (insert-before-markers txt)
8392 (unless (string-match "\n\\'" txt) (insert "\n"))
8393 (setq newend (point))
8394 (org-reinstall-markers-in-region beg)
8395 (setq end (point))
8396 (goto-char beg)
8397 (skip-chars-forward " \t\n\r")
8398 (setq beg (point))
8399 (if (and (outline-invisible-p) visp)
8400 (save-excursion (outline-show-heading)))
8401 ;; Shift if necessary
8402 (unless (= shift 0)
8403 (save-restriction
8404 (narrow-to-region beg end)
8405 (while (not (= shift 0))
8406 (org-map-region func (point-min) (point-max))
8407 (setq shift (+ delta shift)))
8408 (goto-char (point-min))
8409 (setq newend (point-max))))
8410 (when (or (org-called-interactively-p 'interactive) for-yank)
8411 (message "Clipboard pasted as level %d subtree" new-level))
8412 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8413 kill-ring
8414 (eq org-subtree-clip (current-kill 0))
8415 org-subtree-clip-folded)
8416 ;; The tree was folded before it was killed/copied
8417 (hide-subtree))
8418 (and for-yank (goto-char newend)))))
8420 (defun org-kill-is-subtree-p (&optional txt)
8421 "Check if the current kill is an outline subtree, or a set of trees.
8422 Returns nil if kill does not start with a headline, or if the first
8423 headline level is not the largest headline level in the tree.
8424 So this will actually accept several entries of equal levels as well,
8425 which is OK for `org-paste-subtree'.
8426 If optional TXT is given, check this string instead of the current kill."
8427 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8428 (re (org-get-limited-outline-regexp))
8429 (^re (concat "^" re))
8430 (start-level (and kill
8431 (string-match
8432 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8433 kill)
8434 (- (match-end 2) (match-beginning 2) 1)))
8435 (start (1+ (or (match-beginning 2) -1))))
8436 (if (not start-level)
8437 (progn
8438 nil) ;; does not even start with a heading
8439 (catch 'exit
8440 (while (setq start (string-match ^re kill (1+ start)))
8441 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8442 (throw 'exit nil)))
8443 t))))
8445 (defvar org-markers-to-move nil
8446 "Markers that should be moved with a cut-and-paste operation.
8447 Those markers are stored together with their positions relative to
8448 the start of the region.")
8450 (defun org-save-markers-in-region (beg end)
8451 "Check markers in region.
8452 If these markers are between BEG and END, record their position relative
8453 to BEG, so that after moving the block of text, we can put the markers back
8454 into place.
8455 This function gets called just before an entry or tree gets cut from the
8456 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8457 called immediately, to move the markers with the entries."
8458 (setq org-markers-to-move nil)
8459 (when (featurep 'org-clock)
8460 (org-clock-save-markers-for-cut-and-paste beg end))
8461 (when (featurep 'org-agenda)
8462 (org-agenda-save-markers-for-cut-and-paste beg end)))
8464 (defun org-check-and-save-marker (marker beg end)
8465 "Check if MARKER is between BEG and END.
8466 If yes, remember the marker and the distance to BEG."
8467 (when (and (marker-buffer marker)
8468 (equal (marker-buffer marker) (current-buffer)))
8469 (if (and (>= marker beg) (< marker end))
8470 (push (cons marker (- marker beg)) org-markers-to-move))))
8472 (defun org-reinstall-markers-in-region (beg)
8473 "Move all remembered markers to their position relative to BEG."
8474 (mapc (lambda (x)
8475 (move-marker (car x) (+ beg (cdr x))))
8476 org-markers-to-move)
8477 (setq org-markers-to-move nil))
8479 (defun org-narrow-to-subtree ()
8480 "Narrow buffer to the current subtree."
8481 (interactive)
8482 (save-excursion
8483 (save-match-data
8484 (org-with-limited-levels
8485 (narrow-to-region
8486 (progn (org-back-to-heading t) (point))
8487 (progn (org-end-of-subtree t t)
8488 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8489 (point)))))))
8491 (defun org-narrow-to-block ()
8492 "Narrow buffer to the current block."
8493 (interactive)
8494 (let* ((case-fold-search t)
8495 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8496 "^[ \t]*#\\+end_.*")))
8497 (if blockp
8498 (narrow-to-region (car blockp) (cdr blockp))
8499 (user-error "Not in a block"))))
8501 (eval-when-compile
8502 (defvar org-property-drawer-re))
8504 (defvar org-property-start-re) ;; defined below
8505 (defun org-clone-subtree-with-time-shift (n &optional shift)
8506 "Clone the task (subtree) at point N times.
8507 The clones will be inserted as siblings.
8509 In interactive use, the user will be prompted for the number of
8510 clones to be produced. If the entry has a timestamp, the user
8511 will also be prompted for a time shift, which may be a repeater
8512 as used in time stamps, for example `+3d'. To disable this,
8513 you can call the function with a universal prefix argument.
8515 When a valid repeater is given and the entry contains any time
8516 stamps, the clones will become a sequence in time, with time
8517 stamps in the subtree shifted for each clone produced. If SHIFT
8518 is nil or the empty string, time stamps will be left alone. The
8519 ID property of the original subtree is removed.
8521 If the original subtree did contain time stamps with a repeater,
8522 the following will happen:
8523 - the repeater will be removed in each clone
8524 - an additional clone will be produced, with the current, unshifted
8525 date(s) in the entry.
8526 - the original entry will be placed *after* all the clones, with
8527 repeater intact.
8528 - the start days in the repeater in the original entry will be shifted
8529 to past the last clone.
8530 In this way you can spell out a number of instances of a repeating task,
8531 and still retain the repeater to cover future instances of the task."
8532 (interactive "nNumber of clones to produce: ")
8533 (let ((shift
8534 (or shift
8535 (if (and (not (equal current-prefix-arg '(4)))
8536 (save-excursion
8537 (re-search-forward org-ts-regexp-both
8538 (save-excursion
8539 (org-end-of-subtree t)
8540 (point)) t)))
8541 (read-from-minibuffer
8542 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8543 ""))) ;; No time shift
8544 (n-no-remove -1)
8545 (drawer-re org-drawer-regexp)
8546 beg end template task idprop
8547 shift-n shift-what doshift nmin nmax)
8548 (if (not (and (integerp n) (> n 0)))
8549 (error "Invalid number of replications %s" n))
8550 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8551 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8552 shift)))
8553 (error "Invalid shift specification %s" shift))
8554 (when doshift
8555 (setq shift-n (string-to-number (match-string 1 shift))
8556 shift-what (cdr (assoc (match-string 2 shift)
8557 '(("d" . day) ("w" . week)
8558 ("m" . month) ("y" . year))))))
8559 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8560 (setq nmin 1 nmax n)
8561 (org-back-to-heading t)
8562 (setq beg (point))
8563 (setq idprop (org-entry-get nil "ID"))
8564 (org-end-of-subtree t t)
8565 (or (bolp) (insert "\n"))
8566 (setq end (point))
8567 (setq template (buffer-substring beg end))
8568 (when (and doshift
8569 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8570 (delete-region beg end)
8571 (setq end beg)
8572 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8573 (goto-char end)
8574 (loop for n from nmin to nmax do
8575 ;; prepare clone
8576 (with-temp-buffer
8577 (insert template)
8578 (org-mode)
8579 (goto-char (point-min))
8580 (org-show-subtree)
8581 (and idprop (if org-clone-delete-id
8582 (org-entry-delete nil "ID")
8583 (org-id-get-create t)))
8584 (unless (= n 0)
8585 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8586 (kill-whole-line))
8587 (goto-char (point-min))
8588 (while (re-search-forward drawer-re nil t)
8589 (org-remove-empty-drawer-at (point))))
8590 (goto-char (point-min))
8591 (when doshift
8592 (while (re-search-forward org-ts-regexp-both nil t)
8593 (org-timestamp-change (* n shift-n) shift-what))
8594 (unless (= n n-no-remove)
8595 (goto-char (point-min))
8596 (while (re-search-forward org-ts-regexp nil t)
8597 (save-excursion
8598 (goto-char (match-beginning 0))
8599 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8600 (delete-region (match-beginning 1) (match-end 1)))))))
8601 (setq task (buffer-string)))
8602 (insert task))
8603 (goto-char beg)))
8605 ;;; Outline Sorting
8607 (defun org-sort (with-case)
8608 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8609 Optional argument WITH-CASE means sort case-sensitively."
8610 (interactive "P")
8611 (cond
8612 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8613 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8615 (org-call-with-arg 'org-sort-entries with-case))))
8617 (defun org-sort-remove-invisible (s)
8618 "Remove invisible links from string S."
8619 (remove-text-properties 0 (length s) org-rm-props s)
8620 (while (string-match org-bracket-link-regexp s)
8621 (setq s (replace-match (if (match-end 2)
8622 (match-string 3 s)
8623 (match-string 1 s)) t t s)))
8624 (let ((st (format " %s " s)))
8625 (while (string-match org-emph-re st)
8626 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8627 (setq s (substring st 1 -1)))
8630 (defvar org-priority-regexp) ; defined later in the file
8632 (defvar org-after-sorting-entries-or-items-hook nil
8633 "Hook that is run after a bunch of entries or items have been sorted.
8634 When children are sorted, the cursor is in the parent line when this
8635 hook gets called. When a region or a plain list is sorted, the cursor
8636 will be in the first entry of the sorted region/list.")
8638 (defun org-sort-entries
8639 (&optional with-case sorting-type getkey-func compare-func property)
8640 "Sort entries on a certain level of an outline tree.
8641 If there is an active region, the entries in the region are sorted.
8642 Else, if the cursor is before the first entry, sort the top-level items.
8643 Else, the children of the entry at point are sorted.
8645 Sorting can be alphabetically, numerically, by date/time as given by
8646 a time stamp, by a property, by priority order, or by a custom function.
8648 The command prompts for the sorting type unless it has been given to the
8649 function through the SORTING-TYPE argument, which needs to be a character,
8650 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8651 precise meaning of each character:
8653 n Numerically, by converting the beginning of the entry/item to a number.
8654 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8655 o By order of TODO keywords.
8656 t By date/time, either the first active time stamp in the entry, or, if
8657 none exist, by the first inactive one.
8658 s By the scheduled date/time.
8659 d By deadline date/time.
8660 c By creation time, which is assumed to be the first inactive time stamp
8661 at the beginning of a line.
8662 p By priority according to the cookie.
8663 r By the value of a property.
8665 Capital letters will reverse the sort order.
8667 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8668 called with point at the beginning of the record. It must return either
8669 a string or a number that should serve as the sorting key for that record.
8671 Comparing entries ignores case by default. However, with an optional argument
8672 WITH-CASE, the sorting considers case as well.
8674 Sorting is done against the visible part of the headlines, it ignores hidden
8675 links.
8677 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8678 (interactive "P")
8679 (let ((case-func (if with-case 'identity 'downcase))
8680 (cmstr
8681 ;; The clock marker is lost when using `sort-subr', let's
8682 ;; store the clocking string.
8683 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8684 (save-excursion
8685 (goto-char org-clock-marker)
8686 (looking-back "^.*") (match-string-no-properties 0))))
8687 start beg end stars re re2
8688 txt what tmp)
8689 ;; Find beginning and end of region to sort
8690 (cond
8691 ((org-region-active-p)
8692 ;; we will sort the region
8693 (setq end (region-end)
8694 what "region")
8695 (goto-char (region-beginning))
8696 (if (not (org-at-heading-p)) (outline-next-heading))
8697 (setq start (point)))
8698 ((or (org-at-heading-p)
8699 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8700 ;; we will sort the children of the current headline
8701 (org-back-to-heading)
8702 (setq start (point)
8703 end (progn (org-end-of-subtree t t)
8704 (or (bolp) (insert "\n"))
8705 (org-back-over-empty-lines)
8706 (point))
8707 what "children")
8708 (goto-char start)
8709 (show-subtree)
8710 (outline-next-heading))
8712 ;; we will sort the top-level entries in this file
8713 (goto-char (point-min))
8714 (or (org-at-heading-p) (outline-next-heading))
8715 (setq start (point))
8716 (goto-char (point-max))
8717 (beginning-of-line 1)
8718 (when (looking-at ".*?\\S-")
8719 ;; File ends in a non-white line
8720 (end-of-line 1)
8721 (insert "\n"))
8722 (setq end (point-max))
8723 (setq what "top-level")
8724 (goto-char start)
8725 (show-all)))
8727 (setq beg (point))
8728 (if (>= beg end) (user-error "Nothing to sort"))
8730 (looking-at "\\(\\*+\\)")
8731 (setq stars (match-string 1)
8732 re (concat "^" (regexp-quote stars) " +")
8733 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8734 txt (buffer-substring beg end))
8735 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8736 (if (and (not (equal stars "*")) (string-match re2 txt))
8737 (user-error "Region to sort contains a level above the first entry"))
8739 (unless sorting-type
8740 (message
8741 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8742 [t]ime [s]cheduled [d]eadline [c]reated
8743 A/N/P/R/O/F/T/S/D/C means reversed:"
8744 what)
8745 (setq sorting-type (read-char-exclusive))
8747 (unless getkey-func
8748 (and (= (downcase sorting-type) ?f)
8749 (setq getkey-func
8750 (org-icompleting-read "Sort using function: "
8751 obarray 'fboundp t nil nil))
8752 (setq getkey-func (intern getkey-func))))
8754 (and (= (downcase sorting-type) ?r)
8755 (not property)
8756 (setq property
8757 (org-icompleting-read "Property: "
8758 (mapcar 'list (org-buffer-property-keys t))
8759 nil t))))
8761 (message "Sorting entries...")
8763 (save-restriction
8764 (narrow-to-region start end)
8765 (let ((dcst (downcase sorting-type))
8766 (case-fold-search nil)
8767 (now (current-time)))
8768 (sort-subr
8769 (/= dcst sorting-type)
8770 ;; This function moves to the beginning character of the "record" to
8771 ;; be sorted.
8772 (lambda nil
8773 (if (re-search-forward re nil t)
8774 (goto-char (match-beginning 0))
8775 (goto-char (point-max))))
8776 ;; This function moves to the last character of the "record" being
8777 ;; sorted.
8778 (lambda nil
8779 (save-match-data
8780 (condition-case nil
8781 (outline-forward-same-level 1)
8782 (error
8783 (goto-char (point-max))))))
8784 ;; This function returns the value that gets sorted against.
8785 (lambda nil
8786 (cond
8787 ((= dcst ?n)
8788 (if (looking-at org-complex-heading-regexp)
8789 (string-to-number (org-sort-remove-invisible (match-string 4)))
8790 nil))
8791 ((= dcst ?a)
8792 (if (looking-at org-complex-heading-regexp)
8793 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8794 nil))
8795 ((= dcst ?t)
8796 (let ((end (save-excursion (outline-next-heading) (point))))
8797 (if (or (re-search-forward org-ts-regexp end t)
8798 (re-search-forward org-ts-regexp-both end t))
8799 (org-time-string-to-seconds (match-string 0))
8800 (org-float-time now))))
8801 ((= dcst ?c)
8802 (let ((end (save-excursion (outline-next-heading) (point))))
8803 (if (re-search-forward
8804 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8805 end t)
8806 (org-time-string-to-seconds (match-string 0))
8807 (org-float-time now))))
8808 ((= dcst ?s)
8809 (let ((end (save-excursion (outline-next-heading) (point))))
8810 (if (re-search-forward org-scheduled-time-regexp end t)
8811 (org-time-string-to-seconds (match-string 1))
8812 (org-float-time now))))
8813 ((= dcst ?d)
8814 (let ((end (save-excursion (outline-next-heading) (point))))
8815 (if (re-search-forward org-deadline-time-regexp end t)
8816 (org-time-string-to-seconds (match-string 1))
8817 (org-float-time now))))
8818 ((= dcst ?p)
8819 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8820 (string-to-char (match-string 2))
8821 org-default-priority))
8822 ((= dcst ?r)
8823 (or (org-entry-get nil property) ""))
8824 ((= dcst ?o)
8825 (if (looking-at org-complex-heading-regexp)
8826 (- 9999 (length (member (match-string 2)
8827 org-todo-keywords-1)))))
8828 ((= dcst ?f)
8829 (if getkey-func
8830 (progn
8831 (setq tmp (funcall getkey-func))
8832 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8833 tmp)
8834 (error "Invalid key function `%s'" getkey-func)))
8835 (t (error "Invalid sorting type `%c'" sorting-type))))
8837 (cond
8838 ((= dcst ?a) 'string<)
8839 ((= dcst ?f) compare-func)
8840 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8841 (run-hooks 'org-after-sorting-entries-or-items-hook)
8842 ;; Reset the clock marker if needed
8843 (when cmstr
8844 (save-excursion
8845 (goto-char start)
8846 (search-forward cmstr nil t)
8847 (move-marker org-clock-marker (point))))
8848 (message "Sorting entries...done")))
8850 (defun org-do-sort (table what &optional with-case sorting-type)
8851 "Sort TABLE of WHAT according to SORTING-TYPE.
8852 The user will be prompted for the SORTING-TYPE if the call to this
8853 function does not specify it. WHAT is only for the prompt, to indicate
8854 what is being sorted. The sorting key will be extracted from
8855 the car of the elements of the table.
8856 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8857 (unless sorting-type
8858 (message
8859 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8860 what)
8861 (setq sorting-type (read-char-exclusive)))
8862 (let ((dcst (downcase sorting-type))
8863 extractfun comparefun)
8864 ;; Define the appropriate functions
8865 (cond
8866 ((= dcst ?n)
8867 (setq extractfun 'string-to-number
8868 comparefun (if (= dcst sorting-type) '< '>)))
8869 ((= dcst ?a)
8870 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8871 (lambda(x) (downcase (org-sort-remove-invisible x))))
8872 comparefun (if (= dcst sorting-type)
8873 'string<
8874 (lambda (a b) (and (not (string< a b))
8875 (not (string= a b)))))))
8876 ((= dcst ?t)
8877 (setq extractfun
8878 (lambda (x)
8879 (if (or (string-match org-ts-regexp x)
8880 (string-match org-ts-regexp-both x))
8881 (org-float-time
8882 (org-time-string-to-time (match-string 0 x)))
8884 comparefun (if (= dcst sorting-type) '< '>)))
8885 (t (error "Invalid sorting type `%c'" sorting-type)))
8887 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8888 table)
8889 (lambda (a b) (funcall comparefun (car a) (car b))))))
8892 ;;; The orgstruct minor mode
8894 ;; Define a minor mode which can be used in other modes in order to
8895 ;; integrate the org-mode structure editing commands.
8897 ;; This is really a hack, because the org-mode structure commands use
8898 ;; keys which normally belong to the major mode. Here is how it
8899 ;; works: The minor mode defines all the keys necessary to operate the
8900 ;; structure commands, but wraps the commands into a function which
8901 ;; tests if the cursor is currently at a headline or a plain list
8902 ;; item. If that is the case, the structure command is used,
8903 ;; temporarily setting many Org-mode variables like regular
8904 ;; expressions for filling etc. However, when any of those keys is
8905 ;; used at a different location, function uses `key-binding' to look
8906 ;; up if the key has an associated command in another currently active
8907 ;; keymap (minor modes, major mode, global), and executes that
8908 ;; command. There might be problems if any of the keys is otherwise
8909 ;; used as a prefix key.
8911 (defcustom orgstruct-heading-prefix-regexp ""
8912 "Regexp that matches the custom prefix of Org headlines in
8913 orgstruct(++)-mode."
8914 :group 'org
8915 :version "24.4"
8916 :package-version '(Org . "8.3")
8917 :type 'regexp)
8918 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8920 (defcustom orgstruct-setup-hook nil
8921 "Hook run after orgstruct-mode-map is filled."
8922 :group 'org
8923 :version "24.4"
8924 :package-version '(Org . "8.0")
8925 :type 'hook)
8927 (defvar orgstruct-initialized nil)
8929 (defvar org-local-vars nil
8930 "List of local variables, for use by `orgstruct-mode'.")
8932 ;;;###autoload
8933 (define-minor-mode orgstruct-mode
8934 "Toggle the minor mode `orgstruct-mode'.
8935 This mode is for using Org-mode structure commands in other
8936 modes. The following keys behave as if Org-mode were active, if
8937 the cursor is on a headline, or on a plain list item (both as
8938 defined by Org-mode)."
8939 nil " OrgStruct" (make-sparse-keymap)
8940 (funcall (if orgstruct-mode
8941 'add-to-invisibility-spec
8942 'remove-from-invisibility-spec)
8943 '(outline . t))
8944 (when orgstruct-mode
8945 (org-load-modules-maybe)
8946 (unless orgstruct-initialized
8947 (orgstruct-setup)
8948 (setq orgstruct-initialized t))))
8950 ;;;###autoload
8951 (defun turn-on-orgstruct ()
8952 "Unconditionally turn on `orgstruct-mode'."
8953 (orgstruct-mode 1))
8955 (defvar org-fb-vars nil)
8956 (make-variable-buffer-local 'org-fb-vars)
8957 (defun orgstruct++-mode (&optional arg)
8958 "Toggle `orgstruct-mode', the enhanced version of it.
8959 In addition to setting orgstruct-mode, this also exports all
8960 indentation and autofilling variables from org-mode into the
8961 buffer. It will also recognize item context in multiline items."
8962 (interactive "P")
8963 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8964 (if (< arg 1)
8965 (progn (orgstruct-mode -1)
8966 (mapc (lambda(v)
8967 (org-set-local (car v)
8968 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8969 org-fb-vars))
8970 (orgstruct-mode 1)
8971 (setq org-fb-vars nil)
8972 (unless org-local-vars
8973 (setq org-local-vars (org-get-local-variables)))
8974 (let (var val)
8975 (mapc
8976 (lambda (x)
8977 (when (string-match
8978 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8979 (symbol-name (car x)))
8980 (setq var (car x) val (nth 1 x))
8981 (push (list var `(quote ,(eval var))) org-fb-vars)
8982 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8983 org-local-vars)
8984 (org-set-local 'orgstruct-is-++ t))))
8986 (defvar orgstruct-is-++ nil
8987 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8988 (make-variable-buffer-local 'orgstruct-is-++)
8990 ;;;###autoload
8991 (defun turn-on-orgstruct++ ()
8992 "Unconditionally turn on `orgstruct++-mode'."
8993 (orgstruct++-mode 1))
8995 (defun orgstruct-error ()
8996 "Error when there is no default binding for a structure key."
8997 (interactive)
8998 (funcall (if (fboundp 'user-error)
8999 'user-error
9000 'error)
9001 "This key has no function outside structure elements"))
9003 (defun orgstruct-setup ()
9004 "Setup orgstruct keymap."
9005 (dolist (cell '((org-demote . t)
9006 (org-metaleft . t)
9007 (org-metaright . t)
9008 (org-promote . t)
9009 (org-shiftmetaleft . t)
9010 (org-shiftmetaright . t)
9011 org-backward-element
9012 org-backward-heading-same-level
9013 org-ctrl-c-ret
9014 org-ctrl-c-minus
9015 org-ctrl-c-star
9016 org-cycle
9017 org-forward-heading-same-level
9018 org-insert-heading
9019 org-insert-heading-respect-content
9020 org-kill-note-or-show-branches
9021 org-mark-subtree
9022 org-meta-return
9023 org-metadown
9024 org-metaup
9025 org-narrow-to-subtree
9026 org-promote-subtree
9027 org-reveal
9028 org-shiftdown
9029 org-shiftleft
9030 org-shiftmetadown
9031 org-shiftmetaup
9032 org-shiftright
9033 org-shifttab
9034 org-shifttab
9035 org-shiftup
9036 org-show-subtree
9037 org-sort
9038 org-up-element
9039 outline-demote
9040 outline-next-visible-heading
9041 outline-previous-visible-heading
9042 outline-promote
9043 outline-up-heading
9044 show-children))
9045 (let ((f (or (car-safe cell) cell))
9046 (disable-when-heading-prefix (cdr-safe cell)))
9047 (when (fboundp f)
9048 (let ((new-bindings))
9049 (dolist (binding (nconc (where-is-internal f org-mode-map)
9050 (where-is-internal f outline-mode-map)))
9051 (push binding new-bindings)
9052 ;; TODO use local-function-key-map
9053 (dolist (rep '(("<tab>" . "TAB")
9054 ("<return>" . "RET")
9055 ("<escape>" . "ESC")
9056 ("<delete>" . "DEL")))
9057 (setq binding (read-kbd-macro
9058 (let ((case-fold-search))
9059 (replace-regexp-in-string
9060 (regexp-quote (cdr rep))
9061 (car rep)
9062 (key-description binding)))))
9063 (pushnew binding new-bindings :test 'equal)))
9064 (dolist (binding new-bindings)
9065 (let ((key (lookup-key orgstruct-mode-map binding)))
9066 (when (or (not key) (numberp key))
9067 (condition-case nil
9068 (org-defkey orgstruct-mode-map
9069 binding
9070 (orgstruct-make-binding f binding disable-when-heading-prefix))
9071 (error nil)))))))))
9072 (run-hooks 'orgstruct-setup-hook))
9074 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9075 "Create a function for binding in the structure minor mode.
9076 FUN is the command to call inside a table. KEY is the key that
9077 should be checked in for a command to execute outside of tables.
9078 Non-nil `disable-when-heading-prefix' means to disable the command
9079 if `orgstruct-heading-prefix-regexp' is not empty."
9080 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9081 (let ((nname name)
9082 (i 0))
9083 (while (fboundp (intern nname))
9084 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9085 (setq name (intern nname)))
9086 (eval
9087 (let ((bindings '((org-heading-regexp
9088 (concat "^"
9089 orgstruct-heading-prefix-regexp
9090 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9091 (org-outline-regexp
9092 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9093 (org-outline-regexp-bol
9094 (concat "^" org-outline-regexp))
9095 (outline-regexp org-outline-regexp)
9096 (outline-heading-end-regexp "\n")
9097 (outline-level 'org-outline-level)
9098 (outline-heading-alist))))
9099 `(defun ,name (arg)
9100 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9101 "Outside of structure, run the binding of `"
9102 (key-description key) "'."
9103 (when disable-when-heading-prefix
9104 (concat
9105 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9106 "back to the default binding due to limitations of Org's implementation of\n"
9107 "`" (symbol-name fun) "'.")))
9108 (interactive "p")
9109 (let* ((disable
9110 ,(and disable-when-heading-prefix
9111 '(not (string= orgstruct-heading-prefix-regexp ""))))
9112 (fallback
9113 (or disable
9114 (not
9115 (let* ,bindings
9116 (org-context-p 'headline 'item
9117 ,(when (memq fun
9118 '(org-insert-heading
9119 org-insert-heading-respect-content
9120 org-meta-return))
9121 '(when orgstruct-is-++
9122 'item-body))))))))
9123 (if fallback
9124 (let* ((orgstruct-mode)
9125 (binding
9126 (loop with key = ,key
9127 for rep in
9128 '(nil
9129 ("<\\([^>]*\\)tab>" . "\\1TAB")
9130 ("<\\([^>]*\\)return>" . "\\1RET")
9131 ("<\\([^>]*\\)escape>" . "\\1ESC")
9132 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9134 (when rep
9135 (setq key (read-kbd-macro
9136 (let ((case-fold-search))
9137 (replace-regexp-in-string
9138 (car rep)
9139 (cdr rep)
9140 (key-description key))))))
9141 thereis (key-binding key))))
9142 (if (keymapp binding)
9143 (set-transient-map binding)
9144 (let ((func (or binding
9145 (unless disable
9146 'orgstruct-error))))
9147 (when func
9148 (call-interactively func)))))
9149 (org-run-like-in-org-mode
9150 (lambda ()
9151 (interactive)
9152 (let* ,bindings
9153 (call-interactively ',fun)))))))))
9154 name))
9156 (defun org-contextualize-keys (alist contexts)
9157 "Return valid elements in ALIST depending on CONTEXTS.
9159 `org-agenda-custom-commands' or `org-capture-templates' are the
9160 values used for ALIST, and `org-agenda-custom-commands-contexts'
9161 or `org-capture-templates-contexts' are the associated contexts
9162 definitions."
9163 (let ((contexts
9164 ;; normalize contexts
9165 (mapcar
9166 (lambda(c) (cond ((listp (cadr c))
9167 (list (car c) (car c) (cadr c)))
9168 ((string= "" (cadr c))
9169 (list (car c) (car c) (caddr c)))
9170 (t c))) contexts))
9171 (a alist) c r s)
9172 ;; loop over all commands or templates
9173 (while (setq c (pop a))
9174 (let (vrules repl)
9175 (cond
9176 ((not (assoc (car c) contexts))
9177 (push c r))
9178 ((and (assoc (car c) contexts)
9179 (setq vrules (org-contextualize-validate-key
9180 (car c) contexts)))
9181 (mapc (lambda (vr)
9182 (when (not (equal (car vr) (cadr vr)))
9183 (setq repl vr))) vrules)
9184 (if (not repl) (push c r)
9185 (push (cadr repl) s)
9186 (push
9187 (cons (car c)
9188 (cdr (or (assoc (cadr repl) alist)
9189 (error "Undefined key `%s' as contextual replacement for `%s'"
9190 (cadr repl) (car c)))))
9191 r))))))
9192 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9193 (delq
9195 (delete-dups
9196 (mapcar (lambda (x)
9197 (let ((tpl (car x)))
9198 (when (not (delq
9200 (mapcar (lambda(y)
9201 (equal y tpl)) s))) x)))
9202 (reverse r))))))
9204 (defun org-contextualize-validate-key (key contexts)
9205 "Check CONTEXTS for agenda or capture KEY."
9206 (let (r rr res)
9207 (while (setq r (pop contexts))
9208 (mapc
9209 (lambda (rr)
9210 (when
9211 (and (equal key (car r))
9212 (if (functionp rr) (funcall rr)
9213 (or (and (eq (car rr) 'in-file)
9214 (buffer-file-name)
9215 (string-match (cdr rr) (buffer-file-name)))
9216 (and (eq (car rr) 'in-mode)
9217 (string-match (cdr rr) (symbol-name major-mode)))
9218 (and (eq (car rr) 'in-buffer)
9219 (string-match (cdr rr) (buffer-name)))
9220 (when (and (eq (car rr) 'not-in-file)
9221 (buffer-file-name))
9222 (not (string-match (cdr rr) (buffer-file-name))))
9223 (when (eq (car rr) 'not-in-mode)
9224 (not (string-match (cdr rr) (symbol-name major-mode))))
9225 (when (eq (car rr) 'not-in-buffer)
9226 (not (string-match (cdr rr) (buffer-name)))))))
9227 (push r res)))
9228 (car (last r))))
9229 (delete-dups (delq nil res))))
9231 (defun org-context-p (&rest contexts)
9232 "Check if local context is any of CONTEXTS.
9233 Possible values in the list of contexts are `table', `headline', and `item'."
9234 (let ((pos (point)))
9235 (goto-char (point-at-bol))
9236 (prog1 (or (and (memq 'table contexts)
9237 (looking-at "[ \t]*|"))
9238 (and (memq 'headline contexts)
9239 (looking-at org-outline-regexp))
9240 (and (memq 'item contexts)
9241 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9242 (and (memq 'item-body contexts)
9243 (org-in-item-p)))
9244 (goto-char pos))))
9246 (defun org-get-local-variables ()
9247 "Return a list of all local variables in an Org mode buffer."
9248 (let (varlist)
9249 (with-current-buffer (get-buffer-create "*Org tmp*")
9250 (erase-buffer)
9251 (org-mode)
9252 (setq varlist (buffer-local-variables)))
9253 (kill-buffer "*Org tmp*")
9254 (delq nil
9255 (mapcar
9256 (lambda (x)
9257 (setq x
9258 (if (symbolp x)
9259 (list x)
9260 (list (car x) (cdr x))))
9261 (if (and (not (get (car x) 'org-state))
9262 (string-match
9263 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9264 (symbol-name (car x))))
9265 x nil))
9266 varlist))))
9268 (defun org-clone-local-variables (from-buffer &optional regexp)
9269 "Clone local variables from FROM-BUFFER.
9270 Optional argument REGEXP selects variables to clone."
9271 (mapc
9272 (lambda (pair)
9273 (and (symbolp (car pair))
9274 (or (null regexp)
9275 (string-match regexp (symbol-name (car pair))))
9276 (set (make-local-variable (car pair))
9277 (cdr pair))))
9278 (buffer-local-variables from-buffer)))
9280 ;;;###autoload
9281 (defun org-run-like-in-org-mode (cmd)
9282 "Run a command, pretending that the current buffer is in Org-mode.
9283 This will temporarily bind local variables that are typically bound in
9284 Org-mode to the values they have in Org-mode, and then interactively
9285 call CMD."
9286 (org-load-modules-maybe)
9287 (unless org-local-vars
9288 (setq org-local-vars (org-get-local-variables)))
9289 (let (binds)
9290 (dolist (var org-local-vars)
9291 (when (or (not (boundp (car var)))
9292 (eq (symbol-value (car var))
9293 (default-value (car var))))
9294 (push (list (car var) `(quote ,(cadr var))) binds)))
9295 (eval `(let ,binds
9296 (call-interactively (quote ,cmd))))))
9298 ;;;; Archiving
9300 (defun org-get-category (&optional pos force-refresh)
9301 "Get the category applying to position POS."
9302 (save-match-data
9303 (if force-refresh (org-refresh-category-properties))
9304 (let ((pos (or pos (point))))
9305 (or (get-text-property pos 'org-category)
9306 (progn (org-refresh-category-properties)
9307 (get-text-property pos 'org-category))))))
9309 (defun org-refresh-category-properties ()
9310 "Refresh category text properties in the buffer."
9311 (let ((case-fold-search t)
9312 (inhibit-read-only t)
9313 (def-cat (cond
9314 ((null org-category)
9315 (if buffer-file-name
9316 (file-name-sans-extension
9317 (file-name-nondirectory buffer-file-name))
9318 "???"))
9319 ((symbolp org-category) (symbol-name org-category))
9320 (t org-category)))
9321 beg end cat pos optionp)
9322 (org-with-silent-modifications
9323 (save-excursion
9324 (save-restriction
9325 (widen)
9326 (goto-char (point-min))
9327 (put-text-property (point) (point-max) 'org-category def-cat)
9328 (while (re-search-forward
9329 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9330 (setq pos (match-end 0)
9331 optionp (equal (char-after (match-beginning 0)) ?#)
9332 cat (org-trim (match-string 2)))
9333 (if optionp
9334 (setq beg (point-at-bol) end (point-max))
9335 (org-back-to-heading t)
9336 (setq beg (point) end (org-end-of-subtree t t)))
9337 (put-text-property beg end 'org-category cat)
9338 (put-text-property beg end 'org-category-position beg)
9339 (goto-char pos)))))))
9341 (defun org-refresh-properties (dprop tprop)
9342 "Refresh buffer text properties.
9343 DPROP is the drawer property and TPROP is the corresponding text
9344 property to set."
9345 (let ((case-fold-search t)
9346 (inhibit-read-only t) p)
9347 (org-with-silent-modifications
9348 (save-excursion
9349 (save-restriction
9350 (widen)
9351 (goto-char (point-min))
9352 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9353 (setq p (org-match-string-no-properties 1))
9354 (save-excursion
9355 (org-back-to-heading t)
9356 (put-text-property
9357 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9360 ;;;; Link Stuff
9362 ;;; Link abbreviations
9364 (defun org-link-expand-abbrev (link)
9365 "Apply replacements as defined in `org-link-abbrev-alist'."
9366 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9367 (let* ((key (match-string 1 link))
9368 (as (or (assoc key org-link-abbrev-alist-local)
9369 (assoc key org-link-abbrev-alist)))
9370 (tag (and (match-end 2) (match-string 3 link)))
9371 rpl)
9372 (if (not as)
9373 link
9374 (setq rpl (cdr as))
9375 (cond
9376 ((symbolp rpl) (funcall rpl tag))
9377 ((string-match "%(\\([^)]+\\))" rpl)
9378 (replace-match
9379 (save-match-data
9380 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9381 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9382 ((string-match "%h" rpl)
9383 (replace-match (url-hexify-string (or tag "")) t t rpl))
9384 (t (concat rpl tag)))))
9385 link))
9387 ;;; Storing and inserting links
9389 (defvar org-insert-link-history nil
9390 "Minibuffer history for links inserted with `org-insert-link'.")
9392 (defvar org-stored-links nil
9393 "Contains the links stored with `org-store-link'.")
9395 (defvar org-store-link-plist nil
9396 "Plist with info about the most recently link created with `org-store-link'.")
9398 (defvar org-link-protocols nil
9399 "Link protocols added to Org-mode using `org-add-link-type'.")
9401 (defvar org-store-link-functions nil
9402 "List of functions that are called to create and store a link.
9403 Each function will be called in turn until one returns a non-nil
9404 value. Each function should check if it is responsible for creating
9405 this link (for example by looking at the major mode).
9406 If not, it must exit and return nil.
9407 If yes, it should return a non-nil value after a calling
9408 `org-store-link-props' with a list of properties and values.
9409 Special properties are:
9411 :type The link prefix, like \"http\". This must be given.
9412 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9413 This is obligatory as well.
9414 :description Optional default description for the second pair
9415 of brackets in an Org-mode link. The user can still change
9416 this when inserting this link into an Org-mode buffer.
9418 In addition to these, any additional properties can be specified
9419 and then used in capture templates.")
9421 (defun org-add-link-type (type &optional follow export)
9422 "Add TYPE to the list of `org-link-types'.
9423 Re-compute all regular expressions depending on `org-link-types'
9425 FOLLOW and EXPORT are two functions.
9427 FOLLOW should take the link path as the single argument and do whatever
9428 is necessary to follow the link, for example find a file or display
9429 a mail message.
9431 EXPORT should format the link path for export to one of the export formats.
9432 It should be a function accepting three arguments:
9434 path the path of the link, the text after the prefix (like \"http:\")
9435 desc the description of the link, if any, or a description added by
9436 org-export-normalize-links if there is none
9437 format the export format, a symbol like `html' or `latex' or `ascii'..
9439 The function may use the FORMAT information to return different values
9440 depending on the format. The return value will be put literally into
9441 the exported file. If the return value is nil, this means Org should
9442 do what it normally does with links which do not have EXPORT defined.
9444 Org-mode has a built-in default for exporting links. If you are happy with
9445 this default, there is no need to define an export function for the link
9446 type. For a simple example of an export function, see `org-bbdb.el'."
9447 (add-to-list 'org-link-types type t)
9448 (org-make-link-regexps)
9449 (if (assoc type org-link-protocols)
9450 (setcdr (assoc type org-link-protocols) (list follow export))
9451 (push (list type follow export) org-link-protocols)))
9453 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9454 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9456 ;;;###autoload
9457 (defun org-store-link (arg)
9458 "\\<org-mode-map>Store an org-link to the current location.
9459 This link is added to `org-stored-links' and can later be inserted
9460 into an org-buffer with \\[org-insert-link].
9462 For some link types, a prefix arg is interpreted.
9463 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9464 For file links, arg negates `org-context-in-file-links'.
9466 A double prefix arg force skipping storing functions that are not
9467 part of Org's core.
9469 A triple prefix arg force storing a link for each line in the
9470 active region."
9471 (interactive "P")
9472 (org-load-modules-maybe)
9473 (if (and (equal arg '(64)) (org-region-active-p))
9474 (save-excursion
9475 (let ((end (region-end)))
9476 (goto-char (region-beginning))
9477 (set-mark (point))
9478 (while (< (point-at-eol) end)
9479 (move-end-of-line 1) (activate-mark)
9480 (let (current-prefix-arg)
9481 (call-interactively 'org-store-link))
9482 (move-beginning-of-line 2)
9483 (set-mark (point)))))
9484 (org-with-limited-levels
9485 (setq org-store-link-plist nil)
9486 (let (link cpltxt desc description search
9487 txt custom-id agenda-link sfuns sfunsn)
9488 (cond
9490 ;; Store a link using an external link type
9491 ((and (not (equal arg '(16)))
9492 (setq sfuns
9493 (delq
9494 nil (mapcar (lambda (f)
9495 (let (fs) (if (funcall f) (push f fs))))
9496 org-store-link-functions))
9497 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9498 (or (and (cdr sfuns)
9499 (funcall (intern
9500 (completing-read
9501 "Which function for creating the link? "
9502 sfunsn t (car sfunsn)))))
9503 (funcall (caar sfuns)))
9504 (setq link (plist-get org-store-link-plist :link)
9505 desc (or (plist-get org-store-link-plist
9506 :description) link))))
9508 ;; Store a link from a source code buffer
9509 ((org-src-edit-buffer-p)
9510 (let (label gc)
9511 (while (or (not label)
9512 (save-excursion
9513 (save-restriction
9514 (widen)
9515 (goto-char (point-min))
9516 (re-search-forward
9517 (regexp-quote (format org-coderef-label-format label))
9518 nil t))))
9519 (when label (message "Label exists already") (sit-for 2))
9520 (setq label (read-string "Code line label: " label)))
9521 (end-of-line 1)
9522 (setq link (format org-coderef-label-format label))
9523 (setq gc (- 79 (length link)))
9524 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9525 (insert link)
9526 (setq link (concat "(" label ")") desc nil)))
9528 ;; We are in the agenda, link to referenced location
9529 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9530 (let ((m (or (get-text-property (point) 'org-hd-marker)
9531 (get-text-property (point) 'org-marker))))
9532 (when m
9533 (org-with-point-at m
9534 (setq agenda-link
9535 (if (org-called-interactively-p 'any)
9536 (call-interactively 'org-store-link)
9537 (org-store-link nil)))))))
9539 ((eq major-mode 'calendar-mode)
9540 (let ((cd (calendar-cursor-to-date)))
9541 (setq link
9542 (format-time-string
9543 (car org-time-stamp-formats)
9544 (apply 'encode-time
9545 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9546 nil nil nil))))
9547 (org-store-link-props :type "calendar" :date cd)))
9549 ((eq major-mode 'help-mode)
9550 (setq link (concat "help:" (save-excursion
9551 (goto-char (point-min))
9552 (looking-at "^[^ ]+")
9553 (match-string 0))))
9554 (org-store-link-props :type "help"))
9556 ((eq major-mode 'w3-mode)
9557 (setq cpltxt (if (and (buffer-name)
9558 (not (string-match "Untitled" (buffer-name))))
9559 (buffer-name)
9560 (url-view-url t))
9561 link (url-view-url t))
9562 (org-store-link-props :type "w3" :url (url-view-url t)))
9564 ((eq major-mode 'image-mode)
9565 (setq cpltxt (concat "file:"
9566 (abbreviate-file-name buffer-file-name))
9567 link cpltxt)
9568 (org-store-link-props :type "image" :file buffer-file-name))
9570 ;; In dired, store a link to the file of the current line
9571 ((eq major-mode 'dired-mode)
9572 (let ((file (dired-get-filename nil t)))
9573 (setq file (if file
9574 (abbreviate-file-name
9575 (expand-file-name (dired-get-filename nil t)))
9576 ;; otherwise, no file so use current directory.
9577 default-directory))
9578 (setq cpltxt (concat "file:" file)
9579 link cpltxt)))
9581 ((setq search (run-hook-with-args-until-success
9582 'org-create-file-search-functions))
9583 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9584 "::" search))
9585 (setq cpltxt (or description link)))
9587 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9588 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9589 (cond
9590 ;; Store a link using the target at point
9591 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9592 (setq cpltxt
9593 (concat "file:"
9594 (abbreviate-file-name
9595 (buffer-file-name (buffer-base-buffer)))
9596 "::" (match-string 1))
9597 link cpltxt))
9598 ((and (featurep 'org-id)
9599 (or (eq org-id-link-to-org-use-id t)
9600 (and (org-called-interactively-p 'any)
9601 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9602 (and (eq org-id-link-to-org-use-id
9603 'create-if-interactive-and-no-custom-id)
9604 (not custom-id))))
9605 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9606 ;; Store a link using the ID at point
9607 (setq link (condition-case nil
9608 (prog1 (org-id-store-link)
9609 (setq desc (plist-get org-store-link-plist
9610 :description)))
9611 (error
9612 ;; Probably before first headline, link only to file
9613 (concat "file:"
9614 (abbreviate-file-name
9615 (buffer-file-name (buffer-base-buffer))))))))
9617 ;; Just link to current headline
9618 (setq cpltxt (concat "file:"
9619 (abbreviate-file-name
9620 (buffer-file-name (buffer-base-buffer)))))
9621 ;; Add a context search string
9622 (when (org-xor org-context-in-file-links arg)
9623 (let* ((ee (org-element-at-point))
9624 (et (org-element-type ee))
9625 (ev (plist-get (cadr ee) :value))
9626 (ek (plist-get (cadr ee) :key))
9627 (eok (and (stringp ek) (string-match "name" ek))))
9628 (setq txt (cond
9629 ((org-at-heading-p) nil)
9630 ((and (eq et 'keyword) eok) ev)
9631 ((org-region-active-p)
9632 (buffer-substring (region-beginning) (region-end)))))
9633 (when (or (null txt) (string-match "\\S-" txt))
9634 (setq cpltxt
9635 (concat cpltxt "::"
9636 (condition-case nil
9637 (org-make-org-heading-search-string txt)
9638 (error "")))
9639 desc (or (and (eq et 'keyword) eok ev)
9640 (nth 4 (ignore-errors (org-heading-components)))
9641 "NONE")))))
9642 (if (string-match "::\\'" cpltxt)
9643 (setq cpltxt (substring cpltxt 0 -2)))
9644 (setq link cpltxt))))
9646 ((buffer-file-name (buffer-base-buffer))
9647 ;; Just link to this file here.
9648 (setq cpltxt (concat "file:"
9649 (abbreviate-file-name
9650 (buffer-file-name (buffer-base-buffer)))))
9651 ;; Add a context string.
9652 (when (org-xor org-context-in-file-links arg)
9653 (setq txt (if (org-region-active-p)
9654 (buffer-substring (region-beginning) (region-end))
9655 (buffer-substring (point-at-bol) (point-at-eol))))
9656 ;; Only use search option if there is some text.
9657 (when (string-match "\\S-" txt)
9658 (setq cpltxt
9659 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9660 desc "NONE")))
9661 (setq link cpltxt))
9663 ((org-called-interactively-p 'interactive)
9664 (user-error "No method for storing a link from this buffer"))
9666 (t (setq link nil)))
9668 ;; We're done setting link and desc, clean up
9669 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9670 (setq link (or link cpltxt)
9671 desc (or desc cpltxt))
9672 (cond ((equal desc "NONE") (setq desc nil))
9673 ((string-match org-bracket-link-analytic-regexp desc)
9674 (let ((d0 (match-string 3 desc))
9675 (p0 (match-string 5 desc)))
9676 (setq desc
9677 (replace-regexp-in-string
9678 org-bracket-link-regexp
9679 (concat (or p0 d0)
9680 (if (equal (length (match-string 0 desc))
9681 (length desc)) "*" "")) desc)))))
9683 ;; Return the link
9684 (if (not (and (or (org-called-interactively-p 'any)
9685 executing-kbd-macro) link))
9686 (or agenda-link (and link (org-make-link-string link desc)))
9687 (push (list link desc) org-stored-links)
9688 (message "Stored: %s" (or desc link))
9689 (when custom-id
9690 (setq link (concat "file:" (abbreviate-file-name
9691 (buffer-file-name)) "::#" custom-id))
9692 (push (list link desc) org-stored-links))
9693 (car org-stored-links))))))
9695 (defun org-store-link-props (&rest plist)
9696 "Store link properties, extract names and addresses."
9697 (let (x adr)
9698 (when (setq x (plist-get plist :from))
9699 (setq adr (mail-extract-address-components x))
9700 (setq plist (plist-put plist :fromname (car adr)))
9701 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9702 (when (setq x (plist-get plist :to))
9703 (setq adr (mail-extract-address-components x))
9704 (setq plist (plist-put plist :toname (car adr)))
9705 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9706 (let ((from (plist-get plist :from))
9707 (to (plist-get plist :to)))
9708 (when (and from to org-from-is-user-regexp)
9709 (setq plist
9710 (plist-put plist :fromto
9711 (if (string-match org-from-is-user-regexp from)
9712 (concat "to %t")
9713 (concat "from %f"))))))
9714 (setq org-store-link-plist plist))
9716 (defun org-add-link-props (&rest plist)
9717 "Add these properties to the link property list."
9718 (let (key value)
9719 (while plist
9720 (setq key (pop plist) value (pop plist))
9721 (setq org-store-link-plist
9722 (plist-put org-store-link-plist key value)))))
9724 (defun org-email-link-description (&optional fmt)
9725 "Return the description part of an email link.
9726 This takes information from `org-store-link-plist' and formats it
9727 according to FMT (default from `org-email-link-description-format')."
9728 (setq fmt (or fmt org-email-link-description-format))
9729 (let* ((p org-store-link-plist)
9730 (to (plist-get p :toaddress))
9731 (from (plist-get p :fromaddress))
9732 (table
9733 (list
9734 (cons "%c" (plist-get p :fromto))
9735 (cons "%F" (plist-get p :from))
9736 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9737 (cons "%T" (plist-get p :to))
9738 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9739 (cons "%s" (plist-get p :subject))
9740 (cons "%d" (plist-get p :date))
9741 (cons "%m" (plist-get p :message-id)))))
9742 (when (string-match "%c" fmt)
9743 ;; Check if the user wrote this message
9744 (if (and org-from-is-user-regexp from to
9745 (save-match-data (string-match org-from-is-user-regexp from)))
9746 (setq fmt (replace-match "to %t" t t fmt))
9747 (setq fmt (replace-match "from %f" t t fmt))))
9748 (org-replace-escapes fmt table)))
9750 (defun org-make-org-heading-search-string (&optional string)
9751 "Make search string for the current headline or STRING."
9752 (let ((s (or string
9753 (and (derived-mode-p 'org-mode)
9754 (save-excursion
9755 (org-back-to-heading t)
9756 (org-element-property :raw-value (org-element-at-point))))))
9757 (lines org-context-in-file-links))
9758 (or string (setq s (concat "*" s))) ; Add * for headlines
9759 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9760 (when (and string (integerp lines) (> lines 0))
9761 (let ((slines (org-split-string s "\n")))
9762 (when (< lines (length slines))
9763 (setq s (mapconcat
9764 'identity
9765 (reverse (nthcdr (- (length slines) lines)
9766 (reverse slines))) "\n")))))
9767 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9769 (defun org-make-link-string (link &optional description)
9770 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9771 (unless (string-match "\\S-" link)
9772 (error "Empty link"))
9773 (when (and description
9774 (stringp description)
9775 (not (string-match "\\S-" description)))
9776 (setq description nil))
9777 (when (stringp description)
9778 ;; Remove brackets from the description, they are fatal.
9779 (while (string-match "\\[" description)
9780 (setq description (replace-match "{" t t description)))
9781 (while (string-match "\\]" description)
9782 (setq description (replace-match "}" t t description))))
9783 (when (equal link description)
9784 ;; No description needed, it is identical
9785 (setq description nil))
9786 (when (and (not description)
9787 (not (string-match (org-image-file-name-regexp) link))
9788 (not (equal link (org-link-escape link))))
9789 (setq description (org-extract-attributes link)))
9790 (setq link
9791 (cond ((string-match (org-image-file-name-regexp) link) link)
9792 ((string-match org-link-types-re link)
9793 (concat (match-string 1 link)
9794 (org-link-escape (substring link (match-end 1)))))
9795 (t (org-link-escape link))))
9796 (concat "[[" link "]"
9797 (if description (concat "[" description "]") "")
9798 "]"))
9800 (defconst org-link-escape-chars
9801 ;;%20 %2B %3B %3D %5B %5D
9802 '(?\ ?\+ ?\; ?\= ?\[ ?\])
9803 "List of characters that should be escaped in link.
9804 This is the list that is used for internal purposes.")
9806 (defconst org-link-escape-chars-browser
9807 ;;%20 %22
9808 '(?\ ?\")
9809 "List of escapes for characters that are problematic in links.
9810 This is the list that is used before handing over to the browser.")
9812 (defun org-link-escape (text &optional table merge)
9813 "Return percent escaped representation of TEXT.
9814 TEXT is a string with the text to escape.
9815 Optional argument TABLE is a list with characters that should be
9816 escaped. When nil, `org-link-escape-chars' is used.
9817 If optional argument MERGE is set, merge TABLE into
9818 `org-link-escape-chars'."
9819 (cond
9820 ((and table merge)
9821 (mapc (lambda (defchr)
9822 (unless (member defchr table)
9823 (setq table (cons defchr table)))) org-link-escape-chars))
9824 ((null table)
9825 (setq table org-link-escape-chars)))
9826 (mapconcat
9827 (lambda (char)
9828 (if (or (member char table)
9829 (and (or (< char 32) (= char ?\%) (> char 126))
9830 org-url-hexify-p))
9831 (mapconcat (lambda (sequence-element)
9832 (format "%%%.2X" sequence-element))
9833 (or (encode-coding-char char 'utf-8)
9834 (error "Unable to percent escape character: %s"
9835 (char-to-string char))) "")
9836 (char-to-string char))) text ""))
9838 (defun org-link-escape-browser (text)
9839 (if (org-string-match-p
9840 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
9841 text)
9842 (org-link-escape text org-link-escape-chars-browser)
9843 text))
9845 (defun org-link-unescape (str)
9846 "Unhex hexified Unicode strings as returned from the JavaScript function
9847 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9848 (unless (and (null str) (string= "" str))
9849 (let ((pos 0) (case-fold-search t) unhexed)
9850 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9851 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9852 (setq str (replace-match unhexed t t str))
9853 (setq pos (+ pos (length unhexed))))))
9854 str)
9856 (defun org-link-unescape-compound (hex)
9857 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9858 Note: this function also decodes single byte encodings like
9859 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9860 (save-match-data
9861 (let* ((bytes (cdr (split-string hex "%")))
9862 (ret "")
9863 (eat 0)
9864 (sum 0))
9865 (while bytes
9866 (let* ((val (string-to-number (pop bytes) 16))
9867 (shift-xor
9868 (if (= 0 eat)
9869 (cond
9870 ((>= val 252) (cons 6 252))
9871 ((>= val 248) (cons 5 248))
9872 ((>= val 240) (cons 4 240))
9873 ((>= val 224) (cons 3 224))
9874 ((>= val 192) (cons 2 192))
9875 (t (cons 0 0)))
9876 (cons 6 128))))
9877 (if (>= val 192) (setq eat (car shift-xor)))
9878 (setq val (logxor val (cdr shift-xor)))
9879 (setq sum (+ (lsh sum (car shift-xor)) val))
9880 (if (> eat 0) (setq eat (- eat 1)))
9881 (cond
9882 ((= 0 eat) ;multi byte
9883 (setq ret (concat ret (org-char-to-string sum)))
9884 (setq sum 0))
9885 ((not bytes) ; single byte(s)
9886 (setq ret (org-link-unescape-single-byte-sequence hex))))
9887 )) ;; end (while bytes
9888 ret )))
9890 (defun org-link-unescape-single-byte-sequence (hex)
9891 "Unhexify hex-encoded single byte character sequences."
9892 (mapconcat (lambda (byte)
9893 (char-to-string (string-to-number byte 16)))
9894 (cdr (split-string hex "%")) ""))
9896 (defun org-xor (a b)
9897 "Exclusive or."
9898 (if a (not b) b))
9900 (defun org-fixup-message-id-for-http (s)
9901 "Replace special characters in a message id, so it can be used in an http query."
9902 (when (string-match "%" s)
9903 (setq s (mapconcat (lambda (c)
9904 (if (eq c ?%)
9905 "%25"
9906 (char-to-string c)))
9907 s "")))
9908 (while (string-match "<" s)
9909 (setq s (replace-match "%3C" t t s)))
9910 (while (string-match ">" s)
9911 (setq s (replace-match "%3E" t t s)))
9912 (while (string-match "@" s)
9913 (setq s (replace-match "%40" t t s)))
9916 (defun org-link-prettify (link)
9917 "Return a human-readable representation of LINK.
9918 The car of LINK must be a raw link the cdr of LINK must be either
9919 a link description or nil."
9920 (let ((desc (or (cadr link) "<no description>")))
9921 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9922 "<" (car link) ">")))
9924 ;;;###autoload
9925 (defun org-insert-link-global ()
9926 "Insert a link like Org-mode does.
9927 This command can be called in any mode to insert a link in Org-mode syntax."
9928 (interactive)
9929 (org-load-modules-maybe)
9930 (org-run-like-in-org-mode 'org-insert-link))
9932 (defun org-insert-all-links (arg &optional pre post)
9933 "Insert all links in `org-stored-links'.
9934 When a universal prefix, do not delete the links from `org-stored-links'.
9935 When `ARG' is a number, insert the last N link(s).
9936 `PRE' and `POST' are optional arguments to define a string to
9937 prepend or to append."
9938 (interactive "P")
9939 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9940 (links (copy-seq org-stored-links))
9941 (pr (or pre "- "))
9942 (po (or post "\n"))
9943 (cnt 1) l)
9944 (if (null org-stored-links)
9945 (message "No link to insert")
9946 (while (and (or (listp arg) (>= arg cnt))
9947 (setq l (if (listp arg)
9948 (pop links)
9949 (pop org-stored-links))))
9950 (setq cnt (1+ cnt))
9951 (insert pr)
9952 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9953 (insert po)))))
9955 (defun org-insert-last-stored-link (arg)
9956 "Insert the last link stored in `org-stored-links'."
9957 (interactive "p")
9958 (org-insert-all-links arg "" "\n"))
9960 (defun org-link-fontify-links-to-this-file ()
9961 "Fontify links to the current file in `org-stored-links'."
9962 (let ((f (buffer-file-name)) a b)
9963 (setq a (mapcar (lambda(l)
9964 (let ((ll (car l)))
9965 (when (and (string-match "^file:\\(.+\\)::" ll)
9966 (equal f (expand-file-name (match-string 1 ll))))
9967 ll)))
9968 org-stored-links))
9969 (when (featurep 'org-id)
9970 (setq b (mapcar (lambda(l)
9971 (let ((ll (car l)))
9972 (when (and (string-match "^id:\\(.+\\)$" ll)
9973 (equal f (expand-file-name
9974 (or (org-id-find-id-file
9975 (match-string 1 ll)) ""))))
9976 ll)))
9977 org-stored-links)))
9978 (mapcar (lambda(l)
9979 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9980 (delq nil (append a b)))))
9982 (defvar org-link-links-in-this-file nil)
9983 (defun org-insert-link (&optional complete-file link-location default-description)
9984 "Insert a link. At the prompt, enter the link.
9986 Completion can be used to insert any of the link protocol prefixes like
9987 http or ftp in use.
9989 The history can be used to select a link previously stored with
9990 `org-store-link'. When the empty string is entered (i.e. if you just
9991 press RET at the prompt), the link defaults to the most recently
9992 stored link. As SPC triggers completion in the minibuffer, you need to
9993 use M-SPC or C-q SPC to force the insertion of a space character.
9995 You will also be prompted for a description, and if one is given, it will
9996 be displayed in the buffer instead of the link.
9998 If there is already a link at point, this command will allow you to edit link
9999 and description parts.
10001 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10002 be selected using completion. The path to the file will be relative to the
10003 current directory if the file is in the current directory or a subdirectory.
10004 Otherwise, the link will be the absolute path as completed in the minibuffer
10005 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10006 option `org-link-file-path-type'.
10008 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10009 the current directory or below.
10011 With three \\[universal-argument] prefixes, negate the meaning of
10012 `org-keep-stored-link-after-insertion'.
10014 If `org-make-link-description-function' is non-nil, this function will be
10015 called with the link target, and the result will be the default
10016 link description.
10018 If the LINK-LOCATION parameter is non-nil, this value will be
10019 used as the link location instead of reading one interactively.
10021 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10022 be used as the default description."
10023 (interactive "P")
10024 (let* ((wcf (current-window-configuration))
10025 (origbuf (current-buffer))
10026 (region (if (org-region-active-p)
10027 (buffer-substring (region-beginning) (region-end))))
10028 (remove (and region (list (region-beginning) (region-end))))
10029 (desc region)
10030 tmphist ; byte-compile incorrectly complains about this
10031 (link link-location)
10032 (abbrevs org-link-abbrev-alist-local)
10033 entry file all-prefixes auto-desc)
10034 (cond
10035 (link-location) ; specified by arg, just use it.
10036 ((org-in-regexp org-bracket-link-regexp 1)
10037 ;; We do have a link at point, and we are going to edit it.
10038 (setq remove (list (match-beginning 0) (match-end 0)))
10039 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10040 (setq link (read-string "Link: "
10041 (org-link-unescape
10042 (org-match-string-no-properties 1)))))
10043 ((or (org-in-regexp org-angle-link-re)
10044 (org-in-regexp org-plain-link-re))
10045 ;; Convert to bracket link
10046 (setq remove (list (match-beginning 0) (match-end 0))
10047 link (read-string "Link: "
10048 (org-remove-angle-brackets (match-string 0)))))
10049 ((member complete-file '((4) (16)))
10050 ;; Completing read for file names.
10051 (setq link (org-file-complete-link complete-file)))
10053 ;; Read link, with completion for stored links.
10054 (org-link-fontify-links-to-this-file)
10055 (org-switch-to-buffer-other-window "*Org Links*")
10056 (with-current-buffer "*Org Links*"
10057 (erase-buffer)
10058 (insert "Insert a link.
10059 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10060 (when org-stored-links
10061 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10062 (insert (mapconcat 'org-link-prettify
10063 (reverse org-stored-links) "\n")))
10064 (goto-char (point-min)))
10065 (let ((cw (selected-window)))
10066 (select-window (get-buffer-window "*Org Links*" 'visible))
10067 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10068 (unless (pos-visible-in-window-p (point-max))
10069 (org-fit-window-to-buffer))
10070 (and (window-live-p cw) (select-window cw)))
10071 ;; Fake a link history, containing the stored links.
10072 (setq tmphist (append (mapcar 'car org-stored-links)
10073 org-insert-link-history))
10074 (setq all-prefixes (append (mapcar 'car abbrevs)
10075 (mapcar 'car org-link-abbrev-alist)
10076 org-link-types))
10077 (unwind-protect
10078 (progn
10079 (setq link
10080 (org-completing-read
10081 "Link: "
10082 (append
10083 (mapcar (lambda (x) (concat x ":"))
10084 all-prefixes)
10085 (mapcar 'car org-stored-links))
10086 nil nil nil
10087 'tmphist
10088 (caar org-stored-links)))
10089 (if (not (string-match "\\S-" link))
10090 (user-error "No link selected"))
10091 (mapc (lambda(l)
10092 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10093 org-stored-links)
10094 (if (or (member link all-prefixes)
10095 (and (equal ":" (substring link -1))
10096 (member (substring link 0 -1) all-prefixes)
10097 (setq link (substring link 0 -1))))
10098 (setq link (with-current-buffer origbuf
10099 (org-link-try-special-completion link)))))
10100 (set-window-configuration wcf)
10101 (kill-buffer "*Org Links*"))
10102 (setq entry (assoc link org-stored-links))
10103 (or entry (push link org-insert-link-history))
10104 (setq desc (or desc (nth 1 entry)))))
10106 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10107 (not org-keep-stored-link-after-insertion))
10108 (setq org-stored-links (delq (assoc link org-stored-links)
10109 org-stored-links)))
10111 (if (and (string-match org-plain-link-re link)
10112 (not (string-match org-ts-regexp link)))
10113 ;; URL-like link, normalize the use of angular brackets.
10114 (setq link (org-remove-angle-brackets link)))
10116 ;; Check if we are linking to the current file with a search
10117 ;; option If yes, simplify the link by using only the search
10118 ;; option.
10119 (when (and buffer-file-name
10120 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10121 (let* ((path (match-string 1 link))
10122 (case-fold-search nil)
10123 (search (match-string 2 link)))
10124 (save-match-data
10125 (if (equal (file-truename buffer-file-name) (file-truename path))
10126 ;; We are linking to this same file, with a search option
10127 (setq link search)))))
10129 ;; Check if we can/should use a relative path. If yes, simplify the link
10130 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10131 (let* ((type (match-string 1 link))
10132 (path (match-string 2 link))
10133 (origpath path)
10134 (case-fold-search nil))
10135 (cond
10136 ((or (eq org-link-file-path-type 'absolute)
10137 (equal complete-file '(16)))
10138 (setq path (abbreviate-file-name (expand-file-name path))))
10139 ((eq org-link-file-path-type 'noabbrev)
10140 (setq path (expand-file-name path)))
10141 ((eq org-link-file-path-type 'relative)
10142 (setq path (file-relative-name path)))
10144 (save-match-data
10145 (if (string-match (concat "^" (regexp-quote
10146 (expand-file-name
10147 (file-name-as-directory
10148 default-directory))))
10149 (expand-file-name path))
10150 ;; We are linking a file with relative path name.
10151 (setq path (substring (expand-file-name path)
10152 (match-end 0)))
10153 (setq path (abbreviate-file-name (expand-file-name path)))))))
10154 (setq link (concat type path))
10155 (if (equal desc origpath)
10156 (setq desc path))))
10158 (if org-make-link-description-function
10159 (setq desc
10160 (or (condition-case nil
10161 (funcall org-make-link-description-function link desc)
10162 (error (progn (message "Can't get link description from `%s'"
10163 (symbol-name org-make-link-description-function))
10164 (sit-for 2) nil)))
10165 (read-string "Description: " default-description)))
10166 (if default-description (setq desc default-description)
10167 (setq desc (or (and auto-desc desc)
10168 (read-string "Description: " desc)))))
10170 (unless (string-match "\\S-" desc) (setq desc nil))
10171 (if remove (apply 'delete-region remove))
10172 (insert (org-make-link-string link desc))))
10174 (defun org-link-try-special-completion (type)
10175 "If there is completion support for link type TYPE, offer it."
10176 (let ((fun (intern (concat "org-" type "-complete-link"))))
10177 (if (functionp fun)
10178 (funcall fun)
10179 (read-string "Link (no completion support): " (concat type ":")))))
10181 (defun org-file-complete-link (&optional arg)
10182 "Create a file link using completion."
10183 (let (file link)
10184 (setq file (org-iread-file-name "File: "))
10185 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10186 (pwd1 (file-name-as-directory (abbreviate-file-name
10187 (expand-file-name ".")))))
10188 (cond
10189 ((equal arg '(16))
10190 (setq link (concat
10191 "file:"
10192 (abbreviate-file-name (expand-file-name file)))))
10193 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10194 (setq link (concat "file:" (match-string 1 file))))
10195 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10196 (expand-file-name file))
10197 (setq link (concat
10198 "file:" (match-string 1 (expand-file-name file)))))
10199 (t (setq link (concat "file:" file)))))
10200 link))
10202 (defun org-iread-file-name (&rest args)
10203 "Read-file-name using `ido-mode' speedup if available.
10204 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10205 See `read-file-name' for a description of parameters."
10206 (org-without-partial-completion
10207 (if (and org-completion-use-ido
10208 (fboundp 'ido-read-file-name)
10209 (boundp 'ido-mode) ido-mode
10210 (listp (second args)))
10211 (let ((ido-enter-matching-directory nil))
10212 (apply 'ido-read-file-name args))
10213 (apply 'read-file-name args))))
10215 (defun org-completing-read (&rest args)
10216 "Completing-read with SPACE being a normal character."
10217 (let ((enable-recursive-minibuffers t)
10218 (minibuffer-local-completion-map
10219 (copy-keymap minibuffer-local-completion-map)))
10220 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10221 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10222 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10223 (apply 'org-icompleting-read args)))
10225 (defun org-completing-read-no-i (&rest args)
10226 (let (org-completion-use-ido org-completion-use-iswitchb)
10227 (apply 'org-completing-read args)))
10229 (defun org-iswitchb-completing-read (prompt choices &rest args)
10230 "Use iswitch as a completing-read replacement to choose from choices.
10231 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10232 from."
10233 (let* ((iswitchb-use-virtual-buffers nil)
10234 (iswitchb-make-buflist-hook
10235 (lambda ()
10236 (setq iswitchb-temp-buflist choices))))
10237 (iswitchb-read-buffer prompt)))
10239 (defun org-icompleting-read (&rest args)
10240 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10241 (org-without-partial-completion
10242 (if (and org-completion-use-ido
10243 (fboundp 'ido-completing-read)
10244 (boundp 'ido-mode) ido-mode
10245 (listp (second args)))
10246 (let ((ido-enter-matching-directory nil))
10247 (apply 'ido-completing-read (concat (car args))
10248 (if (consp (car (nth 1 args)))
10249 (mapcar 'car (nth 1 args))
10250 (nth 1 args))
10251 (cddr args)))
10252 (if (and org-completion-use-iswitchb
10253 (boundp 'iswitchb-mode) iswitchb-mode
10254 (listp (second args)))
10255 (apply 'org-iswitchb-completing-read (concat (car args))
10256 (if (consp (car (nth 1 args)))
10257 (mapcar 'car (nth 1 args))
10258 (nth 1 args))
10259 (cddr args))
10260 (apply 'completing-read args)))))
10262 (defun org-extract-attributes (s)
10263 "Extract the attributes cookie from a string and set as text property."
10264 (let (a attr (start 0) key value)
10265 (save-match-data
10266 (when (string-match "{{\\([^}]+\\)}}$" s)
10267 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10268 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10269 (setq key (match-string 1 a) value (match-string 2 a)
10270 start (match-end 0)
10271 attr (plist-put attr (intern key) value))))
10272 (org-add-props s nil 'org-attr attr))
10275 ;;; Opening/following a link
10277 (defvar org-link-search-failed nil)
10279 (defvar org-open-link-functions nil
10280 "Hook for functions finding a plain text link.
10281 These functions must take a single argument, the link content.
10282 They will be called for links that look like [[link text][description]]
10283 when LINK TEXT does not have a protocol like \"http:\" and does not look
10284 like a filename (e.g. \"./blue.png\").
10286 These functions will be called *before* Org attempts to resolve the
10287 link by doing text searches in the current buffer - so if you want a
10288 link \"[[target]]\" to still find \"<<target>>\", your function should
10289 handle this as a special case.
10291 When the function does handle the link, it must return a non-nil value.
10292 If it decides that it is not responsible for this link, it must return
10293 nil to indicate that that Org-mode can continue with other options
10294 like exact and fuzzy text search.")
10296 (defun org-next-link (&optional search-backward)
10297 "Move forward to the next link.
10298 If the link is in hidden text, expose it."
10299 (interactive "P")
10300 (when (and org-link-search-failed (eq this-command last-command))
10301 (goto-char (point-min))
10302 (message "Link search wrapped back to beginning of buffer"))
10303 (setq org-link-search-failed nil)
10304 (let* ((pos (point))
10305 (ct (org-context))
10306 (a (assoc :link ct))
10307 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10308 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10309 ((looking-at org-any-link-re)
10310 ;; Don't stay stuck at link without an org-link face
10311 (forward-char (if search-backward -1 1))))
10312 (if (funcall srch-fun org-any-link-re nil t)
10313 (progn
10314 (goto-char (match-beginning 0))
10315 (if (outline-invisible-p) (org-show-context)))
10316 (goto-char pos)
10317 (setq org-link-search-failed t)
10318 (message "No further link found"))))
10320 (defun org-previous-link ()
10321 "Move backward to the previous link.
10322 If the link is in hidden text, expose it."
10323 (interactive)
10324 (funcall 'org-next-link t))
10326 (defun org-translate-link (s)
10327 "Translate a link string if a translation function has been defined."
10328 (if (and org-link-translation-function
10329 (fboundp org-link-translation-function)
10330 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10331 (progn
10332 (setq s (funcall org-link-translation-function
10333 (match-string 1 s) (match-string 2 s)))
10334 (concat (car s) ":" (cdr s)))
10337 (defun org-translate-link-from-planner (type path)
10338 "Translate a link from Emacs Planner syntax so that Org can follow it.
10339 This is still an experimental function, your mileage may vary."
10340 (cond
10341 ((member type '("http" "https" "news" "ftp"))
10342 ;; standard Internet links are the same.
10343 nil)
10344 ((and (equal type "irc") (string-match "^//" path))
10345 ;; Planner has two / at the beginning of an irc link, we have 1.
10346 ;; We should have zero, actually....
10347 (setq path (substring path 1)))
10348 ((and (equal type "lisp") (string-match "^/" path))
10349 ;; Planner has a slash, we do not.
10350 (setq type "elisp" path (substring path 1)))
10351 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10352 ;; A typical message link. Planner has the id after the final slash,
10353 ;; we separate it with a hash mark
10354 (setq path (concat (match-string 1 path) "#"
10355 (org-remove-angle-brackets (match-string 2 path))))))
10356 (cons type path))
10358 (defun org-find-file-at-mouse (ev)
10359 "Open file link or URL at mouse."
10360 (interactive "e")
10361 (mouse-set-point ev)
10362 (org-open-at-point 'in-emacs))
10364 (defun org-open-at-mouse (ev)
10365 "Open file link or URL at mouse.
10366 See the docstring of `org-open-file' for details."
10367 (interactive "e")
10368 (mouse-set-point ev)
10369 (if (eq major-mode 'org-agenda-mode)
10370 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10371 (org-open-at-point))
10373 (defvar org-window-config-before-follow-link nil
10374 "The window configuration before following a link.
10375 This is saved in case the need arises to restore it.")
10377 (defvar org-open-link-marker (make-marker)
10378 "Marker pointing to the location where `org-open-at-point; was called.")
10380 ;;;###autoload
10381 (defun org-open-at-point-global ()
10382 "Follow a link like Org-mode does.
10383 This command can be called in any mode to follow a link that has
10384 Org-mode syntax."
10385 (interactive)
10386 (org-run-like-in-org-mode 'org-open-at-point))
10388 ;;;###autoload
10389 (defun org-open-link-from-string (s &optional arg reference-buffer)
10390 "Open a link in the string S, as if it was in Org-mode."
10391 (interactive "sLink: \nP")
10392 (let ((reference-buffer (or reference-buffer (current-buffer))))
10393 (with-temp-buffer
10394 (let ((org-inhibit-startup (not reference-buffer)))
10395 (org-mode)
10396 (insert s)
10397 (goto-char (point-min))
10398 (when reference-buffer
10399 (setq org-link-abbrev-alist-local
10400 (with-current-buffer reference-buffer
10401 org-link-abbrev-alist-local)))
10402 (org-open-at-point arg reference-buffer)))))
10404 (defvar org-open-at-point-functions nil
10405 "Hook that is run when following a link at point.
10407 Functions in this hook must return t if they identify and follow
10408 a link at point. If they don't find anything interesting at point,
10409 they must return nil.")
10411 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10412 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10413 (defun org-open-at-point (&optional arg reference-buffer)
10414 "Open link at or after point.
10415 If there is no link at point, this function will search forward up to
10416 the end of the current line.
10417 Normally, files will be opened by an appropriate application. If the
10418 optional prefix argument ARG is non-nil, Emacs will visit the file.
10419 With a double prefix argument, try to open outside of Emacs, in the
10420 application the system uses for this file type."
10421 (interactive "P")
10422 ;; if in a code block, then open the block's results
10423 (unless (call-interactively #'org-babel-open-src-block-result)
10424 (org-load-modules-maybe)
10425 (move-marker org-open-link-marker (point))
10426 (setq org-window-config-before-follow-link (current-window-configuration))
10427 (org-remove-occur-highlights nil nil t)
10428 (cond
10429 ((and (org-at-heading-p)
10430 (not (org-at-timestamp-p t))
10431 (not (org-in-regexp
10432 (concat org-plain-link-re "\\|"
10433 org-bracket-link-regexp "\\|"
10434 org-angle-link-re "\\|"
10435 "[ \t]:[^ \t\n]+:[ \t]*$")))
10436 (not (get-text-property (point) 'org-linked-text)))
10437 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10438 (lk0 (car lkall))
10439 (lk (if (stringp lk0) (list lk0) lk0))
10440 (lkend (cdr lkall)))
10441 (mapcar (lambda(l)
10442 (search-forward l nil lkend)
10443 (goto-char (match-beginning 0))
10444 (org-open-at-point))
10445 lk))
10446 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10447 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10448 ((and (org-at-timestamp-p t)
10449 (not (org-in-regexp org-bracket-link-regexp)))
10450 (org-follow-timestamp-link))
10451 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10452 (not (org-in-regexp org-any-link-re)))
10453 (org-footnote-action))
10455 (let (type path link line search (pos (point)))
10456 (catch 'match
10457 (save-excursion
10458 (skip-chars-forward "^]\n\r")
10459 (when (org-in-regexp org-bracket-link-regexp 1)
10460 (setq link (org-extract-attributes
10461 (org-link-unescape (org-match-string-no-properties 1))))
10462 (while (string-match " *\n *" link)
10463 (setq link (replace-match " " t t link)))
10464 (setq link (org-link-expand-abbrev link))
10465 (cond
10466 ((or (file-name-absolute-p link)
10467 (string-match "^\\.\\.?/" link))
10468 (setq type "file" path link))
10469 ((string-match org-link-re-with-space3 link)
10470 (setq type (match-string 1 link) path (match-string 2 link)))
10471 ((string-match "^help:+\\(.+\\)" link)
10472 (setq type "help" path (match-string 1 link)))
10473 (t (setq type "thisfile" path link)))
10474 (throw 'match t)))
10476 (when (get-text-property (point) 'org-linked-text)
10477 (setq type "thisfile"
10478 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10479 (1+ (point)) (point))
10480 path (buffer-substring
10481 (or (previous-single-property-change pos 'org-linked-text)
10482 (point-min))
10483 (or (next-single-property-change pos 'org-linked-text)
10484 (point-max)))
10485 ;; Ensure we will search for a <<<radio>>> link, not
10486 ;; a simple reference like <<ref>>
10487 path (concat "<" path))
10488 (throw 'match t))
10490 (save-excursion
10491 (when (or (org-in-regexp org-angle-link-re)
10492 (let ((match (org-in-regexp org-plain-link-re)))
10493 ;; Check a plain link is not within a bracket link
10494 (and match
10495 (save-excursion
10496 (progn
10497 (goto-char (car match))
10498 (not (org-in-regexp org-bracket-link-regexp))))))
10499 (let ((line_ending (save-excursion (end-of-line) (point))))
10500 ;; We are in a line before a plain or bracket link
10501 (or (re-search-forward org-plain-link-re line_ending t)
10502 (re-search-forward org-bracket-link-regexp line_ending t))))
10503 (setq type (match-string 1)
10504 path (org-link-unescape (match-string 2)))
10505 (throw 'match t)))
10506 (save-excursion
10507 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10508 (setq type "tags"
10509 path (match-string 1))
10510 (while (string-match ":" path)
10511 (setq path (replace-match "+" t t path)))
10512 (throw 'match t)))
10513 (when (org-in-regexp "<\\([^><\n]+\\)>")
10514 (setq type "tree-match"
10515 path (match-string 1))
10516 (throw 'match t)))
10517 (unless path
10518 (user-error "No link found"))
10520 ;; switch back to reference buffer
10521 ;; needed when if called in a temporary buffer through
10522 ;; org-open-link-from-string
10523 (with-current-buffer (or reference-buffer (current-buffer))
10525 ;; Remove any trailing spaces in path
10526 (if (string-match " +\\'" path)
10527 (setq path (replace-match "" t t path)))
10528 (if (and org-link-translation-function
10529 (fboundp org-link-translation-function))
10530 ;; Check if we need to translate the link
10531 (let ((tmp (funcall org-link-translation-function type path)))
10532 (setq type (car tmp) path (cdr tmp))))
10534 (cond
10536 ((assoc type org-link-protocols)
10537 (funcall (nth 1 (assoc type org-link-protocols)) path))
10539 ((equal type "help")
10540 (let ((f-or-v (intern path)))
10541 (cond ((fboundp f-or-v)
10542 (describe-function f-or-v))
10543 ((boundp f-or-v)
10544 (describe-variable f-or-v))
10545 (t (error "Not a known function or variable")))))
10547 ((equal type "mailto")
10548 (let ((cmd (car org-link-mailto-program))
10549 (args (cdr org-link-mailto-program)) args1
10550 (address path) (subject "") a)
10551 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10552 (setq address (match-string 1 path)
10553 subject (org-link-escape (match-string 2 path))))
10554 (while args
10555 (cond
10556 ((not (stringp (car args))) (push (pop args) args1))
10557 (t (setq a (pop args))
10558 (if (string-match "%a" a)
10559 (setq a (replace-match address t t a)))
10560 (if (string-match "%s" a)
10561 (setq a (replace-match subject t t a)))
10562 (push a args1))))
10563 (apply cmd (nreverse args1))))
10565 ((member type '("http" "https" "ftp" "news"))
10566 ;; In the example of the http Org link
10567 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10568 ;; to open a browser with +subject:"Release 8.2" in the
10569 ;; query field the variable `path' contains
10570 ;; [...]=%2Bsubject:"Release+8.2", `url-encode-url'
10571 ;; converts correct to [...]=%2Bsubject:%22Release+8.2%22
10572 ;; and `org-link-escape-browser' converts wrong to
10573 ;; [...]=%252Bsubject:%22Release+8.2%22.
10575 ;; `url-encode-url' is available since Emacs 24.3.1 and
10576 ;; `org-link-escape-browser' can be removed altogether
10577 ;; once Org drops support for Emacs 24.1 and 24.2.
10578 (browse-url (funcall (if (fboundp 'url-encode-url)
10579 #'url-encode-url
10580 #'org-link-escape-browser)
10581 (concat type ":" path))))
10583 ((string= type "doi")
10584 ;; See comments for type http above
10585 (browse-url (funcall (if (fboundp 'url-encode-url)
10586 #'url-encode-url
10587 #'org-link-escape-browser)
10588 (concat org-doi-server-url path))))
10590 ((member type '("message"))
10591 (browse-url (concat type ":" path)))
10593 ((string= type "tags")
10594 (org-tags-view arg path))
10596 ((string= type "tree-match")
10597 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10599 ((string= type "file")
10600 (if (string-match "::\\([0-9]+\\)\\'" path)
10601 (setq line (string-to-number (match-string 1 path))
10602 path (substring path 0 (match-beginning 0)))
10603 (if (string-match "::\\(.+\\)\\'" path)
10604 (setq search (match-string 1 path)
10605 path (substring path 0 (match-beginning 0)))))
10606 (if (string-match "[*?{]" (file-name-nondirectory path))
10607 (dired path)
10608 (org-open-file path arg line search)))
10610 ((string= type "shell")
10611 (let ((buf (generate-new-buffer "*Org Shell Output"))
10612 (cmd path))
10613 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10614 (string-match org-confirm-shell-link-not-regexp cmd))
10615 (not org-confirm-shell-link-function)
10616 (funcall org-confirm-shell-link-function
10617 (format "Execute \"%s\" in shell? "
10618 (org-add-props cmd nil
10619 'face 'org-warning))))
10620 (progn
10621 (message "Executing %s" cmd)
10622 (shell-command cmd buf)
10623 (if (featurep 'midnight)
10624 (setq clean-buffer-list-kill-buffer-names
10625 (cons buf clean-buffer-list-kill-buffer-names))))
10626 (error "Abort"))))
10628 ((string= type "elisp")
10629 (let ((cmd path))
10630 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10631 (string-match org-confirm-elisp-link-not-regexp cmd))
10632 (not org-confirm-elisp-link-function)
10633 (funcall org-confirm-elisp-link-function
10634 (format "Execute \"%s\" as elisp? "
10635 (org-add-props cmd nil
10636 'face 'org-warning))))
10637 (message "%s => %s" cmd
10638 (if (equal (string-to-char cmd) ?\()
10639 (eval (read cmd))
10640 (call-interactively (read cmd))))
10641 (error "Abort"))))
10643 ((and (string= type "thisfile")
10644 (or (run-hook-with-args-until-success
10645 'org-open-link-functions path)
10646 (and link
10647 (string-match "^id:" link)
10648 (or (featurep 'org-id) (require 'org-id))
10649 (progn
10650 (funcall (nth 1 (assoc "id" org-link-protocols))
10651 (substring path 3))
10652 t)))))
10654 ((string= type "thisfile")
10655 (if arg
10656 (switch-to-buffer-other-window
10657 (org-get-buffer-for-internal-link (current-buffer)))
10658 (org-mark-ring-push))
10659 (let ((cmd `(org-link-search
10660 ,path
10661 ,(cond ((equal arg '(4)) ''occur)
10662 ((equal arg '(16)) ''org-occur))
10663 ,pos)))
10664 (condition-case nil (let ((org-link-search-inhibit-query t))
10665 (eval cmd))
10666 (error (progn (widen) (eval cmd))))))
10668 (t (browse-url-at-point)))))))
10669 (move-marker org-open-link-marker nil)
10670 (run-hook-with-args 'org-follow-link-hook)))
10672 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10673 "Offer links in the current entry and return the selected link.
10674 If there is only one link, return it.
10675 If NTH is an integer, return the NTH link found.
10676 If ZERO is a string, check also this string for a link, and if
10677 there is one, return it."
10678 (with-current-buffer buffer
10679 (save-excursion
10680 (save-restriction
10681 (widen)
10682 (goto-char marker)
10683 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10684 "\\(" org-angle-link-re "\\)\\|"
10685 "\\(" org-plain-link-re "\\)"))
10686 (cnt ?0)
10687 (in-emacs (if (integerp nth) nil nth))
10688 have-zero end links link c)
10689 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10690 (push (match-string 0 zero) links)
10691 (setq cnt (1- cnt) have-zero t))
10692 (save-excursion
10693 (org-back-to-heading t)
10694 (setq end (save-excursion (outline-next-heading) (point)))
10695 (while (re-search-forward re end t)
10696 (push (match-string 0) links))
10697 (setq links (org-uniquify (reverse links))))
10698 (cond
10699 ((null links)
10700 (message "No links"))
10701 ((equal (length links) 1)
10702 (setq link (car links)))
10703 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10704 (setq link (nth (if have-zero nth (1- nth)) links)))
10705 (t ; we have to select a link
10706 (save-excursion
10707 (save-window-excursion
10708 (delete-other-windows)
10709 (with-output-to-temp-buffer "*Select Link*"
10710 (mapc (lambda (l)
10711 (if (not (string-match org-bracket-link-regexp l))
10712 (princ (format "[%c] %s\n" (incf cnt)
10713 (org-remove-angle-brackets l)))
10714 (if (match-end 3)
10715 (princ (format "[%c] %s (%s)\n" (incf cnt)
10716 (match-string 3 l) (match-string 1 l)))
10717 (princ (format "[%c] %s\n" (incf cnt)
10718 (match-string 1 l))))))
10719 links))
10720 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10721 (message "Select link to open, RET to open all:")
10722 (setq c (read-char-exclusive))
10723 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10724 (when (equal c ?q) (error "Abort"))
10725 (if (equal c ?\C-m)
10726 (setq link links)
10727 (setq nth (- c ?0))
10728 (if have-zero (setq nth (1+ nth)))
10729 (unless (and (integerp nth) (>= (length links) nth))
10730 (user-error "Invalid link selection"))
10731 (setq link (nth (1- nth) links)))))
10732 (cons link end))))))
10734 ;; Add special file links that specify the way of opening
10736 (org-add-link-type "file+sys" 'org-open-file-with-system)
10737 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10738 (defun org-open-file-with-system (path)
10739 "Open file at PATH using the system way of opening it."
10740 (org-open-file path 'system))
10741 (defun org-open-file-with-emacs (path)
10742 "Open file at PATH in Emacs."
10743 (org-open-file path 'emacs))
10746 ;;; File search
10748 (defvar org-create-file-search-functions nil
10749 "List of functions to construct the right search string for a file link.
10750 These functions are called in turn with point at the location to
10751 which the link should point.
10753 A function in the hook should first test if it would like to
10754 handle this file type, for example by checking the `major-mode'
10755 or the file extension. If it decides not to handle this file, it
10756 should just return nil to give other functions a chance. If it
10757 does handle the file, it must return the search string to be used
10758 when following the link. The search string will be part of the
10759 file link, given after a double colon, and `org-open-at-point'
10760 will automatically search for it. If special measures must be
10761 taken to make the search successful, another function should be
10762 added to the companion hook `org-execute-file-search-functions',
10763 which see.
10765 A function in this hook may also use `setq' to set the variable
10766 `description' to provide a suggestion for the descriptive text to
10767 be used for this link when it gets inserted into an Org-mode
10768 buffer with \\[org-insert-link].")
10770 (defvar org-execute-file-search-functions nil
10771 "List of functions to execute a file search triggered by a link.
10773 Functions added to this hook must accept a single argument, the
10774 search string that was part of the file link, the part after the
10775 double colon. The function must first check if it would like to
10776 handle this search, for example by checking the `major-mode' or
10777 the file extension. If it decides not to handle this search, it
10778 should just return nil to give other functions a chance. If it
10779 does handle the search, it must return a non-nil value to keep
10780 other functions from trying.
10782 Each function can access the current prefix argument through the
10783 variable `current-prefix-arg'. Note that a single prefix is used
10784 to force opening a link in Emacs, so it may be good to only use a
10785 numeric or double prefix to guide the search function.
10787 In case this is needed, a function in this hook can also restore
10788 the window configuration before `org-open-at-point' was called using:
10790 (set-window-configuration org-window-config-before-follow-link)")
10792 (defun org-link-search (s &optional type avoid-pos stealth)
10793 "Search for a link search option.
10794 If S is surrounded by forward slashes, it is interpreted as a
10795 regular expression. In org-mode files, this will create an `org-occur'
10796 sparse tree. In ordinary files, `occur' will be used to list matches.
10797 If the current buffer is in `dired-mode', grep will be used to search
10798 in all files. If AVOID-POS is given, ignore matches near that position.
10800 When optional argument STEALTH is non-nil, do not modify
10801 visibility around point, thus ignoring
10802 `org-show-hierarchy-above', `org-show-following-heading' and
10803 `org-show-siblings' variables."
10804 (let ((case-fold-search t)
10805 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10806 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10807 (append '(("") (" ") ("\t") ("\n"))
10808 org-emphasis-alist)
10809 "\\|") "\\)"))
10810 (pos (point))
10811 (pre nil) (post nil)
10812 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10813 (cond
10814 ;; First check if there are any special search functions
10815 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10816 ;; Now try the builtin stuff
10817 ((and (equal (string-to-char s0) ?#)
10818 (> (length s0) 1)
10819 (save-excursion
10820 (goto-char (point-min))
10821 (and
10822 (re-search-forward
10823 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10824 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10825 (setq type 'dedicated
10826 pos (match-beginning 0))))
10827 ;; There is an exact target for this
10828 (goto-char pos)
10829 (org-back-to-heading t)))
10830 ((save-excursion
10831 (goto-char (point-min))
10832 (and
10833 (re-search-forward
10834 (concat "<<" (regexp-quote s0) ">>") nil t)
10835 (setq type 'dedicated
10836 pos (match-beginning 0))))
10837 ;; There is an exact target for this
10838 (goto-char pos))
10839 ((save-excursion
10840 (goto-char (point-min))
10841 (and
10842 (re-search-forward
10843 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10844 (setq type 'dedicated pos (match-beginning 0))))
10845 ;; Found an element with a matching #+name affiliated keyword.
10846 (goto-char pos))
10847 ((and (string-match "^(\\(.*\\))$" s0)
10848 (save-excursion
10849 (goto-char (point-min))
10850 (and
10851 (re-search-forward
10852 (concat "[^[]" (regexp-quote
10853 (format org-coderef-label-format
10854 (match-string 1 s0))))
10855 nil t)
10856 (setq type 'dedicated
10857 pos (1+ (match-beginning 0))))))
10858 ;; There is a coderef target for this
10859 (goto-char pos))
10860 ((string-match "^/\\(.*\\)/$" s)
10861 ;; A regular expression
10862 (cond
10863 ((derived-mode-p 'org-mode)
10864 (org-occur (match-string 1 s)))
10865 (t (org-do-occur (match-string 1 s)))))
10866 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10867 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10868 (goto-char (point-min))
10869 (cond
10870 ((let (case-fold-search)
10871 (re-search-forward (format org-complex-heading-regexp-format
10872 (regexp-quote s))
10873 nil t))
10874 ;; OK, found a match
10875 (setq type 'dedicated)
10876 (goto-char (match-beginning 0)))
10877 ((and (not org-link-search-inhibit-query)
10878 (eq org-link-search-must-match-exact-headline 'query-to-create)
10879 (y-or-n-p "No match - create this as a new heading? "))
10880 (goto-char (point-max))
10881 (or (bolp) (newline))
10882 (insert "* " s "\n")
10883 (beginning-of-line 0))
10885 (goto-char pos)
10886 (error "No match"))))
10888 ;; A normal search string
10889 (when (equal (string-to-char s) ?*)
10890 ;; Anchor on headlines, post may include tags.
10891 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10892 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10893 s (substring s 1)))
10894 (remove-text-properties
10895 0 (length s)
10896 '(face nil mouse-face nil keymap nil fontified nil) s)
10897 ;; Make a series of regular expressions to find a match
10898 (setq words (org-split-string s "[ \n\r\t]+")
10900 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10901 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10902 "\\)" markers)
10903 re2a_ (concat "\\(" (mapconcat 'downcase words
10904 "[ \t\r\n]+") "\\)[ \t\r\n]")
10905 re2a (concat "[ \t\r\n]" re2a_)
10906 re4_ (concat "\\(" (mapconcat 'downcase words
10907 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10908 re4 (concat "[^a-zA-Z_]" re4_)
10910 re1 (concat pre re2 post)
10911 re3 (concat pre (if pre re4_ re4) post)
10912 re5 (concat pre ".*" re4)
10913 re2 (concat pre re2)
10914 re2a (concat pre (if pre re2a_ re2a))
10915 re4 (concat pre (if pre re4_ re4))
10916 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10917 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10918 re5 "\\)"))
10919 (cond
10920 ((eq type 'org-occur) (org-occur reall))
10921 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10922 (t (goto-char (point-min))
10923 (setq type 'fuzzy)
10924 (if (or (and (org-search-not-self 1 re0 nil t)
10925 (setq type 'dedicated))
10926 (org-search-not-self 1 re1 nil t)
10927 (org-search-not-self 1 re2 nil t)
10928 (org-search-not-self 1 re2a nil t)
10929 (org-search-not-self 1 re3 nil t)
10930 (org-search-not-self 1 re4 nil t)
10931 (org-search-not-self 1 re5 nil t))
10932 (goto-char (match-beginning 1))
10933 (goto-char pos)
10934 (error "No match"))))))
10935 (and (derived-mode-p 'org-mode)
10936 (not stealth)
10937 (org-show-context 'link-search))
10938 type))
10940 (defun org-search-not-self (group &rest args)
10941 "Execute `re-search-forward', but only accept matches that do not
10942 enclose the position of `org-open-link-marker'."
10943 (let ((m org-open-link-marker))
10944 (catch 'exit
10945 (while (apply 're-search-forward args)
10946 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10947 (goto-char (match-end group))
10948 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10949 (> (match-beginning 0) (marker-position m))
10950 (< (match-end 0) (marker-position m)))
10951 (save-match-data
10952 (or (not (org-in-regexp
10953 org-bracket-link-analytic-regexp 1))
10954 (not (match-end 4)) ; no description
10955 (and (<= (match-beginning 4) (point))
10956 (>= (match-end 4) (point))))))
10957 (throw 'exit (point))))))))
10959 (defun org-get-buffer-for-internal-link (buffer)
10960 "Return a buffer to be used for displaying the link target of internal links."
10961 (cond
10962 ((not org-display-internal-link-with-indirect-buffer)
10963 buffer)
10964 ((string-match "(Clone)$" (buffer-name buffer))
10965 (message "Buffer is already a clone, not making another one")
10966 ;; we also do not modify visibility in this case
10967 buffer)
10968 (t ; make a new indirect buffer for displaying the link
10969 (let* ((bn (buffer-name buffer))
10970 (ibn (concat bn "(Clone)"))
10971 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10972 (with-current-buffer ib (org-overview))
10973 ib))))
10975 (defun org-do-occur (regexp &optional cleanup)
10976 "Call the Emacs command `occur'.
10977 If CLEANUP is non-nil, remove the printout of the regular expression
10978 in the *Occur* buffer. This is useful if the regex is long and not useful
10979 to read."
10980 (occur regexp)
10981 (when cleanup
10982 (let ((cwin (selected-window)) win beg end)
10983 (when (setq win (get-buffer-window "*Occur*"))
10984 (select-window win))
10985 (goto-char (point-min))
10986 (when (re-search-forward "match[a-z]+" nil t)
10987 (setq beg (match-end 0))
10988 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10989 (setq end (1- (match-beginning 0)))))
10990 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10991 (goto-char (point-min))
10992 (select-window cwin))))
10994 ;;; The mark ring for links jumps
10996 (defvar org-mark-ring nil
10997 "Mark ring for positions before jumps in Org-mode.")
10998 (defvar org-mark-ring-last-goto nil
10999 "Last position in the mark ring used to go back.")
11000 ;; Fill and close the ring
11001 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11002 (loop for i from 1 to org-mark-ring-length do
11003 (push (make-marker) org-mark-ring))
11004 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11005 org-mark-ring)
11007 (defun org-mark-ring-push (&optional pos buffer)
11008 "Put the current position or POS into the mark ring and rotate it."
11009 (interactive)
11010 (setq pos (or pos (point)))
11011 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11012 (move-marker (car org-mark-ring)
11013 (or pos (point))
11014 (or buffer (current-buffer)))
11015 (message "%s"
11016 (substitute-command-keys
11017 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11019 (defun org-mark-ring-goto (&optional n)
11020 "Jump to the previous position in the mark ring.
11021 With prefix arg N, jump back that many stored positions. When
11022 called several times in succession, walk through the entire ring.
11023 Org-mode commands jumping to a different position in the current file,
11024 or to another Org-mode file, automatically push the old position
11025 onto the ring."
11026 (interactive "p")
11027 (let (p m)
11028 (if (eq last-command this-command)
11029 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11030 (setq p org-mark-ring))
11031 (setq org-mark-ring-last-goto p)
11032 (setq m (car p))
11033 (org-pop-to-buffer-same-window (marker-buffer m))
11034 (goto-char m)
11035 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11037 (defun org-remove-angle-brackets (s)
11038 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11039 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11041 (defun org-add-angle-brackets (s)
11042 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11043 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11045 (defun org-remove-double-quotes (s)
11046 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11047 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11050 ;;; Following specific links
11052 (defun org-follow-timestamp-link ()
11053 "Open an agenda view for the time-stamp date/range at point."
11054 (cond
11055 ((org-at-date-range-p t)
11056 (let ((org-agenda-start-on-weekday)
11057 (t1 (match-string 1))
11058 (t2 (match-string 2)) tt1 tt2)
11059 (setq tt1 (time-to-days (org-time-string-to-time t1))
11060 tt2 (time-to-days (org-time-string-to-time t2)))
11061 (let ((org-agenda-buffer-tmp-name
11062 (format "*Org Agenda(a:%s)"
11063 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11064 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11065 ((org-at-timestamp-p t)
11066 (let ((org-agenda-buffer-tmp-name
11067 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11068 (org-agenda-list nil (time-to-days (org-time-string-to-time
11069 (substring (match-string 1) 0 10)))
11070 1)))
11071 (t (error "This should not happen"))))
11074 ;;; Following file links
11075 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11076 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11077 (declare-function mailcap-mime-info
11078 "mailcap" (string &optional request no-decode))
11079 (defvar org-wait nil)
11080 (defun org-open-file (path &optional in-emacs line search)
11081 "Open the file at PATH.
11082 First, this expands any special file name abbreviations. Then the
11083 configuration variable `org-file-apps' is checked if it contains an
11084 entry for this file type, and if yes, the corresponding command is launched.
11086 If no application is found, Emacs simply visits the file.
11088 With optional prefix argument IN-EMACS, Emacs will visit the file.
11089 With a double \\[universal-argument] \\[universal-argument] \
11090 prefix arg, Org tries to avoid opening in Emacs
11091 and to use an external application to visit the file.
11093 Optional LINE specifies a line to go to, optional SEARCH a string
11094 to search for. If LINE or SEARCH is given, the file will be
11095 opened in Emacs, unless an entry from org-file-apps that makes
11096 use of groups in a regexp matches.
11098 If you want to change the way frames are used when following a
11099 link, please customize `org-link-frame-setup'.
11101 If the file does not exist, an error is thrown."
11102 (let* ((file (if (equal path "")
11103 buffer-file-name
11104 (substitute-in-file-name (expand-file-name path))))
11105 (file-apps (append org-file-apps (org-default-apps)))
11106 (apps (org-remove-if
11107 'org-file-apps-entry-match-against-dlink-p file-apps))
11108 (apps-dlink (org-remove-if-not
11109 'org-file-apps-entry-match-against-dlink-p file-apps))
11110 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11111 (dirp (if remp nil (file-directory-p file)))
11112 (file (if (and dirp org-open-directory-means-index-dot-org)
11113 (concat (file-name-as-directory file) "index.org")
11114 file))
11115 (a-m-a-p (assq 'auto-mode apps))
11116 (dfile (downcase file))
11117 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11118 (link (cond ((and (eq line nil)
11119 (eq search nil))
11120 file)
11121 (line
11122 (concat file "::" (number-to-string line)))
11123 (search
11124 (concat file "::" search))))
11125 (dlink (downcase link))
11126 (old-buffer (current-buffer))
11127 (old-pos (point))
11128 (old-mode major-mode)
11129 ext cmd link-match-data)
11130 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11131 (setq ext (match-string 1 dfile))
11132 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11133 (setq ext (match-string 1 dfile))))
11134 (cond
11135 ((member in-emacs '((16) system))
11136 (setq cmd (cdr (assoc 'system apps))))
11137 (in-emacs (setq cmd 'emacs))
11139 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11140 (and dirp (cdr (assoc 'directory apps)))
11141 ; first, try matching against apps-dlink
11142 ; if we get a match here, store the match data for later
11143 (let ((match (assoc-default dlink apps-dlink
11144 'string-match)))
11145 (if match
11146 (progn (setq link-match-data (match-data))
11147 match)
11148 (progn (setq in-emacs (or in-emacs line search))
11149 nil))) ; if we have no match in apps-dlink,
11150 ; always open the file in emacs if line or search
11151 ; is given (for backwards compatibility)
11152 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11153 'string-match)
11154 (cdr (assoc ext apps))
11155 (cdr (assoc t apps))))))
11156 (when (eq cmd 'system)
11157 (setq cmd (cdr (assoc 'system apps))))
11158 (when (eq cmd 'default)
11159 (setq cmd (cdr (assoc t apps))))
11160 (when (eq cmd 'mailcap)
11161 (require 'mailcap)
11162 (mailcap-parse-mailcaps)
11163 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11164 (command (mailcap-mime-info mime-type)))
11165 (if (stringp command)
11166 (setq cmd command)
11167 (setq cmd 'emacs))))
11168 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11169 (not (file-exists-p file))
11170 (not org-open-non-existing-files))
11171 (user-error "No such file: %s" file))
11172 (cond
11173 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11174 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11175 (while (string-match "['\"]%s['\"]" cmd)
11176 (setq cmd (replace-match "%s" t t cmd)))
11177 (while (string-match "%s" cmd)
11178 (setq cmd (replace-match
11179 (save-match-data
11180 (shell-quote-argument
11181 (convert-standard-filename file)))
11182 t t cmd)))
11184 ;; Replace "%1", "%2" etc. in command with group matches from regex
11185 (save-match-data
11186 (let ((match-index 1)
11187 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11188 (set-match-data link-match-data)
11189 (while (<= match-index number-of-groups)
11190 (let ((regex (concat "%" (number-to-string match-index)))
11191 (replace-with (match-string match-index dlink)))
11192 (while (string-match regex cmd)
11193 (setq cmd (replace-match replace-with t t cmd))))
11194 (setq match-index (+ match-index 1)))))
11196 (save-window-excursion
11197 (message "Running %s...done" cmd)
11198 (start-process-shell-command cmd nil cmd)
11199 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11200 ((or (stringp cmd)
11201 (eq cmd 'emacs))
11202 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11203 (widen)
11204 (if line (progn (org-goto-line line)
11205 (if (derived-mode-p 'org-mode)
11206 (org-reveal)))
11207 (if search (org-link-search search))))
11208 ((consp cmd)
11209 (let ((file (convert-standard-filename file)))
11210 (save-match-data
11211 (set-match-data link-match-data)
11212 (eval cmd))))
11213 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11214 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11215 (or (not (equal old-buffer (current-buffer)))
11216 (not (equal old-pos (point))))
11217 (org-mark-ring-push old-pos old-buffer))))
11219 (defun org-file-apps-entry-match-against-dlink-p (entry)
11220 "This function returns non-nil if `entry' uses a regular
11221 expression which should be matched against the whole link by
11222 org-open-file.
11224 It assumes that is the case when the entry uses a regular
11225 expression which has at least one grouping construct and the
11226 action is either a lisp form or a command string containing
11227 '%1', i.e. using at least one subexpression match as a
11228 parameter."
11229 (let ((selector (car entry))
11230 (action (cdr entry)))
11231 (if (stringp selector)
11232 (and (> (regexp-opt-depth selector) 0)
11233 (or (and (stringp action)
11234 (string-match "%[0-9]" action))
11235 (consp action)))
11236 nil)))
11238 (defun org-default-apps ()
11239 "Return the default applications for this operating system."
11240 (cond
11241 ((eq system-type 'darwin)
11242 org-file-apps-defaults-macosx)
11243 ((eq system-type 'windows-nt)
11244 org-file-apps-defaults-windowsnt)
11245 (t org-file-apps-defaults-gnu)))
11247 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11248 "Convert extensions to regular expressions in the cars of LIST.
11249 Also, weed out any non-string entries, because the return value is used
11250 only for regexp matching.
11251 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11252 point to the symbol `emacs', indicating that the file should
11253 be opened in Emacs."
11254 (append
11255 (delq nil
11256 (mapcar (lambda (x)
11257 (if (not (stringp (car x)))
11259 (if (string-match "\\W" (car x))
11261 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11262 list))
11263 (if add-auto-mode
11264 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11266 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11267 (defun org-file-remote-p (file)
11268 "Test whether FILE specifies a location on a remote system.
11269 Return non-nil if the location is indeed remote.
11271 For example, the filename \"/user@host:/foo\" specifies a location
11272 on the system \"/user@host:\"."
11273 (cond ((fboundp 'file-remote-p)
11274 (file-remote-p file))
11275 ((fboundp 'tramp-handle-file-remote-p)
11276 (tramp-handle-file-remote-p file))
11277 ((and (boundp 'ange-ftp-name-format)
11278 (string-match (car ange-ftp-name-format) file))
11279 t)))
11282 ;;;; Refiling
11284 (defun org-get-org-file ()
11285 "Read a filename, with default directory `org-directory'."
11286 (let ((default (or org-default-notes-file remember-data-file)))
11287 (read-file-name (format "File name [%s]: " default)
11288 (file-name-as-directory org-directory)
11289 default)))
11291 (defun org-notes-order-reversed-p ()
11292 "Check if the current file should receive notes in reversed order."
11293 (cond
11294 ((not org-reverse-note-order) nil)
11295 ((eq t org-reverse-note-order) t)
11296 ((not (listp org-reverse-note-order)) nil)
11297 (t (catch 'exit
11298 (let ((all org-reverse-note-order)
11299 entry)
11300 (while (setq entry (pop all))
11301 (if (string-match (car entry) buffer-file-name)
11302 (throw 'exit (cdr entry))))
11303 nil)))))
11305 (defvar org-refile-target-table nil
11306 "The list of refile targets, created by `org-refile'.")
11308 (defvar org-agenda-new-buffers nil
11309 "Buffers created to visit agenda files.")
11311 (defvar org-refile-cache nil
11312 "Cache for refile targets.")
11314 (defvar org-refile-markers nil
11315 "All the markers used for caching refile locations.")
11317 (defun org-refile-marker (pos)
11318 "Get a new refile marker, but only if caching is in use."
11319 (if (not org-refile-use-cache)
11321 (let ((m (make-marker)))
11322 (move-marker m pos)
11323 (push m org-refile-markers)
11324 m)))
11326 (defun org-refile-cache-clear ()
11327 "Clear the refile cache and disable all the markers."
11328 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11329 (setq org-refile-markers nil)
11330 (setq org-refile-cache nil)
11331 (message "Refile cache has been cleared"))
11333 (defun org-refile-cache-check-set (set)
11334 "Check if all the markers in the cache still have live buffers."
11335 (let (marker)
11336 (catch 'exit
11337 (while (and set (setq marker (nth 3 (pop set))))
11338 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11339 (when (and marker (null (marker-buffer marker)))
11340 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11341 (sit-for 3)
11342 (throw 'exit nil)))
11343 t)))
11345 (defun org-refile-cache-put (set &rest identifiers)
11346 "Push the refile targets SET into the cache, under IDENTIFIERS."
11347 (let* ((key (sha1 (prin1-to-string identifiers)))
11348 (entry (assoc key org-refile-cache)))
11349 (if entry
11350 (setcdr entry set)
11351 (push (cons key set) org-refile-cache))))
11353 (defun org-refile-cache-get (&rest identifiers)
11354 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11355 (cond
11356 ((not org-refile-cache) nil)
11357 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11359 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11360 org-refile-cache))))
11361 (and set (org-refile-cache-check-set set) set)))))
11363 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11364 "Produce a table with refile targets."
11365 (let ((case-fold-search nil)
11366 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11367 (entries (or org-refile-targets '((nil . (:level . 1)))))
11368 targets tgs txt re files f desc descre fast-path-p level pos0)
11369 (message "Getting targets...")
11370 (with-current-buffer (or default-buffer (current-buffer))
11371 (while (setq entry (pop entries))
11372 (setq files (car entry) desc (cdr entry))
11373 (setq fast-path-p nil)
11374 (cond
11375 ((null files) (setq files (list (current-buffer))))
11376 ((eq files 'org-agenda-files)
11377 (setq files (org-agenda-files 'unrestricted)))
11378 ((and (symbolp files) (fboundp files))
11379 (setq files (funcall files)))
11380 ((and (symbolp files) (boundp files))
11381 (setq files (symbol-value files))))
11382 (if (stringp files) (setq files (list files)))
11383 (cond
11384 ((eq (car desc) :tag)
11385 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11386 ((eq (car desc) :todo)
11387 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11388 ((eq (car desc) :regexp)
11389 (setq descre (cdr desc)))
11390 ((eq (car desc) :level)
11391 (setq descre (concat "^\\*\\{" (number-to-string
11392 (if org-odd-levels-only
11393 (1- (* 2 (cdr desc)))
11394 (cdr desc)))
11395 "\\}[ \t]")))
11396 ((eq (car desc) :maxlevel)
11397 (setq fast-path-p t)
11398 (setq descre (concat "^\\*\\{1," (number-to-string
11399 (if org-odd-levels-only
11400 (1- (* 2 (cdr desc)))
11401 (cdr desc)))
11402 "\\}[ \t]")))
11403 (t (error "Bad refiling target description %s" desc)))
11404 (while (setq f (pop files))
11405 (with-current-buffer
11406 (if (bufferp f) f (org-get-agenda-file-buffer f))
11408 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11409 (progn
11410 (if (bufferp f) (setq f (buffer-file-name
11411 (buffer-base-buffer f))))
11412 (setq f (and f (expand-file-name f)))
11413 (if (eq org-refile-use-outline-path 'file)
11414 (push (list (file-name-nondirectory f) f nil nil) tgs))
11415 (save-excursion
11416 (save-restriction
11417 (widen)
11418 (goto-char (point-min))
11419 (while (re-search-forward descre nil t)
11420 (goto-char (setq pos0 (point-at-bol)))
11421 (catch 'next
11422 (when org-refile-target-verify-function
11423 (save-match-data
11424 (or (funcall org-refile-target-verify-function)
11425 (throw 'next t))))
11426 (when (and (looking-at org-complex-heading-regexp)
11427 (not (member (match-string 4) excluded-entries))
11428 (match-string 4))
11429 (setq level (org-reduced-level
11430 (- (match-end 1) (match-beginning 1)))
11431 txt (org-link-display-format (match-string 4))
11432 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11433 re (format org-complex-heading-regexp-format
11434 (regexp-quote (match-string 4))))
11435 (when org-refile-use-outline-path
11436 (setq txt (mapconcat
11437 'org-protect-slash
11438 (append
11439 (if (eq org-refile-use-outline-path
11440 'file)
11441 (list (file-name-nondirectory
11442 (buffer-file-name
11443 (buffer-base-buffer))))
11444 (if (eq org-refile-use-outline-path
11445 'full-file-path)
11446 (list (buffer-file-name
11447 (buffer-base-buffer)))))
11448 (org-get-outline-path fast-path-p
11449 level txt)
11450 (list txt))
11451 "/")))
11452 (push (list txt f re (org-refile-marker (point)))
11453 tgs)))
11454 (when (= (point) pos0)
11455 ;; verification function has not moved point
11456 (goto-char (point-at-eol))))))))
11457 (when org-refile-use-cache
11458 (org-refile-cache-put tgs (buffer-file-name) descre))
11459 (setq targets (append tgs targets))))))
11460 (message "Getting targets...done")
11461 (nreverse targets)))
11463 (defun org-protect-slash (s)
11464 (while (string-match "/" s)
11465 (setq s (replace-match "\\" t t s)))
11468 (defvar org-olpa (make-vector 20 nil))
11470 (defun org-get-outline-path (&optional fastp level heading)
11471 "Return the outline path to the current entry, as a list.
11473 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11474 routine which makes outline path derivations for an entire file,
11475 avoiding backtracing. Refile target collection makes use of that."
11476 (if fastp
11477 (progn
11478 (if (> level 19)
11479 (error "Outline path failure, more than 19 levels"))
11480 (loop for i from level upto 19 do
11481 (aset org-olpa i nil))
11482 (prog1
11483 (delq nil (append org-olpa nil))
11484 (aset org-olpa level heading)))
11485 (let (rtn case-fold-search)
11486 (save-excursion
11487 (save-restriction
11488 (widen)
11489 (while (org-up-heading-safe)
11490 (when (looking-at org-complex-heading-regexp)
11491 (push (org-trim
11492 (replace-regexp-in-string
11493 ;; Remove statistical/checkboxes cookies
11494 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11495 (org-match-string-no-properties 4)))
11496 rtn)))
11497 rtn)))))
11499 (defun org-format-outline-path (path &optional width prefix separator)
11500 "Format the outline path PATH for display.
11501 WIDTH is the maximum number of characters that is available.
11502 PREFIX is a prefix to be included in the returned string,
11503 such as the file name.
11504 SEPARATOR is inserted between the different parts of the path,
11505 the default is \"/\"."
11506 (setq width (or width 79))
11507 (if prefix (setq width (- width (length prefix))))
11508 (if (not path)
11509 (or prefix "")
11510 (let* ((nsteps (length path))
11511 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11512 (maxwidth (if (<= total-width width)
11513 10000 ;; everything fits
11514 ;; we need to shorten the level headings
11515 (/ (- width nsteps) nsteps)))
11516 (org-odd-levels-only nil)
11517 (n 0)
11518 (total (1+ (length prefix))))
11519 (setq maxwidth (max maxwidth 10))
11520 (concat prefix
11521 (if prefix (or separator "/"))
11522 (mapconcat
11523 (lambda (h)
11524 (setq n (1+ n))
11525 (if (and (= n nsteps) (< maxwidth 10000))
11526 (setq maxwidth (- total-width total)))
11527 (if (< (length h) maxwidth)
11528 (progn (setq total (+ total (length h) 1)) h)
11529 (setq h (substring h 0 (- maxwidth 2))
11530 total (+ total maxwidth 1))
11531 (if (string-match "[ \t]+\\'" h)
11532 (setq h (substring h 0 (match-beginning 0))))
11533 (setq h (concat h "..")))
11534 (org-add-props h nil 'face
11535 (nth (% (1- n) org-n-level-faces)
11536 org-level-faces))
11538 path (or separator "/"))))))
11540 (defun org-display-outline-path (&optional file current separator just-return-string)
11541 "Display the current outline path in the echo area.
11543 If FILE is non-nil, prepend the output with the file name.
11544 If CURRENT is non-nil, append the current heading to the output.
11545 SEPARATOR is passed through to `org-format-outline-path'. It separates
11546 the different parts of the path and defaults to \"/\".
11547 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11548 (interactive "P")
11549 (let* (case-fold-search
11550 (bfn (buffer-file-name (buffer-base-buffer)))
11551 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11552 res)
11553 (if current (setq path (append path
11554 (save-excursion
11555 (org-back-to-heading t)
11556 (if (looking-at org-complex-heading-regexp)
11557 (list (match-string 4)))))))
11558 (setq res
11559 (org-format-outline-path
11560 path
11561 (1- (frame-width))
11562 (and file bfn (concat (file-name-nondirectory bfn) separator))
11563 separator))
11564 (if just-return-string
11565 (org-no-properties res)
11566 (org-unlogged-message "%s" res))))
11568 (defvar org-refile-history nil
11569 "History for refiling operations.")
11571 (defvar org-after-refile-insert-hook nil
11572 "Hook run after `org-refile' has inserted its stuff at the new location.
11573 Note that this is still *before* the stuff will be removed from
11574 the *old* location.")
11576 (defvar org-capture-last-stored-marker)
11577 (defvar org-refile-keep nil
11578 "Non-nil means `org-refile' will copy instead of refile.")
11580 (defun org-copy ()
11581 "Like `org-refile', but copy."
11582 (interactive)
11583 (let ((org-refile-keep t))
11584 (funcall 'org-refile nil nil nil "Copy")))
11586 (defun org-refile (&optional goto default-buffer rfloc msg)
11587 "Move the entry or entries at point to another heading.
11588 The list of target headings is compiled using the information in
11589 `org-refile-targets', which see.
11591 At the target location, the entry is filed as a subitem of the target
11592 heading. Depending on `org-reverse-note-order', the new subitem will
11593 either be the first or the last subitem.
11595 If there is an active region, all entries in that region will be moved.
11596 However, the region must fulfill the requirement that the first heading
11597 is the first one sets the top-level of the moved text - at most siblings
11598 below it are allowed.
11600 With prefix arg GOTO, the command will only visit the target location
11601 and not actually move anything.
11603 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11604 go to the location where the last refiling operation has put the subtree.
11606 With a numeric prefix argument of `2', refile to the running clock.
11608 With a numeric prefix argument of `3', emulate `org-refile-keep'
11609 being set to `t' and copy to the target location, don't move it.
11610 Beware that keeping refiled entries may result in duplicated ID
11611 properties.
11613 RFLOC can be a refile location obtained in a different way.
11615 MSG is a string to replace \"Refile\" in the default prompt with
11616 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11618 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11620 If you are using target caching (see `org-refile-use-cache'),
11621 you have to clear the target cache in order to find new targets.
11622 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11623 prefix argument (`C-u C-u C-u C-c C-w')."
11625 (interactive "P")
11626 (if (member goto '(0 (64)))
11627 (org-refile-cache-clear)
11628 (let* ((actionmsg (or msg "Refile"))
11629 (cbuf (current-buffer))
11630 (regionp (org-region-active-p))
11631 (region-start (and regionp (region-beginning)))
11632 (region-end (and regionp (region-end)))
11633 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11634 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11635 pos it nbuf file re level reversed)
11636 (setq last-command nil)
11637 (when regionp
11638 (goto-char region-start)
11639 (or (bolp) (goto-char (point-at-bol)))
11640 (setq region-start (point))
11641 (unless (or (org-kill-is-subtree-p
11642 (buffer-substring region-start region-end))
11643 (prog1 org-refile-active-region-within-subtree
11644 (let ((s (point-at-eol)))
11645 (org-toggle-heading)
11646 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11647 (user-error "The region is not a (sequence of) subtree(s)")))
11648 (if (equal goto '(16))
11649 (org-refile-goto-last-stored)
11650 (when (or
11651 (and (equal goto 2)
11652 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11653 (prog1
11654 (setq it (list (or org-clock-heading "running clock")
11655 (buffer-file-name
11656 (marker-buffer org-clock-hd-marker))
11658 (marker-position org-clock-hd-marker)))
11659 (setq goto nil)))
11660 (setq it (or rfloc
11661 (let (heading-text)
11662 (save-excursion
11663 (unless goto
11664 (org-back-to-heading t)
11665 (setq heading-text
11666 (nth 4 (org-heading-components))))
11668 (org-refile-get-location
11669 (cond (goto "Goto")
11670 (regionp (concat actionmsg " region to"))
11671 (t (concat actionmsg " subtree \""
11672 heading-text "\" to")))
11673 default-buffer
11674 (and (not (equal '(4) goto))
11675 org-refile-allow-creating-parent-nodes)
11676 goto))))))
11677 (setq file (nth 1 it)
11678 re (nth 2 it)
11679 pos (nth 3 it))
11680 (if (and (not goto)
11682 (equal (buffer-file-name) file)
11683 (if regionp
11684 (and (>= pos region-start)
11685 (<= pos region-end))
11686 (and (>= pos (point))
11687 (< pos (save-excursion
11688 (org-end-of-subtree t t))))))
11689 (error "Cannot refile to position inside the tree or region"))
11691 (setq nbuf (or (find-buffer-visiting file)
11692 (find-file-noselect file)))
11693 (if (and goto (not (equal goto 3)))
11694 (progn
11695 (org-pop-to-buffer-same-window nbuf)
11696 (goto-char pos)
11697 (org-show-context 'org-goto))
11698 (if regionp
11699 (progn
11700 (org-kill-new (buffer-substring region-start region-end))
11701 (org-save-markers-in-region region-start region-end))
11702 (org-copy-subtree 1 nil t))
11703 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11704 (find-file-noselect file)))
11705 (setq reversed (org-notes-order-reversed-p))
11706 (save-excursion
11707 (save-restriction
11708 (widen)
11709 (if pos
11710 (progn
11711 (goto-char pos)
11712 (looking-at org-outline-regexp)
11713 (setq level (org-get-valid-level (funcall outline-level) 1))
11714 (goto-char
11715 (if reversed
11716 (or (outline-next-heading) (point-max))
11717 (or (save-excursion (org-get-next-sibling))
11718 (org-end-of-subtree t t)
11719 (point-max)))))
11720 (setq level 1)
11721 (if (not reversed)
11722 (goto-char (point-max))
11723 (goto-char (point-min))
11724 (or (outline-next-heading) (goto-char (point-max)))))
11725 (if (not (bolp)) (newline))
11726 (org-paste-subtree level)
11727 (when org-log-refile
11728 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11729 (unless (eq org-log-refile 'note)
11730 (save-excursion (org-add-log-note))))
11731 (and org-auto-align-tags
11732 (let ((org-loop-over-headlines-in-active-region nil))
11733 (org-set-tags nil t)))
11734 (let ((bookmark-name (plist-get org-bookmark-names-plist
11735 :last-refile)))
11736 (when bookmark-name
11737 (with-demoted-errors
11738 (bookmark-set bookmark-name))))
11739 ;; If we are refiling for capture, make sure that the
11740 ;; last-capture pointers point here
11741 (when (org-bound-and-true-p org-refile-for-capture)
11742 (let ((bookmark-name (plist-get org-bookmark-names-plist
11743 :last-capture-marker)))
11744 (when bookmark-name
11745 (with-demoted-errors
11746 (bookmark-set bookmark-name))))
11747 (move-marker org-capture-last-stored-marker (point)))
11748 (if (fboundp 'deactivate-mark) (deactivate-mark))
11749 (run-hooks 'org-after-refile-insert-hook))))
11750 (unless org-refile-keep
11751 (if regionp
11752 (delete-region (point) (+ (point) (- region-end region-start)))
11753 (delete-region
11754 (and (org-back-to-heading t) (point))
11755 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11756 (when (featurep 'org-inlinetask)
11757 (org-inlinetask-remove-END-maybe))
11758 (setq org-markers-to-move nil)
11759 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11761 (defun org-refile-goto-last-stored ()
11762 "Go to the location where the last refile was stored."
11763 (interactive)
11764 (bookmark-jump "org-refile-last-stored")
11765 (message "This is the location of the last refile"))
11767 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11768 no-exclude)
11769 "Prompt the user for a refile location, using PROMPT.
11770 PROMPT should not be suffixed with a colon and a space, because
11771 this function appends the default value from
11772 `org-refile-history' automatically, if that is not empty.
11773 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11774 this is used for the GOTO interface."
11775 (let ((org-refile-targets org-refile-targets)
11776 (org-refile-use-outline-path org-refile-use-outline-path)
11777 excluded-entries)
11778 (when (and (derived-mode-p 'org-mode)
11779 (not org-refile-use-cache)
11780 (not no-exclude))
11781 (org-map-tree
11782 (lambda()
11783 (setq excluded-entries
11784 (append excluded-entries (list (org-get-heading t t)))))))
11785 (setq org-refile-target-table
11786 (org-refile-get-targets default-buffer excluded-entries)))
11787 (unless org-refile-target-table
11788 (user-error "No refile targets"))
11789 (let* ((cbuf (current-buffer))
11790 (partial-completion-mode nil)
11791 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11792 (cfunc (if (and org-refile-use-outline-path
11793 org-outline-path-complete-in-steps)
11794 'org-olpath-completing-read
11795 'org-icompleting-read))
11796 (extra (if org-refile-use-outline-path "/" ""))
11797 (cbnex (concat (buffer-name) extra))
11798 (filename (and cfn (expand-file-name cfn)))
11799 (tbl (mapcar
11800 (lambda (x)
11801 (if (and (not (member org-refile-use-outline-path
11802 '(file full-file-path)))
11803 (not (equal filename (nth 1 x))))
11804 (cons (concat (car x) extra " ("
11805 (file-name-nondirectory (nth 1 x)) ")")
11806 (cdr x))
11807 (cons (concat (car x) extra) (cdr x))))
11808 org-refile-target-table))
11809 (completion-ignore-case t)
11810 cdef
11811 (prompt (concat prompt
11812 (or (and (car org-refile-history)
11813 (concat " (default " (car org-refile-history) ")"))
11814 (and (assoc cbnex tbl) (setq cdef cbnex)
11815 (concat " (default " cbnex ")"))) ": "))
11816 pa answ parent-target child parent old-hist)
11817 (setq old-hist org-refile-history)
11818 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11819 nil 'org-refile-history (or cdef (car org-refile-history))))
11820 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11821 (if pa
11822 (progn
11823 (org-refile-check-position pa)
11824 (when (or (not org-refile-history)
11825 (not (eq old-hist org-refile-history))
11826 (not (equal (car pa) (car org-refile-history))))
11827 (setq org-refile-history
11828 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11829 org-refile-history
11830 (cdr org-refile-history))))
11831 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11832 (pop org-refile-history)))
11834 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11835 (progn
11836 (setq parent (match-string 1 answ)
11837 child (match-string 2 answ))
11838 (setq parent-target (or (assoc parent tbl)
11839 (assoc (concat parent "/") tbl)))
11840 (when (and parent-target
11841 (or (eq new-nodes t)
11842 (and (eq new-nodes 'confirm)
11843 (y-or-n-p (format "Create new node \"%s\"? "
11844 child)))))
11845 (org-refile-new-child parent-target child)))
11846 (user-error "Invalid target location")))))
11848 (declare-function org-string-nw-p "org-macs" (s))
11849 (defun org-refile-check-position (refile-pointer)
11850 "Check if the refile pointer matches the headline to which it points."
11851 (let* ((file (nth 1 refile-pointer))
11852 (re (nth 2 refile-pointer))
11853 (pos (nth 3 refile-pointer))
11854 buffer)
11855 (if (and (not (markerp pos)) (not file))
11856 (if file
11857 (user-error "Please save the buffer to a file before refiling")
11858 (user-error "Please indicate a target file in the refile path"))
11859 (when (org-string-nw-p re)
11860 (setq buffer (if (markerp pos)
11861 (marker-buffer pos)
11862 (or (find-buffer-visiting file)
11863 (find-file-noselect file))))
11864 (with-current-buffer buffer
11865 (save-excursion
11866 (save-restriction
11867 (widen)
11868 (goto-char pos)
11869 (beginning-of-line 1)
11870 (unless (org-looking-at-p re)
11871 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11873 (defun org-refile-new-child (parent-target child)
11874 "Use refile target PARENT-TARGET to add new CHILD below it."
11875 (unless parent-target
11876 (error "Cannot find parent for new node"))
11877 (let ((file (nth 1 parent-target))
11878 (pos (nth 3 parent-target))
11879 level)
11880 (with-current-buffer (or (find-buffer-visiting file)
11881 (find-file-noselect file))
11882 (save-excursion
11883 (save-restriction
11884 (widen)
11885 (if pos
11886 (goto-char pos)
11887 (goto-char (point-max))
11888 (if (not (bolp)) (newline)))
11889 (when (looking-at org-outline-regexp)
11890 (setq level (funcall outline-level))
11891 (org-end-of-subtree t t))
11892 (org-back-over-empty-lines)
11893 (insert "\n" (make-string
11894 (if pos (org-get-valid-level level 1) 1) ?*)
11895 " " child "\n")
11896 (beginning-of-line 0)
11897 (list (concat (car parent-target) "/" child) file "" (point)))))))
11899 (defun org-olpath-completing-read (prompt collection &rest args)
11900 "Read an outline path like a file name."
11901 (let ((thetable collection)
11902 (org-completion-use-ido nil) ; does not work with ido.
11903 (org-completion-use-iswitchb nil)) ; or iswitchb
11904 (apply
11905 'org-icompleting-read prompt
11906 (lambda (string predicate &optional flag)
11907 (let (rtn r f (l (length string)))
11908 (cond
11909 ((eq flag nil)
11910 ;; try completion
11911 (try-completion string thetable))
11912 ((eq flag t)
11913 ;; all-completions
11914 (setq rtn (all-completions string thetable predicate))
11915 (mapcar
11916 (lambda (x)
11917 (setq r (substring x l))
11918 (if (string-match " ([^)]*)$" x)
11919 (setq f (match-string 0 x))
11920 (setq f ""))
11921 (if (string-match "/" r)
11922 (concat string (substring r 0 (match-end 0)) f)
11924 rtn))
11925 ((eq flag 'lambda)
11926 ;; exact match?
11927 (assoc string thetable)))))
11928 args)))
11930 ;;;; Dynamic blocks
11932 (defun org-find-dblock (name)
11933 "Find the first dynamic block with name NAME in the buffer.
11934 If not found, stay at current position and return nil."
11935 (let ((case-fold-search t) pos)
11936 (save-excursion
11937 (goto-char (point-min))
11938 (setq pos (and (re-search-forward
11939 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11940 (match-beginning 0))))
11941 (if pos (goto-char pos))
11942 pos))
11944 (defun org-create-dblock (plist)
11945 "Create a dynamic block section, with parameters taken from PLIST.
11946 PLIST must contain a :name entry which is used as name of the block."
11947 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11948 (end-of-line 1)
11949 (newline))
11950 (let ((col (current-column))
11951 (name (plist-get plist :name)))
11952 (insert "#+BEGIN: " name)
11953 (while plist
11954 (if (eq (car plist) :name)
11955 (setq plist (cddr plist))
11956 (insert " " (prin1-to-string (pop plist)))))
11957 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11958 (beginning-of-line -2)))
11960 (defun org-prepare-dblock ()
11961 "Prepare dynamic block for refresh.
11962 This empties the block, puts the cursor at the insert position and returns
11963 the property list including an extra property :name with the block name."
11964 (unless (looking-at org-dblock-start-re)
11965 (user-error "Not at a dynamic block"))
11966 (let* ((begdel (1+ (match-end 0)))
11967 (name (org-no-properties (match-string 1)))
11968 (params (append (list :name name)
11969 (read (concat "(" (match-string 3) ")")))))
11970 (save-excursion
11971 (beginning-of-line 1)
11972 (skip-chars-forward " \t")
11973 (setq params (plist-put params :indentation-column (current-column))))
11974 (unless (re-search-forward org-dblock-end-re nil t)
11975 (error "Dynamic block not terminated"))
11976 (setq params
11977 (append params
11978 (list :content (buffer-substring
11979 begdel (match-beginning 0)))))
11980 (delete-region begdel (match-beginning 0))
11981 (goto-char begdel)
11982 (open-line 1)
11983 params))
11985 (defun org-map-dblocks (&optional command)
11986 "Apply COMMAND to all dynamic blocks in the current buffer.
11987 If COMMAND is not given, use `org-update-dblock'."
11988 (let ((cmd (or command 'org-update-dblock)))
11989 (save-excursion
11990 (goto-char (point-min))
11991 (while (re-search-forward org-dblock-start-re nil t)
11992 (goto-char (match-beginning 0))
11993 (save-excursion
11994 (condition-case nil
11995 (funcall cmd)
11996 (error (message "Error during update of dynamic block"))))
11997 (unless (re-search-forward org-dblock-end-re nil t)
11998 (error "Dynamic block not terminated"))))))
12000 (defun org-dblock-update (&optional arg)
12001 "User command for updating dynamic blocks.
12002 Update the dynamic block at point. With prefix ARG, update all dynamic
12003 blocks in the buffer."
12004 (interactive "P")
12005 (if arg
12006 (org-update-all-dblocks)
12007 (or (looking-at org-dblock-start-re)
12008 (org-beginning-of-dblock))
12009 (org-update-dblock)))
12011 (defun org-update-dblock ()
12012 "Update the dynamic block at point.
12013 This means to empty the block, parse for parameters and then call
12014 the correct writing function."
12015 (interactive)
12016 (save-window-excursion
12017 (let* ((pos (point))
12018 (line (org-current-line))
12019 (params (org-prepare-dblock))
12020 (name (plist-get params :name))
12021 (indent (plist-get params :indentation-column))
12022 (cmd (intern (concat "org-dblock-write:" name))))
12023 (message "Updating dynamic block `%s' at line %d..." name line)
12024 (funcall cmd params)
12025 (message "Updating dynamic block `%s' at line %d...done" name line)
12026 (goto-char pos)
12027 (when (and indent (> indent 0))
12028 (setq indent (make-string indent ?\ ))
12029 (save-excursion
12030 (org-beginning-of-dblock)
12031 (forward-line 1)
12032 (while (not (looking-at org-dblock-end-re))
12033 (insert indent)
12034 (beginning-of-line 2))
12035 (when (looking-at org-dblock-end-re)
12036 (and (looking-at "[ \t]+")
12037 (replace-match ""))
12038 (insert indent)))))))
12040 (defun org-beginning-of-dblock ()
12041 "Find the beginning of the dynamic block at point.
12042 Error if there is no such block at point."
12043 (let ((pos (point))
12044 beg)
12045 (end-of-line 1)
12046 (if (and (re-search-backward org-dblock-start-re nil t)
12047 (setq beg (match-beginning 0))
12048 (re-search-forward org-dblock-end-re nil t)
12049 (> (match-end 0) pos))
12050 (goto-char beg)
12051 (goto-char pos)
12052 (error "Not in a dynamic block"))))
12054 (defun org-update-all-dblocks ()
12055 "Update all dynamic blocks in the buffer.
12056 This function can be used in a hook."
12057 (interactive)
12058 (when (derived-mode-p 'org-mode)
12059 (org-map-dblocks 'org-update-dblock)))
12062 ;;;; Completion
12064 (declare-function org-export-backend-name "org-export" (cl-x))
12065 (declare-function org-export-backend-options "org-export" (cl-x))
12066 (defun org-get-export-keywords ()
12067 "Return a list of all currently understood export keywords.
12068 Export keywords include options, block names, attributes and
12069 keywords relative to each registered export back-end."
12070 (let (keywords)
12071 (dolist (backend
12072 (org-bound-and-true-p org-export--registered-backends)
12073 (delq nil keywords))
12074 ;; Back-end name (for keywords, like #+LATEX:)
12075 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12076 (dolist (option-entry (org-export-backend-options backend))
12077 ;; Back-end options.
12078 (push (nth 1 option-entry) keywords)))))
12080 (defconst org-options-keywords
12081 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12082 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12083 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12084 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12085 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12087 (defcustom org-structure-template-alist
12088 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12089 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12090 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12091 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12092 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12093 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12094 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12095 "<literal style=\"latex\">\n?\n</literal>")
12096 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12097 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12098 "<literal style=\"html\">\n?\n</literal>")
12099 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12100 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12101 ("A" "#+ASCII: " "")
12102 ("i" "#+INDEX: ?" "#+INDEX: ?")
12103 ("I" "#+INCLUDE: %file ?"
12104 "<include file=%file markup=\"?\">"))
12105 "Structure completion elements.
12106 This is a list of abbreviation keys and values. The value gets inserted
12107 if you type `<' followed by the key and then press the completion key,
12108 usually `M-TAB'. %file will be replaced by a file name after prompting
12109 for the file using completion. The cursor will be placed at the position
12110 of the `?` in the template.
12111 There are two templates for each key, the first uses the original Org syntax,
12112 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12113 the default when the /org-mtags.el/ module has been loaded. See also the
12114 variable `org-mtags-prefer-muse-templates'."
12115 :group 'org-completion
12116 :type '(repeat
12117 (list
12118 (string :tag "Key")
12119 (string :tag "Template")
12120 (string :tag "Muse Template"))))
12122 (defun org-try-structure-completion ()
12123 "Try to complete a structure template before point.
12124 This looks for strings like \"<e\" on an otherwise empty line and
12125 expands them."
12126 (let ((l (buffer-substring (point-at-bol) (point)))
12128 (when (and (looking-at "[ \t]*$")
12129 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12130 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12131 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12132 (match-beginning 1)) a)
12133 t)))
12135 (defun org-complete-expand-structure-template (start cell)
12136 "Expand a structure template."
12137 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12138 (rpl (nth (if musep 2 1) cell))
12139 (ind ""))
12140 (delete-region start (point))
12141 (when (string-match "\\`#\\+" rpl)
12142 (cond
12143 ((bolp))
12144 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12145 (setq ind (buffer-substring (point-at-bol) (point))))
12146 (t (newline))))
12147 (setq start (point))
12148 (if (string-match "%file" rpl)
12149 (setq rpl (replace-match
12150 (concat
12151 "\""
12152 (save-match-data
12153 (abbreviate-file-name (read-file-name "Include file: ")))
12154 "\"")
12155 t t rpl)))
12156 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12157 (concat "\n" ind)))
12158 (insert rpl)
12159 (if (re-search-backward "\\?" start t) (delete-char 1))))
12161 ;;;; TODO, DEADLINE, Comments
12163 (defun org-toggle-comment ()
12164 "Change the COMMENT state of an entry."
12165 (interactive)
12166 (save-excursion
12167 (org-back-to-heading)
12168 (let (case-fold-search)
12169 (cond
12170 ((looking-at (format org-heading-keyword-regexp-format
12171 org-comment-string))
12172 (goto-char (match-end 1))
12173 (looking-at (concat " +" org-comment-string))
12174 (replace-match "" t t)
12175 (when (eolp) (insert " ")))
12176 ((looking-at org-outline-regexp)
12177 (goto-char (match-end 0))
12178 (insert org-comment-string " "))))))
12180 (defvar org-last-todo-state-is-todo nil
12181 "This is non-nil when the last TODO state change led to a TODO state.
12182 If the last change removed the TODO tag or switched to DONE, then
12183 this is nil.")
12185 (defvar org-setting-tags nil) ; dynamically skipped
12187 (defvar org-todo-setup-filter-hook nil
12188 "Hook for functions that pre-filter todo specs.
12189 Each function takes a todo spec and returns either nil or the spec
12190 transformed into canonical form." )
12192 (defvar org-todo-get-default-hook nil
12193 "Hook for functions that get a default item for todo.
12194 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12195 nil or a string to be used for the todo mark." )
12197 (defvar org-agenda-headline-snapshot-before-repeat)
12199 (defun org-current-effective-time ()
12200 "Return current time adjusted for `org-extend-today-until' variable."
12201 (let* ((ct (org-current-time))
12202 (dct (decode-time ct))
12203 (ct1
12204 (cond
12205 (org-use-last-clock-out-time-as-effective-time
12206 (or (org-clock-get-last-clock-out-time) ct))
12207 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12208 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12209 (t ct))))
12210 ct1))
12212 (defun org-todo-yesterday (&optional arg)
12213 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12214 (interactive "P")
12215 (if (eq major-mode 'org-agenda-mode)
12216 (apply 'org-agenda-todo-yesterday arg)
12217 (let* ((hour (third (decode-time
12218 (org-current-time))))
12219 (org-extend-today-until (1+ hour)))
12220 (org-todo arg))))
12222 (defvar org-block-entry-blocking ""
12223 "First entry preventing the TODO state change.")
12225 (defun org-cancel-repeater ()
12226 "Cancel a repeater by setting its numeric value to zero."
12227 (interactive)
12228 (save-excursion
12229 (org-back-to-heading t)
12230 (let ((bound1 (point))
12231 (bound0 (save-excursion (outline-next-heading) (point))))
12232 (when (re-search-forward
12233 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12234 org-deadline-time-regexp "\\)\\|\\("
12235 org-ts-regexp "\\)")
12236 bound0 t)
12237 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12238 (replace-match "0" t nil nil 1))))))
12240 (defun org-todo (&optional arg)
12241 "Change the TODO state of an item.
12242 The state of an item is given by a keyword at the start of the heading,
12243 like
12244 *** TODO Write paper
12245 *** DONE Call mom
12247 The different keywords are specified in the variable `org-todo-keywords'.
12248 By default the available states are \"TODO\" and \"DONE\".
12249 So for this example: when the item starts with TODO, it is changed to DONE.
12250 When it starts with DONE, the DONE is removed. And when neither TODO nor
12251 DONE are present, add TODO at the beginning of the heading.
12253 With \\[universal-argument] prefix arg, use completion to determine the new \
12254 state.
12255 With numeric prefix arg, switch to that state.
12256 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12257 keywords (nextset).
12258 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12259 With a numeric prefix arg of 0, inhibit note taking for the change.
12260 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12262 When called through ELisp, arg is also interpreted in the following way:
12263 'none -> empty state
12264 \"\"(empty string) -> switch to empty state
12265 'done -> switch to DONE
12266 'nextset -> switch to the next set of keywords
12267 'previousset -> switch to the previous set of keywords
12268 \"WAITING\" -> switch to the specified keyword, but only if it
12269 really is a member of `org-todo-keywords'."
12270 (interactive "P")
12271 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12272 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12273 'region-start-level 'region))
12274 org-loop-over-headlines-in-active-region)
12275 (org-map-entries
12276 `(org-todo ,arg)
12277 org-loop-over-headlines-in-active-region
12278 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12279 (if (equal arg '(16)) (setq arg 'nextset))
12280 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12281 (let ((org-blocker-hook org-blocker-hook)
12282 commentp
12283 case-fold-search)
12284 (when (equal arg '(64))
12285 (setq arg nil org-blocker-hook nil))
12286 (when (and org-blocker-hook
12287 (or org-inhibit-blocking
12288 (org-entry-get nil "NOBLOCKING")))
12289 (setq org-blocker-hook nil))
12290 (save-excursion
12291 (catch 'exit
12292 (org-back-to-heading t)
12293 (when (looking-at (concat "^\\*+ " org-comment-string))
12294 (org-toggle-comment)
12295 (setq commentp t))
12296 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12297 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12298 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12299 (let* ((match-data (match-data))
12300 (startpos (point-at-bol))
12301 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12302 (org-log-done org-log-done)
12303 (org-log-repeat org-log-repeat)
12304 (org-todo-log-states org-todo-log-states)
12305 (org-inhibit-logging
12306 (if (equal arg 0)
12307 (progn (setq arg nil) 'note) org-inhibit-logging))
12308 (this (match-string 1))
12309 (hl-pos (match-beginning 0))
12310 (head (org-get-todo-sequence-head this))
12311 (ass (assoc head org-todo-kwd-alist))
12312 (interpret (nth 1 ass))
12313 (done-word (nth 3 ass))
12314 (final-done-word (nth 4 ass))
12315 (org-last-state (or this ""))
12316 (completion-ignore-case t)
12317 (member (member this org-todo-keywords-1))
12318 (tail (cdr member))
12319 (org-state (cond
12320 ((and org-todo-key-trigger
12321 (or (and (equal arg '(4))
12322 (eq org-use-fast-todo-selection 'prefix))
12323 (and (not arg) org-use-fast-todo-selection
12324 (not (eq org-use-fast-todo-selection
12325 'prefix)))))
12326 ;; Use fast selection
12327 (org-fast-todo-selection))
12328 ((and (equal arg '(4))
12329 (or (not org-use-fast-todo-selection)
12330 (not org-todo-key-trigger)))
12331 ;; Read a state with completion
12332 (org-icompleting-read
12333 "State: " (mapcar 'list org-todo-keywords-1)
12334 nil t))
12335 ((eq arg 'right)
12336 (if this
12337 (if tail (car tail) nil)
12338 (car org-todo-keywords-1)))
12339 ((eq arg 'left)
12340 (if (equal member org-todo-keywords-1)
12342 (if this
12343 (nth (- (length org-todo-keywords-1)
12344 (length tail) 2)
12345 org-todo-keywords-1)
12346 (org-last org-todo-keywords-1))))
12347 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12348 (setq arg nil))) ; hack to fall back to cycling
12349 (arg
12350 ;; user or caller requests a specific state
12351 (cond
12352 ((equal arg "") nil)
12353 ((eq arg 'none) nil)
12354 ((eq arg 'done) (or done-word (car org-done-keywords)))
12355 ((eq arg 'nextset)
12356 (or (car (cdr (member head org-todo-heads)))
12357 (car org-todo-heads)))
12358 ((eq arg 'previousset)
12359 (let ((org-todo-heads (reverse org-todo-heads)))
12360 (or (car (cdr (member head org-todo-heads)))
12361 (car org-todo-heads))))
12362 ((car (member arg org-todo-keywords-1)))
12363 ((stringp arg)
12364 (user-error "State `%s' not valid in this file" arg))
12365 ((nth (1- (prefix-numeric-value arg))
12366 org-todo-keywords-1))))
12367 ((null member) (or head (car org-todo-keywords-1)))
12368 ((equal this final-done-word) nil) ;; -> make empty
12369 ((null tail) nil) ;; -> first entry
12370 ((memq interpret '(type priority))
12371 (if (eq this-command last-command)
12372 (car tail)
12373 (if (> (length tail) 0)
12374 (or done-word (car org-done-keywords))
12375 nil)))
12377 (car tail))))
12378 (org-state (or
12379 (run-hook-with-args-until-success
12380 'org-todo-get-default-hook org-state org-last-state)
12381 org-state))
12382 (next (if org-state (concat " " org-state " ") " "))
12383 (change-plist (list :type 'todo-state-change :from this :to org-state
12384 :position startpos))
12385 dolog now-done-p)
12386 (when org-blocker-hook
12387 (setq org-last-todo-state-is-todo
12388 (not (member this org-done-keywords)))
12389 (unless (save-excursion
12390 (save-match-data
12391 (org-with-wide-buffer
12392 (run-hook-with-args-until-failure
12393 'org-blocker-hook change-plist))))
12394 (if (org-called-interactively-p 'interactive)
12395 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12396 this org-state org-block-entry-blocking)
12397 ;; fail silently
12398 (message "TODO state change from %s to %s blocked (by \"%s\")"
12399 this org-state org-block-entry-blocking)
12400 (throw 'exit nil))))
12401 (store-match-data match-data)
12402 (replace-match next t t)
12403 (unless (pos-visible-in-window-p hl-pos)
12404 (message "TODO state changed to %s" (org-trim next)))
12405 (unless head
12406 (setq head (org-get-todo-sequence-head org-state)
12407 ass (assoc head org-todo-kwd-alist)
12408 interpret (nth 1 ass)
12409 done-word (nth 3 ass)
12410 final-done-word (nth 4 ass)))
12411 (when (memq arg '(nextset previousset))
12412 (message "Keyword-Set %d/%d: %s"
12413 (- (length org-todo-sets) -1
12414 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12415 (length org-todo-sets)
12416 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12417 (setq org-last-todo-state-is-todo
12418 (not (member org-state org-done-keywords)))
12419 (setq now-done-p (and (member org-state org-done-keywords)
12420 (not (member this org-done-keywords))))
12421 (and logging (org-local-logging logging))
12422 (when (and (or org-todo-log-states org-log-done)
12423 (not (eq org-inhibit-logging t))
12424 (not (memq arg '(nextset previousset))))
12425 ;; we need to look at recording a time and note
12426 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12427 (nth 2 (assoc this org-todo-log-states))))
12428 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12429 (setq dolog 'time))
12430 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12431 (and org-state
12432 (member org-state org-not-done-keywords)
12433 (not (member this org-not-done-keywords))))
12434 ;; This is now a todo state and was not one before
12435 ;; If there was a CLOSED time stamp, get rid of it.
12436 (org-add-planning-info nil nil 'closed))
12437 (when (and now-done-p org-log-done)
12438 ;; It is now done, and it was not done before
12439 (org-add-planning-info 'closed (org-current-effective-time))
12440 (if (and (not dolog) (eq 'note org-log-done))
12441 (org-add-log-setup 'done org-state this 'findpos 'note)))
12442 (when (and org-state dolog)
12443 ;; This is a non-nil state, and we need to log it
12444 (org-add-log-setup 'state org-state this 'findpos dolog)))
12445 ;; Fixup tag positioning
12446 (org-todo-trigger-tag-changes org-state)
12447 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12448 (when org-provide-todo-statistics
12449 (org-update-parent-todo-statistics))
12450 (run-hooks 'org-after-todo-state-change-hook)
12451 (if (and arg (not (member org-state org-done-keywords)))
12452 (setq head (org-get-todo-sequence-head org-state)))
12453 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12454 ;; Do we need to trigger a repeat?
12455 (when now-done-p
12456 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12457 ;; This is for the agenda, take a snapshot of the headline.
12458 (save-match-data
12459 (setq org-agenda-headline-snapshot-before-repeat
12460 (org-get-heading))))
12461 (org-auto-repeat-maybe org-state))
12462 ;; Fixup cursor location if close to the keyword
12463 (if (and (outline-on-heading-p)
12464 (not (bolp))
12465 (save-excursion (beginning-of-line 1)
12466 (looking-at org-todo-line-regexp))
12467 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12468 (progn
12469 (goto-char (or (match-end 2) (match-end 1)))
12470 (and (looking-at " ") (just-one-space))))
12471 (when org-trigger-hook
12472 (save-excursion
12473 (run-hook-with-args 'org-trigger-hook change-plist)))
12474 (when commentp (org-toggle-comment))))))))
12476 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12477 "Block turning an entry into a TODO, using the hierarchy.
12478 This checks whether the current task should be blocked from state
12479 changes. Such blocking occurs when:
12481 1. The task has children which are not all in a completed state.
12483 2. A task has a parent with the property :ORDERED:, and there
12484 are siblings prior to the current task with incomplete
12485 status.
12487 3. The parent of the task is blocked because it has siblings that should
12488 be done first, or is child of a block grandparent TODO entry."
12490 (if (not org-enforce-todo-dependencies)
12491 t ; if locally turned off don't block
12492 (catch 'dont-block
12493 ;; If this is not a todo state change, or if this entry is already DONE,
12494 ;; do not block
12495 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12496 (member (plist-get change-plist :from)
12497 (cons 'done org-done-keywords))
12498 (member (plist-get change-plist :to)
12499 (cons 'todo org-not-done-keywords))
12500 (not (plist-get change-plist :to)))
12501 (throw 'dont-block t))
12502 ;; If this task has children, and any are undone, it's blocked
12503 (save-excursion
12504 (org-back-to-heading t)
12505 (let ((this-level (funcall outline-level)))
12506 (outline-next-heading)
12507 (let ((child-level (funcall outline-level)))
12508 (while (and (not (eobp))
12509 (> child-level this-level))
12510 ;; this todo has children, check whether they are all
12511 ;; completed
12512 (if (and (not (org-entry-is-done-p))
12513 (org-entry-is-todo-p))
12514 (progn (setq org-block-entry-blocking (org-get-heading))
12515 (throw 'dont-block nil)))
12516 (outline-next-heading)
12517 (setq child-level (funcall outline-level))))))
12518 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12519 ;; any previous siblings are undone, it's blocked
12520 (save-excursion
12521 (org-back-to-heading t)
12522 (let* ((pos (point))
12523 (parent-pos (and (org-up-heading-safe) (point))))
12524 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12525 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12526 (forward-line 1)
12527 (re-search-forward org-not-done-heading-regexp pos t))
12528 (setq org-block-entry-blocking (match-string 0))
12529 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12530 ;; Search further up the hierarchy, to see if an ancestor is blocked
12531 (while t
12532 (goto-char parent-pos)
12533 (if (not (looking-at org-not-done-heading-regexp))
12534 (throw 'dont-block t)) ; do not block, parent is not a TODO
12535 (setq pos (point))
12536 (setq parent-pos (and (org-up-heading-safe) (point)))
12537 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12538 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12539 (forward-line 1)
12540 (re-search-forward org-not-done-heading-regexp pos t)
12541 (setq org-block-entry-blocking (org-get-heading)))
12542 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12544 (defcustom org-track-ordered-property-with-tag nil
12545 "Should the ORDERED property also be shown as a tag?
12546 The ORDERED property decides if an entry should require subtasks to be
12547 completed in sequence. Since a property is not very visible, setting
12548 this option means that toggling the ORDERED property with the command
12549 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12550 not relevant for the behavior, but it makes things more visible.
12552 Note that toggling the tag with tags commands will not change the property
12553 and therefore not influence behavior!
12555 This can be t, meaning the tag ORDERED should be used, It can also be a
12556 string to select a different tag for this task."
12557 :group 'org-todo
12558 :type '(choice
12559 (const :tag "No tracking" nil)
12560 (const :tag "Track with ORDERED tag" t)
12561 (string :tag "Use other tag")))
12563 (defun org-toggle-ordered-property ()
12564 "Toggle the ORDERED property of the current entry.
12565 For better visibility, you can track the value of this property with a tag.
12566 See variable `org-track-ordered-property-with-tag'."
12567 (interactive)
12568 (let* ((t1 org-track-ordered-property-with-tag)
12569 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12570 (save-excursion
12571 (org-back-to-heading)
12572 (if (org-entry-get nil "ORDERED")
12573 (progn
12574 (org-delete-property "ORDERED")
12575 (and tag (org-toggle-tag tag 'off))
12576 (message "Subtasks can be completed in arbitrary order"))
12577 (org-entry-put nil "ORDERED" "t")
12578 (and tag (org-toggle-tag tag 'on))
12579 (message "Subtasks must be completed in sequence")))))
12581 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12582 (defun org-block-todo-from-checkboxes (change-plist)
12583 "Block turning an entry into a TODO, using checkboxes.
12584 This checks whether the current task should be blocked from state
12585 changes because there are unchecked boxes in this entry."
12586 (if (not org-enforce-todo-checkbox-dependencies)
12587 t ; if locally turned off don't block
12588 (catch 'dont-block
12589 ;; If this is not a todo state change, or if this entry is already DONE,
12590 ;; do not block
12591 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12592 (member (plist-get change-plist :from)
12593 (cons 'done org-done-keywords))
12594 (member (plist-get change-plist :to)
12595 (cons 'todo org-not-done-keywords))
12596 (not (plist-get change-plist :to)))
12597 (throw 'dont-block t))
12598 ;; If this task has checkboxes that are not checked, it's blocked
12599 (save-excursion
12600 (org-back-to-heading t)
12601 (let ((beg (point)) end)
12602 (outline-next-heading)
12603 (setq end (point))
12604 (goto-char beg)
12605 (if (org-list-search-forward
12606 (concat (org-item-beginning-re)
12607 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12608 "\\[[- ]\\]")
12609 end t)
12610 (progn
12611 (if (boundp 'org-blocked-by-checkboxes)
12612 (setq org-blocked-by-checkboxes t))
12613 (throw 'dont-block nil)))))
12614 t))) ; do not block
12616 (defun org-entry-blocked-p ()
12617 "Is the current entry blocked?"
12618 (org-with-silent-modifications
12619 (if (org-entry-get nil "NOBLOCKING")
12620 nil ;; Never block this entry
12621 (not (run-hook-with-args-until-failure
12622 'org-blocker-hook
12623 (list :type 'todo-state-change
12624 :position (point)
12625 :from 'todo
12626 :to 'done))))))
12628 (defun org-update-statistics-cookies (all)
12629 "Update the statistics cookie, either from TODO or from checkboxes.
12630 This should be called with the cursor in a line with a statistics cookie."
12631 (interactive "P")
12632 (if all
12633 (progn
12634 (org-update-checkbox-count 'all)
12635 (org-map-entries 'org-update-parent-todo-statistics))
12636 (if (not (org-at-heading-p))
12637 (org-update-checkbox-count)
12638 (let ((pos (point-marker))
12639 end l1 l2)
12640 (ignore-errors (org-back-to-heading t))
12641 (if (not (org-at-heading-p))
12642 (org-update-checkbox-count)
12643 (setq l1 (org-outline-level))
12644 (setq end (save-excursion
12645 (outline-next-heading)
12646 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12647 (point)))
12648 (if (and (save-excursion
12649 (re-search-forward
12650 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12651 (not (save-excursion (re-search-forward
12652 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12653 (org-update-checkbox-count)
12654 (if (and l2 (> l2 l1))
12655 (progn
12656 (goto-char end)
12657 (org-update-parent-todo-statistics))
12658 (goto-char pos)
12659 (beginning-of-line 1)
12660 (while (re-search-forward
12661 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12662 (point-at-eol) t)
12663 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12664 (goto-char pos)
12665 (move-marker pos nil)))))
12667 (defvar org-entry-property-inherited-from) ;; defined below
12668 (defun org-update-parent-todo-statistics ()
12669 "Update any statistics cookie in the parent of the current headline.
12670 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12671 the entire subtree and this will travel up the hierarchy and update
12672 statistics everywhere."
12673 (let* ((prop (save-excursion (org-up-heading-safe)
12674 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12675 (recursive (or (not org-hierarchical-todo-statistics)
12676 (and prop (string-match "\\<recursive\\>" prop))))
12677 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12679 (first t)
12680 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12681 level ltoggle l1 new ndel
12682 (cnt-all 0) (cnt-done 0) is-percent kwd
12683 checkbox-beg ov ovs ove cookie-present)
12684 (catch 'exit
12685 (save-excursion
12686 (beginning-of-line 1)
12687 (setq ltoggle (funcall outline-level))
12688 ;; Three situations are to consider:
12690 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12691 ;; to the top-level ancestor on the headline;
12693 ;; 2. If parent has "recursive" property, repeat up to the
12694 ;; headline setting that property, taking inheritance into
12695 ;; account;
12697 ;; 3. Else, move up to direct parent and proceed only once.
12698 (while (and (setq level (org-up-heading-safe))
12699 (or recursive first)
12700 (>= (point) lim))
12701 (setq first nil cookie-present nil)
12702 (unless (and level
12703 (not (string-match
12704 "\\<checkbox\\>"
12705 (downcase (or (org-entry-get nil "COOKIE_DATA")
12706 "")))))
12707 (throw 'exit nil))
12708 (while (re-search-forward box-re (point-at-eol) t)
12709 (setq cnt-all 0 cnt-done 0 cookie-present t)
12710 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12711 (save-match-data
12712 (unless (outline-next-heading) (throw 'exit nil))
12713 (while (and (looking-at org-complex-heading-regexp)
12714 (> (setq l1 (length (match-string 1))) level))
12715 (setq kwd (and (or recursive (= l1 ltoggle))
12716 (match-string 2)))
12717 (if (or (eq org-provide-todo-statistics 'all-headlines)
12718 (and (listp org-provide-todo-statistics)
12719 (stringp (car org-provide-todo-statistics))
12720 (or (member kwd org-provide-todo-statistics)
12721 (member kwd org-done-keywords)))
12722 (and (listp org-provide-todo-statistics)
12723 (listp (car org-provide-todo-statistics))
12724 (or (member kwd (car org-provide-todo-statistics))
12725 (and (member kwd org-done-keywords)
12726 (member kwd (cadr org-provide-todo-statistics))))))
12727 (setq cnt-all (1+ cnt-all))
12728 (if (eq org-provide-todo-statistics t)
12729 (and kwd (setq cnt-all (1+ cnt-all)))))
12730 (when (or (and (listp org-provide-todo-statistics)
12731 (listp (car org-provide-todo-statistics))
12732 (member kwd org-done-keywords)
12733 (member kwd (cadr org-provide-todo-statistics)))
12734 (and (listp org-provide-todo-statistics)
12735 (stringp (car org-provide-todo-statistics))
12736 (member kwd org-done-keywords)))
12737 (setq cnt-done (1+ cnt-done)))
12738 (outline-next-heading)))
12739 (setq new
12740 (if is-percent
12741 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12742 (format "[%d/%d]" cnt-done cnt-all))
12743 ndel (- (match-end 0) checkbox-beg))
12744 ;; handle overlays when updating cookie from column view
12745 (when (setq ov (car (overlays-at checkbox-beg)))
12746 (setq ovs (overlay-start ov) ove (overlay-end ov))
12747 (delete-overlay ov))
12748 (goto-char checkbox-beg)
12749 (insert new)
12750 (delete-region (point) (+ (point) ndel))
12751 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12752 (when ov (move-overlay ov ovs ove)))
12753 (when cookie-present
12754 (run-hook-with-args 'org-after-todo-statistics-hook
12755 cnt-done (- cnt-all cnt-done))))))
12756 (run-hooks 'org-todo-statistics-hook)))
12758 (defvar org-after-todo-statistics-hook nil
12759 "Hook that is called after a TODO statistics cookie has been updated.
12760 Each function is called with two arguments: the number of not-done entries
12761 and the number of done entries.
12763 For example, the following function, when added to this hook, will switch
12764 an entry to DONE when all children are done, and back to TODO when new
12765 entries are set to a TODO status. Note that this hook is only called
12766 when there is a statistics cookie in the headline!
12768 (defun org-summary-todo (n-done n-not-done)
12769 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12770 (let (org-log-done org-log-states) ; turn off logging
12771 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12774 (defvar org-todo-statistics-hook nil
12775 "Hook that is run whenever Org thinks TODO statistics should be updated.
12776 This hook runs even if there is no statistics cookie present, in which case
12777 `org-after-todo-statistics-hook' would not run.")
12779 (defun org-todo-trigger-tag-changes (state)
12780 "Apply the changes defined in `org-todo-state-tags-triggers'."
12781 (let ((l org-todo-state-tags-triggers)
12782 changes)
12783 (when (or (not state) (equal state ""))
12784 (setq changes (append changes (cdr (assoc "" l)))))
12785 (when (and (stringp state) (> (length state) 0))
12786 (setq changes (append changes (cdr (assoc state l)))))
12787 (when (member state org-not-done-keywords)
12788 (setq changes (append changes (cdr (assoc 'todo l)))))
12789 (when (member state org-done-keywords)
12790 (setq changes (append changes (cdr (assoc 'done l)))))
12791 (dolist (c changes)
12792 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12794 (defun org-local-logging (value)
12795 "Get logging settings from a property VALUE."
12796 (let* (words w a)
12797 ;; directly set the variables, they are already local.
12798 (setq org-log-done nil
12799 org-log-repeat nil
12800 org-todo-log-states nil)
12801 (setq words (org-split-string value))
12802 (while (setq w (pop words))
12803 (cond
12804 ((setq a (assoc w org-startup-options))
12805 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12806 (set (nth 1 a) (nth 2 a))))
12807 ((setq a (org-extract-log-state-settings w))
12808 (and (member (car a) org-todo-keywords-1)
12809 (push a org-todo-log-states)))))))
12811 (defun org-get-todo-sequence-head (kwd)
12812 "Return the head of the TODO sequence to which KWD belongs.
12813 If KWD is not set, check if there is a text property remembering the
12814 right sequence."
12815 (let (p)
12816 (cond
12817 ((not kwd)
12818 (or (get-text-property (point-at-bol) 'org-todo-head)
12819 (progn
12820 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12821 nil (point-at-eol)))
12822 (get-text-property p 'org-todo-head))))
12823 ((not (member kwd org-todo-keywords-1))
12824 (car org-todo-keywords-1))
12825 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12827 (defun org-fast-todo-selection ()
12828 "Fast TODO keyword selection with single keys.
12829 Returns the new TODO keyword, or nil if no state change should occur."
12830 (let* ((fulltable org-todo-key-alist)
12831 (done-keywords org-done-keywords) ;; needed for the faces.
12832 (maxlen (apply 'max (mapcar
12833 (lambda (x)
12834 (if (stringp (car x)) (string-width (car x)) 0))
12835 fulltable)))
12836 (expert nil)
12837 (fwidth (+ maxlen 3 1 3))
12838 (ncol (/ (- (window-width) 4) fwidth))
12839 tg cnt e c tbl
12840 groups ingroup)
12841 (save-excursion
12842 (save-window-excursion
12843 (if expert
12844 (set-buffer (get-buffer-create " *Org todo*"))
12845 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12846 (erase-buffer)
12847 (org-set-local 'org-done-keywords done-keywords)
12848 (setq tbl fulltable cnt 0)
12849 (while (setq e (pop tbl))
12850 (cond
12851 ((equal e '(:startgroup))
12852 (push '() groups) (setq ingroup t)
12853 (when (not (= cnt 0))
12854 (setq cnt 0)
12855 (insert "\n"))
12856 (insert "{ "))
12857 ((equal e '(:endgroup))
12858 (setq ingroup nil cnt 0)
12859 (insert "}\n"))
12860 ((equal e '(:newline))
12861 (when (not (= cnt 0))
12862 (setq cnt 0)
12863 (insert "\n")
12864 (setq e (car tbl))
12865 (while (equal (car tbl) '(:newline))
12866 (insert "\n")
12867 (setq tbl (cdr tbl)))))
12869 (setq tg (car e) c (cdr e))
12870 (if ingroup (push tg (car groups)))
12871 (setq tg (org-add-props tg nil 'face
12872 (org-get-todo-face tg)))
12873 (if (and (= cnt 0) (not ingroup)) (insert " "))
12874 (insert "[" c "] " tg (make-string
12875 (- fwidth 4 (length tg)) ?\ ))
12876 (when (= (setq cnt (1+ cnt)) ncol)
12877 (insert "\n")
12878 (if ingroup (insert " "))
12879 (setq cnt 0)))))
12880 (insert "\n")
12881 (goto-char (point-min))
12882 (if (not expert) (org-fit-window-to-buffer))
12883 (message "[a-z..]:Set [SPC]:clear")
12884 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12885 (cond
12886 ((or (= c ?\C-g)
12887 (and (= c ?q) (not (rassoc c fulltable))))
12888 (setq quit-flag t))
12889 ((= c ?\ ) nil)
12890 ((setq e (rassoc c fulltable) tg (car e))
12892 (t (setq quit-flag t)))))))
12894 (defun org-entry-is-todo-p ()
12895 (member (org-get-todo-state) org-not-done-keywords))
12897 (defun org-entry-is-done-p ()
12898 (member (org-get-todo-state) org-done-keywords))
12900 (defun org-get-todo-state ()
12901 "Return the TODO keyword of the current subtree."
12902 (save-excursion
12903 (org-back-to-heading t)
12904 (and (looking-at org-todo-line-regexp)
12905 (match-end 2)
12906 (match-string 2))))
12908 (defun org-at-date-range-p (&optional inactive-ok)
12909 "Is the cursor inside a date range?"
12910 (interactive)
12911 (save-excursion
12912 (catch 'exit
12913 (let ((pos (point)))
12914 (skip-chars-backward "^[<\r\n")
12915 (skip-chars-backward "<[")
12916 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12917 (>= (match-end 0) pos)
12918 (throw 'exit t))
12919 (skip-chars-backward "^<[\r\n")
12920 (skip-chars-backward "<[")
12921 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12922 (>= (match-end 0) pos)
12923 (throw 'exit t)))
12924 nil)))
12926 (defun org-get-repeat (&optional tagline)
12927 "Check if there is a deadline/schedule with repeater in this entry."
12928 (save-match-data
12929 (save-excursion
12930 (org-back-to-heading t)
12931 (and (re-search-forward (if tagline
12932 (concat tagline "\\s-*" org-repeat-re)
12933 org-repeat-re)
12934 (org-entry-end-position) t)
12935 (match-string-no-properties 1)))))
12937 (defvar org-last-changed-timestamp)
12938 (defvar org-last-inserted-timestamp)
12939 (defvar org-log-post-message)
12940 (defvar org-log-note-purpose)
12941 (defvar org-log-note-how)
12942 (defvar org-log-note-extra)
12943 (defun org-auto-repeat-maybe (done-word)
12944 "Check if the current headline contains a repeated deadline/schedule.
12945 If yes, set TODO state back to what it was and change the base date
12946 of repeating deadline/scheduled time stamps to new date.
12947 This function is run automatically after each state change to a DONE state."
12948 ;; last-state is dynamically scoped into this function
12949 (let* ((repeat (org-get-repeat))
12950 (aa (assoc org-last-state org-todo-kwd-alist))
12951 (interpret (nth 1 aa))
12952 (head (nth 2 aa))
12953 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12954 (msg "Entry repeats: ")
12955 (org-log-done nil)
12956 (org-todo-log-states nil)
12957 re type n what ts time to-state)
12958 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12959 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12960 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12961 org-todo-repeat-to-state))
12962 (unless (and to-state (member to-state org-todo-keywords-1))
12963 (setq to-state (if (eq interpret 'type) org-last-state head)))
12964 (org-todo to-state)
12965 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12966 (org-entry-put nil "LAST_REPEAT" (format-time-string
12967 (org-time-stamp-format t t))))
12968 (when org-log-repeat
12969 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12970 (memq 'org-add-log-note post-command-hook))
12971 ;; OK, we are already setup for some record
12972 (if (eq org-log-repeat 'note)
12973 ;; make sure we take a note, not only a time stamp
12974 (setq org-log-note-how 'note))
12975 ;; Set up for taking a record
12976 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12977 org-last-state
12978 'findpos org-log-repeat)))
12979 (org-back-to-heading t)
12980 (org-add-planning-info nil nil 'closed)
12981 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12982 org-deadline-time-regexp "\\)\\|\\("
12983 org-ts-regexp "\\)"))
12984 (while (re-search-forward
12985 re (save-excursion (outline-next-heading) (point)) t)
12986 (setq type (if (match-end 1) org-scheduled-string
12987 (if (match-end 3) org-deadline-string "Plain:"))
12988 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12989 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12990 (setq n (string-to-number (match-string 2 ts))
12991 what (match-string 3 ts))
12992 (if (equal what "w") (setq n (* n 7) what "d"))
12993 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12994 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12995 ;; Preparation, see if we need to modify the start date for the change
12996 (when (match-end 1)
12997 (setq time (save-match-data (org-time-string-to-time ts)))
12998 (cond
12999 ((equal (match-string 1 ts) ".")
13000 ;; Shift starting date to today
13001 (org-timestamp-change
13002 (- (org-today) (time-to-days time))
13003 'day))
13004 ((equal (match-string 1 ts) "+")
13005 (let ((nshiftmax 10) (nshift 0))
13006 (while (or (= nshift 0)
13007 (<= (time-to-days time)
13008 (time-to-days (current-time))))
13009 (when (= (incf nshift) nshiftmax)
13010 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13011 (error "Abort")))
13012 (org-timestamp-change n (cdr (assoc what whata)))
13013 (org-at-timestamp-p t)
13014 (setq ts (match-string 1))
13015 (setq time (save-match-data (org-time-string-to-time ts)))))
13016 (org-timestamp-change (- n) (cdr (assoc what whata)))
13017 ;; rematch, so that we have everything in place for the real shift
13018 (org-at-timestamp-p t)
13019 (setq ts (match-string 1))
13020 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13021 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13022 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13023 (setq org-log-post-message msg)
13024 (message "%s" msg))))
13026 (defun org-show-todo-tree (arg)
13027 "Make a compact tree which shows all headlines marked with TODO.
13028 The tree will show the lines where the regexp matches, and all higher
13029 headlines above the match.
13030 With a \\[universal-argument] prefix, prompt for a regexp to match.
13031 With a numeric prefix N, construct a sparse tree for the Nth element
13032 of `org-todo-keywords-1'."
13033 (interactive "P")
13034 (let ((case-fold-search nil)
13035 (kwd-re
13036 (cond ((null arg) org-not-done-regexp)
13037 ((equal arg '(4))
13038 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13039 (mapcar 'list org-todo-keywords-1))))
13040 (concat "\\("
13041 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13042 "\\)\\>")))
13043 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13044 (regexp-quote (nth (1- (prefix-numeric-value arg))
13045 org-todo-keywords-1)))
13046 (t (user-error "Invalid prefix argument: %s" arg)))))
13047 (message "%d TODO entries found"
13048 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13050 (defun org-deadline (arg &optional time)
13051 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13052 With one universal prefix argument, remove any deadline from the item.
13053 With two universal prefix arguments, prompt for a warning delay.
13054 With argument TIME, set the deadline at the corresponding date. TIME
13055 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13056 (interactive "P")
13057 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13058 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13059 'region-start-level 'region))
13060 org-loop-over-headlines-in-active-region)
13061 (org-map-entries
13062 `(org-deadline ',arg ,time)
13063 org-loop-over-headlines-in-active-region
13064 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13065 (let* ((old-date (org-entry-get nil "DEADLINE"))
13066 (old-date-time (if old-date (org-time-string-to-time old-date)))
13067 (repeater (and old-date
13068 (string-match
13069 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13070 old-date)
13071 (match-string 1 old-date))))
13072 (cond
13073 ((equal arg '(4))
13074 (when (and old-date org-log-redeadline)
13075 (org-add-log-setup 'deldeadline nil old-date 'findpos
13076 org-log-redeadline))
13077 (org-remove-timestamp-with-keyword org-deadline-string)
13078 (message "Item no longer has a deadline."))
13079 ((equal arg '(16))
13080 (save-excursion
13081 (org-back-to-heading t)
13082 (if (re-search-forward
13083 org-deadline-time-regexp
13084 (save-excursion (outline-next-heading) (point)) t)
13085 (let* ((rpl0 (match-string 1))
13086 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13087 (replace-match
13088 (concat org-deadline-string
13089 " <" rpl
13090 (format " -%dd"
13091 (abs
13092 (- (time-to-days
13093 (save-match-data
13094 (org-read-date nil t nil "Warn starting from" old-date-time)))
13095 (time-to-days old-date-time))))
13096 ">") t t))
13097 (user-error "No deadline information to update"))))
13099 (org-add-planning-info 'deadline time 'closed)
13100 (when (and old-date org-log-redeadline
13101 (not (equal old-date
13102 (substring org-last-inserted-timestamp 1 -1))))
13103 (org-add-log-setup 'redeadline nil old-date 'findpos
13104 org-log-redeadline))
13105 (when repeater
13106 (save-excursion
13107 (org-back-to-heading t)
13108 (when (re-search-forward (concat org-deadline-string " "
13109 org-last-inserted-timestamp)
13110 (save-excursion
13111 (outline-next-heading) (point)) t)
13112 (goto-char (1- (match-end 0)))
13113 (insert " " repeater)
13114 (setq org-last-inserted-timestamp
13115 (concat (substring org-last-inserted-timestamp 0 -1)
13116 " " repeater
13117 (substring org-last-inserted-timestamp -1))))))
13118 (message "Deadline on %s" org-last-inserted-timestamp))))))
13120 (defun org-schedule (arg &optional time)
13121 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13122 With one universal prefix argument, remove any scheduling date from the item.
13123 With two universal prefix arguments, prompt for a delay cookie.
13124 With argument TIME, scheduled at the corresponding date. TIME can
13125 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13126 (interactive "P")
13127 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13128 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13129 'region-start-level 'region))
13130 org-loop-over-headlines-in-active-region)
13131 (org-map-entries
13132 `(org-schedule ',arg ,time)
13133 org-loop-over-headlines-in-active-region
13134 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13135 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13136 (old-date-time (if old-date (org-time-string-to-time old-date)))
13137 (repeater (and old-date
13138 (string-match
13139 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13140 old-date)
13141 (match-string 1 old-date))))
13142 (cond
13143 ((equal arg '(4))
13144 (progn
13145 (when (and old-date org-log-reschedule)
13146 (org-add-log-setup 'delschedule nil old-date 'findpos
13147 org-log-reschedule))
13148 (org-remove-timestamp-with-keyword org-scheduled-string)
13149 (message "Item is no longer scheduled.")))
13150 ((equal arg '(16))
13151 (save-excursion
13152 (org-back-to-heading t)
13153 (if (re-search-forward
13154 org-scheduled-time-regexp
13155 (save-excursion (outline-next-heading) (point)) t)
13156 (let* ((rpl0 (match-string 1))
13157 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13158 (replace-match
13159 (concat org-scheduled-string
13160 " <" rpl
13161 (format " -%dd"
13162 (abs
13163 (- (time-to-days
13164 (save-match-data
13165 (org-read-date nil t nil "Delay until" old-date-time)))
13166 (time-to-days old-date-time))))
13167 ">") t t))
13168 (user-error "No scheduled information to update"))))
13170 (org-add-planning-info 'scheduled time 'closed)
13171 (when (and old-date org-log-reschedule
13172 (not (equal old-date
13173 (substring org-last-inserted-timestamp 1 -1))))
13174 (org-add-log-setup 'reschedule nil old-date 'findpos
13175 org-log-reschedule))
13176 (when repeater
13177 (save-excursion
13178 (org-back-to-heading t)
13179 (when (re-search-forward (concat org-scheduled-string " "
13180 org-last-inserted-timestamp)
13181 (save-excursion
13182 (outline-next-heading) (point)) t)
13183 (goto-char (1- (match-end 0)))
13184 (insert " " repeater)
13185 (setq org-last-inserted-timestamp
13186 (concat (substring org-last-inserted-timestamp 0 -1)
13187 " " repeater
13188 (substring org-last-inserted-timestamp -1))))))
13189 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13191 (defun org-get-scheduled-time (pom &optional inherit)
13192 "Get the scheduled time as a time tuple, of a format suitable
13193 for calling org-schedule with, or if there is no scheduling,
13194 returns nil."
13195 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13196 (when time
13197 (apply 'encode-time (org-parse-time-string time)))))
13199 (defun org-get-deadline-time (pom &optional inherit)
13200 "Get the deadline as a time tuple, of a format suitable for
13201 calling org-deadline with, or if there is no scheduling, returns
13202 nil."
13203 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13204 (when time
13205 (apply 'encode-time (org-parse-time-string time)))))
13207 (defun org-remove-timestamp-with-keyword (keyword)
13208 "Remove all time stamps with KEYWORD in the current entry."
13209 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13210 beg)
13211 (save-excursion
13212 (org-back-to-heading t)
13213 (setq beg (point))
13214 (outline-next-heading)
13215 (while (re-search-backward re beg t)
13216 (replace-match "")
13217 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13218 (equal (char-before) ?\ ))
13219 (backward-delete-char 1)
13220 (if (string-match "^[ \t]*$" (buffer-substring
13221 (point-at-bol) (point-at-eol)))
13222 (delete-region (point-at-bol)
13223 (min (point-max) (1+ (point-at-eol))))))))))
13225 (defvar org-time-was-given) ; dynamically scoped parameter
13226 (defvar org-end-time-was-given) ; dynamically scoped parameter
13228 (defun org-add-planning-info (what &optional time &rest remove)
13229 "Insert new timestamp with keyword in the line directly after the headline.
13230 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13231 If non is given, the user is prompted for a date.
13232 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13233 be removed."
13234 (interactive)
13235 (let (org-time-was-given org-end-time-was-given ts
13236 end default-time default-input)
13238 (catch 'exit
13239 (when (and (memq what '(scheduled deadline))
13240 (or (not time)
13241 (and (stringp time)
13242 (string-match "^[-+]+[0-9]" time))))
13243 ;; Try to get a default date/time from existing timestamp
13244 (save-excursion
13245 (org-back-to-heading t)
13246 (setq end (save-excursion (outline-next-heading) (point)))
13247 (when (re-search-forward (if (eq what 'scheduled)
13248 org-scheduled-time-regexp
13249 org-deadline-time-regexp)
13250 end t)
13251 (setq ts (match-string 1)
13252 default-time
13253 (apply 'encode-time (org-parse-time-string ts))
13254 default-input (and ts (org-get-compact-tod ts))))))
13255 (when what
13256 (setq time
13257 (if (stringp time)
13258 ;; This is a string (relative or absolute), set proper date
13259 (apply 'encode-time
13260 (org-read-date-analyze
13261 time default-time (decode-time default-time)))
13262 ;; If necessary, get the time from the user
13263 (or time (org-read-date nil 'to-time nil nil
13264 default-time default-input)))))
13266 (when (and org-insert-labeled-timestamps-at-point
13267 (member what '(scheduled deadline)))
13268 (insert
13269 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13270 (org-insert-time-stamp time org-time-was-given
13271 nil nil nil (list org-end-time-was-given))
13272 (setq what nil))
13273 (save-excursion
13274 (save-restriction
13275 (let (col list elt ts buffer-invisibility-spec)
13276 (org-back-to-heading t)
13277 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13278 (goto-char (match-end 1))
13279 (setq col (current-column))
13280 (goto-char (match-end 0))
13281 (if (eobp) (insert "\n") (forward-char 1))
13282 (when (and (not what)
13283 (not (looking-at
13284 (concat "[ \t]*"
13285 org-keyword-time-not-clock-regexp))))
13286 ;; Nothing to add, nothing to remove...... :-)
13287 (throw 'exit nil))
13288 (if (and (not (looking-at org-outline-regexp))
13289 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13290 "[^\r\n]*"))
13291 (not (equal (match-string 1) org-clock-string)))
13292 (narrow-to-region (match-beginning 0) (match-end 0))
13293 (insert-before-markers "\n")
13294 (backward-char 1)
13295 (narrow-to-region (point) (point))
13296 (and org-adapt-indentation (org-indent-to-column col)))
13297 ;; Check if we have to remove something.
13298 (setq list (cons what remove))
13299 (while list
13300 (setq elt (pop list))
13301 (when (or (and (eq elt 'scheduled)
13302 (re-search-forward org-scheduled-time-regexp nil t))
13303 (and (eq elt 'deadline)
13304 (re-search-forward org-deadline-time-regexp nil t))
13305 (and (eq elt 'closed)
13306 (re-search-forward org-closed-time-regexp nil t)))
13307 (replace-match "")
13308 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13309 (and (looking-at "[ \t]+") (replace-match ""))
13310 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13311 (when what
13312 (insert
13313 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13314 (cond ((eq what 'scheduled) org-scheduled-string)
13315 ((eq what 'deadline) org-deadline-string)
13316 ((eq what 'closed) org-closed-string))
13317 " ")
13318 (setq ts (org-insert-time-stamp
13319 time
13320 (or org-time-was-given
13321 (and (eq what 'closed) org-log-done-with-time))
13322 (eq what 'closed)
13323 nil nil (list org-end-time-was-given)))
13324 (insert
13325 (if (not (or (bolp) (eq (char-before) ?\ )
13326 (memq (char-after) '(32 10))
13327 (eobp))) " " ""))
13328 (end-of-line 1))
13329 (goto-char (point-min))
13330 (widen)
13331 (if (and (looking-at "[ \t]*\n")
13332 (equal (char-before) ?\n))
13333 (delete-region (1- (point)) (point-at-eol)))
13334 ts))))))
13336 (defvar org-log-note-marker (make-marker))
13337 (defvar org-log-note-purpose nil)
13338 (defvar org-log-note-state nil)
13339 (defvar org-log-note-previous-state nil)
13340 (defvar org-log-note-how nil)
13341 (defvar org-log-note-extra nil)
13342 (defvar org-log-note-window-configuration nil)
13343 (defvar org-log-note-return-to (make-marker))
13344 (defvar org-log-note-effective-time nil
13345 "Remembered current time so that dynamically scoped
13346 `org-extend-today-until' affects tha timestamps in state change
13347 log")
13349 (defvar org-log-post-message nil
13350 "Message to be displayed after a log note has been stored.
13351 The auto-repeater uses this.")
13353 (defun org-add-note ()
13354 "Add a note to the current entry.
13355 This is done in the same way as adding a state change note."
13356 (interactive)
13357 (org-add-log-setup 'note nil nil 'findpos nil))
13359 (defvar org-property-end-re)
13360 (defun org-add-log-setup (&optional purpose state prev-state
13361 findpos how extra)
13362 "Set up the post command hook to take a note.
13363 If this is about to TODO state change, the new state is expected in STATE.
13364 When FINDPOS is non-nil, find the correct position for the note in
13365 the current entry. If not, assume that it can be inserted at point.
13366 HOW is an indicator what kind of note should be created.
13367 EXTRA is additional text that will be inserted into the notes buffer."
13368 (let* ((org-log-into-drawer (org-log-into-drawer))
13369 (drawer (cond ((stringp org-log-into-drawer)
13370 org-log-into-drawer)
13371 (org-log-into-drawer "LOGBOOK"))))
13372 (save-restriction
13373 (save-excursion
13374 (when findpos
13375 (org-back-to-heading t)
13376 (narrow-to-region (point) (save-excursion
13377 (outline-next-heading) (point)))
13378 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13379 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13380 "[^\r\n]*\\)?"))
13381 (goto-char (match-end 0))
13382 (cond
13383 (drawer
13384 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13385 nil t)
13386 (progn
13387 (goto-char (match-end 0))
13388 (or org-log-states-order-reversed
13389 (and (re-search-forward org-property-end-re nil t)
13390 (goto-char (1- (match-beginning 0))))))
13391 (insert "\n:" drawer ":\n:END:")
13392 (beginning-of-line 0)
13393 (org-indent-line)
13394 (beginning-of-line 2)
13395 (org-indent-line)
13396 (end-of-line 0)))
13397 ((and org-log-state-notes-insert-after-drawers
13398 (save-excursion
13399 (forward-line) (looking-at org-drawer-regexp)))
13400 (forward-line)
13401 (while (looking-at org-drawer-regexp)
13402 (goto-char (match-end 0))
13403 (re-search-forward org-property-end-re (point-max) t)
13404 (forward-line))
13405 (forward-line -1)))
13406 (unless org-log-states-order-reversed
13407 (and (= (char-after) ?\n) (forward-char 1))
13408 (org-skip-over-state-notes)
13409 (skip-chars-backward " \t\n\r")))
13410 (move-marker org-log-note-marker (point))
13411 (setq org-log-note-purpose purpose
13412 org-log-note-state state
13413 org-log-note-previous-state prev-state
13414 org-log-note-how how
13415 org-log-note-extra extra
13416 org-log-note-effective-time (org-current-effective-time))
13417 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13419 (defun org-skip-over-state-notes ()
13420 "Skip past the list of State notes in an entry."
13421 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13422 (when (ignore-errors (goto-char (org-in-item-p)))
13423 (let* ((struct (org-list-struct))
13424 (prevs (org-list-prevs-alist struct)))
13425 (while (looking-at "[ \t]*- State")
13426 (goto-char (or (org-list-get-next-item (point) struct prevs)
13427 (org-list-get-item-end (point) struct)))))))
13429 (defun org-add-log-note (&optional purpose)
13430 "Pop up a window for taking a note, and add this note later at point."
13431 (remove-hook 'post-command-hook 'org-add-log-note)
13432 (setq org-log-note-window-configuration (current-window-configuration))
13433 (delete-other-windows)
13434 (move-marker org-log-note-return-to (point))
13435 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13436 (goto-char org-log-note-marker)
13437 (org-switch-to-buffer-other-window "*Org Note*")
13438 (erase-buffer)
13439 (if (memq org-log-note-how '(time state))
13440 (let (current-prefix-arg) (org-store-log-note))
13441 (let ((org-inhibit-startup t)) (org-mode))
13442 (insert (format "# Insert note for %s.
13443 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13444 (cond
13445 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13446 ((eq org-log-note-purpose 'done) "closed todo item")
13447 ((eq org-log-note-purpose 'state)
13448 (format "state change from \"%s\" to \"%s\""
13449 (or org-log-note-previous-state "")
13450 (or org-log-note-state "")))
13451 ((eq org-log-note-purpose 'reschedule)
13452 "rescheduling")
13453 ((eq org-log-note-purpose 'delschedule)
13454 "no longer scheduled")
13455 ((eq org-log-note-purpose 'redeadline)
13456 "changing deadline")
13457 ((eq org-log-note-purpose 'deldeadline)
13458 "removing deadline")
13459 ((eq org-log-note-purpose 'refile)
13460 "refiling")
13461 ((eq org-log-note-purpose 'note)
13462 "this entry")
13463 (t (error "This should not happen")))))
13464 (if org-log-note-extra (insert org-log-note-extra))
13465 (org-set-local 'org-finish-function 'org-store-log-note)
13466 (run-hooks 'org-log-buffer-setup-hook)))
13468 (defvar org-note-abort nil) ; dynamically scoped
13469 (defun org-store-log-note ()
13470 "Finish taking a log note, and insert it to where it belongs."
13471 (let ((txt (buffer-string)))
13472 (kill-buffer (current-buffer))
13473 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13474 lines ind bul)
13475 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13476 (setq txt (replace-match "" t t txt)))
13477 (if (string-match "\\s-+\\'" txt)
13478 (setq txt (replace-match "" t t txt)))
13479 (setq lines (org-split-string txt "\n"))
13480 (when (and note (string-match "\\S-" note))
13481 (setq note
13482 (org-replace-escapes
13483 note
13484 (list (cons "%u" (user-login-name))
13485 (cons "%U" user-full-name)
13486 (cons "%t" (format-time-string
13487 (org-time-stamp-format 'long 'inactive)
13488 org-log-note-effective-time))
13489 (cons "%T" (format-time-string
13490 (org-time-stamp-format 'long nil)
13491 org-log-note-effective-time))
13492 (cons "%d" (format-time-string
13493 (org-time-stamp-format nil 'inactive)
13494 org-log-note-effective-time))
13495 (cons "%D" (format-time-string
13496 (org-time-stamp-format nil nil)
13497 org-log-note-effective-time))
13498 (cons "%s" (if org-log-note-state
13499 (concat "\"" org-log-note-state "\"")
13500 ""))
13501 (cons "%S" (if org-log-note-previous-state
13502 (concat "\"" org-log-note-previous-state "\"")
13503 "\"\"")))))
13504 (if lines (setq note (concat note " \\\\")))
13505 (push note lines))
13506 (when (or current-prefix-arg org-note-abort)
13507 (when org-log-into-drawer
13508 (org-remove-empty-drawer-at org-log-note-marker))
13509 (setq lines nil))
13510 (when lines
13511 (with-current-buffer (marker-buffer org-log-note-marker)
13512 (save-excursion
13513 (goto-char org-log-note-marker)
13514 (move-marker org-log-note-marker nil)
13515 (end-of-line 1)
13516 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13517 (setq ind (save-excursion
13518 (if (ignore-errors (goto-char (org-in-item-p)))
13519 (let ((struct (org-list-struct)))
13520 (org-list-get-ind
13521 (org-list-get-top-point struct) struct))
13522 (skip-chars-backward " \r\t\n")
13523 (cond
13524 ((and (org-at-heading-p)
13525 org-adapt-indentation)
13526 (1+ (org-current-level)))
13527 ((org-at-heading-p) 0)
13528 (t (org-get-indentation))))))
13529 (setq bul (org-list-bullet-string "-"))
13530 (org-indent-line-to ind)
13531 (insert bul (pop lines))
13532 (let ((ind-body (+ (length bul) ind)))
13533 (while lines
13534 (insert "\n")
13535 (org-indent-line-to ind-body)
13536 (insert (pop lines))))
13537 (message "Note stored")
13538 (org-back-to-heading t)
13539 (org-cycle-hide-drawers 'children))
13540 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13541 ;; from within `org-add-log-note' because `buffer-undo-list'
13542 ;; is then modified outside of `org-with-remote-undo'.
13543 (when (eq this-command 'org-agenda-todo)
13544 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13545 ;; Don't add undo information when called from `org-agenda-todo'
13546 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13547 (set-window-configuration org-log-note-window-configuration)
13548 (with-current-buffer (marker-buffer org-log-note-return-to)
13549 (goto-char org-log-note-return-to))
13550 (move-marker org-log-note-return-to nil)
13551 (and org-log-post-message (message "%s" org-log-post-message))))
13553 (defun org-remove-empty-drawer-at (pos)
13554 "Remove an empty drawer at position POS.
13555 POS may also be a marker."
13556 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13557 (org-with-wide-buffer
13558 (goto-char pos)
13559 (let ((drawer (org-element-at-point)))
13560 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13561 (not (org-element-property :contents-begin drawer)))
13562 (delete-region (org-element-property :begin drawer)
13563 (progn (goto-char (org-element-property :end drawer))
13564 (skip-chars-backward " \r\t\n")
13565 (forward-line)
13566 (point))))))))
13568 (defvar org-ts-type nil)
13569 (defun org-sparse-tree (&optional arg type)
13570 "Create a sparse tree, prompt for the details.
13571 This command can create sparse trees. You first need to select the type
13572 of match used to create the tree:
13574 t Show all TODO entries.
13575 T Show entries with a specific TODO keyword.
13576 m Show entries selected by a tags/property match.
13577 p Enter a property name and its value (both with completion on existing
13578 names/values) and show entries with that property.
13579 r Show entries matching a regular expression (`/' can be used as well).
13580 b Show deadlines and scheduled items before a date.
13581 a Show deadlines and scheduled items after a date.
13582 d Show deadlines due within `org-deadline-warning-days'.
13583 D Show deadlines and scheduled items between a date range."
13584 (interactive "P")
13585 (let (ans kwd value ts-type)
13586 (setq type (or type org-sparse-tree-default-date-type))
13587 (setq org-ts-type type)
13588 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range\n [c]ycle through date types: %s"
13589 (cond ((eq type 'all) "all timestamps")
13590 ((eq type 'scheduled) "only scheduled")
13591 ((eq type 'deadline) "only deadline")
13592 ((eq type 'active) "only active timestamps")
13593 ((eq type 'inactive) "only inactive timestamps")
13594 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13595 ((eq type 'closed) "with a closed time-stamp")
13596 (t "scheduled/deadline")))
13597 (setq ans (read-char-exclusive))
13598 (cond
13599 ((equal ans ?c)
13600 (org-sparse-tree
13601 arg (cadr (member type '(scheduled-or-deadline
13602 all scheduled deadline active inactive closed)))))
13603 ((equal ans ?d)
13604 (call-interactively 'org-check-deadlines))
13605 ((equal ans ?b)
13606 (call-interactively 'org-check-before-date))
13607 ((equal ans ?a)
13608 (call-interactively 'org-check-after-date))
13609 ((equal ans ?D)
13610 (call-interactively 'org-check-dates-range))
13611 ((equal ans ?t)
13612 (call-interactively 'org-show-todo-tree))
13613 ((equal ans ?T)
13614 (org-show-todo-tree '(4)))
13615 ((member ans '(?T ?m))
13616 (call-interactively 'org-match-sparse-tree))
13617 ((member ans '(?p ?P))
13618 (setq kwd (org-icompleting-read "Property: "
13619 (mapcar 'list (org-buffer-property-keys))))
13620 (setq value (org-icompleting-read "Value: "
13621 (mapcar 'list (org-property-values kwd))))
13622 (unless (string-match "\\`{.*}\\'" value)
13623 (setq value (concat "\"" value "\"")))
13624 (org-match-sparse-tree arg (concat kwd "=" value)))
13625 ((member ans '(?r ?R ?/))
13626 (call-interactively 'org-occur))
13627 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13629 (defvar org-occur-highlights nil
13630 "List of overlays used for occur matches.")
13631 (make-variable-buffer-local 'org-occur-highlights)
13632 (defvar org-occur-parameters nil
13633 "Parameters of the active org-occur calls.
13634 This is a list, each call to org-occur pushes as cons cell,
13635 containing the regular expression and the callback, onto the list.
13636 The list can contain several entries if `org-occur' has been called
13637 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13638 will only contain one set of parameters. When the highlights are
13639 removed (for example with `C-c C-c', or with the next edit (depending
13640 on `org-remove-highlights-with-change'), this variable is emptied
13641 as well.")
13642 (make-variable-buffer-local 'org-occur-parameters)
13644 (defun org-occur (regexp &optional keep-previous callback)
13645 "Make a compact tree which shows all matches of REGEXP.
13646 The tree will show the lines where the regexp matches, and all higher
13647 headlines above the match. It will also show the heading after the match,
13648 to make sure editing the matching entry is easy.
13649 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13650 call to `org-occur' will be kept, to allow stacking of calls to this
13651 command.
13652 If CALLBACK is non-nil, it is a function which is called to confirm
13653 that the match should indeed be shown."
13654 (interactive "sRegexp: \nP")
13655 (when (equal regexp "")
13656 (user-error "Regexp cannot be empty"))
13657 (unless keep-previous
13658 (org-remove-occur-highlights nil nil t))
13659 (push (cons regexp callback) org-occur-parameters)
13660 (let ((cnt 0))
13661 (save-excursion
13662 (goto-char (point-min))
13663 (if (or (not keep-previous) ; do not want to keep
13664 (not org-occur-highlights)) ; no previous matches
13665 ;; hide everything
13666 (org-overview))
13667 (while (re-search-forward regexp nil t)
13668 (when (or (not callback)
13669 (save-match-data (funcall callback)))
13670 (setq cnt (1+ cnt))
13671 (when org-highlight-sparse-tree-matches
13672 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13673 (org-show-context 'occur-tree))))
13674 (when org-remove-highlights-with-change
13675 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13676 nil 'local))
13677 (unless org-sparse-tree-open-archived-trees
13678 (org-hide-archived-subtrees (point-min) (point-max)))
13679 (run-hooks 'org-occur-hook)
13680 (if (org-called-interactively-p 'interactive)
13681 (message "%d match(es) for regexp %s" cnt regexp))
13682 cnt))
13684 (defun org-occur-next-match (&optional n reset)
13685 "Function for `next-error-function' to find sparse tree matches.
13686 N is the number of matches to move, when negative move backwards.
13687 RESET is entirely ignored - this function always goes back to the
13688 starting point when no match is found."
13689 (let* ((limit (if (< n 0) (point-min) (point-max)))
13690 (search-func (if (< n 0)
13691 'previous-single-char-property-change
13692 'next-single-char-property-change))
13693 (n (abs n))
13694 (pos (point))
13696 (catch 'exit
13697 (while (setq p1 (funcall search-func (point) 'org-type))
13698 (when (equal p1 limit)
13699 (goto-char pos)
13700 (error "No more matches"))
13701 (when (equal (get-char-property p1 'org-type) 'org-occur)
13702 (setq n (1- n))
13703 (when (= n 0)
13704 (goto-char p1)
13705 (throw 'exit (point))))
13706 (goto-char p1))
13707 (goto-char p1)
13708 (error "No more matches"))))
13710 (defun org-show-context (&optional key)
13711 "Make sure point and context are visible.
13712 How much context is shown depends upon the variables
13713 `org-show-hierarchy-above', `org-show-following-heading',
13714 `org-show-entry-below' and `org-show-siblings'."
13715 (let ((heading-p (org-at-heading-p t))
13716 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13717 (following-p (org-get-alist-option org-show-following-heading key))
13718 (entry-p (org-get-alist-option org-show-entry-below key))
13719 (siblings-p (org-get-alist-option org-show-siblings key)))
13720 ;; Show heading or entry text
13721 (if (and heading-p (not entry-p))
13722 (org-flag-heading nil) ; only show the heading
13723 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13724 (org-show-hidden-entry))) ; show entire entry
13725 (when following-p
13726 ;; Show next sibling, or heading below text
13727 (save-excursion
13728 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13729 (org-flag-heading nil))))
13730 (when siblings-p (org-show-siblings))
13731 (when hierarchy-p
13732 ;; show all higher headings, possibly with siblings
13733 (save-excursion
13734 (while (and (condition-case nil
13735 (progn (org-up-heading-all 1) t)
13736 (error nil))
13737 (not (bobp)))
13738 (org-flag-heading nil)
13739 (when siblings-p (org-show-siblings)))))
13740 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13742 (defvar org-reveal-start-hook nil
13743 "Hook run before revealing a location.")
13745 (defun org-reveal (&optional siblings)
13746 "Show current entry, hierarchy above it, and the following headline.
13747 This can be used to show a consistent set of context around locations
13748 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13749 not t for the search context.
13751 With optional argument SIBLINGS, on each level of the hierarchy all
13752 siblings are shown. This repairs the tree structure to what it would
13753 look like when opened with hierarchical calls to `org-cycle'.
13754 With double optional argument \\[universal-argument] \\[universal-argument], \
13755 go to the parent and show the
13756 entire tree."
13757 (interactive "P")
13758 (run-hooks 'org-reveal-start-hook)
13759 (let ((org-show-hierarchy-above t)
13760 (org-show-following-heading t)
13761 (org-show-siblings (if siblings t org-show-siblings)))
13762 (org-show-context nil))
13763 (when (equal siblings '(16))
13764 (save-excursion
13765 (when (org-up-heading-safe)
13766 (org-show-subtree)
13767 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13769 (defun org-highlight-new-match (beg end)
13770 "Highlight from BEG to END and mark the highlight is an occur headline."
13771 (let ((ov (make-overlay beg end)))
13772 (overlay-put ov 'face 'secondary-selection)
13773 (overlay-put ov 'org-type 'org-occur)
13774 (push ov org-occur-highlights)))
13776 (defun org-remove-occur-highlights (&optional beg end noremove)
13777 "Remove the occur highlights from the buffer.
13778 BEG and END are ignored. If NOREMOVE is nil, remove this function
13779 from the `before-change-functions' in the current buffer."
13780 (interactive)
13781 (unless org-inhibit-highlight-removal
13782 (mapc 'delete-overlay org-occur-highlights)
13783 (setq org-occur-highlights nil)
13784 (setq org-occur-parameters nil)
13785 (unless noremove
13786 (remove-hook 'before-change-functions
13787 'org-remove-occur-highlights 'local))))
13789 ;;;; Priorities
13791 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13792 "Regular expression matching the priority indicator.")
13794 (defvar org-remove-priority-next-time nil)
13796 (defun org-priority-up ()
13797 "Increase the priority of the current item."
13798 (interactive)
13799 (org-priority 'up))
13801 (defun org-priority-down ()
13802 "Decrease the priority of the current item."
13803 (interactive)
13804 (org-priority 'down))
13806 (defun org-priority (&optional action show)
13807 "Change the priority of an item.
13808 ACTION can be `set', `up', `down', or a character."
13809 (interactive "P")
13810 (if (equal action '(4))
13811 (org-show-priority)
13812 (unless org-enable-priority-commands
13813 (user-error "Priority commands are disabled"))
13814 (setq action (or action 'set))
13815 (let (current new news have remove)
13816 (save-excursion
13817 (org-back-to-heading t)
13818 (if (looking-at org-priority-regexp)
13819 (setq current (string-to-char (match-string 2))
13820 have t))
13821 (cond
13822 ((eq action 'remove)
13823 (setq remove t new ?\ ))
13824 ((or (eq action 'set)
13825 (if (featurep 'xemacs) (characterp action) (integerp action)))
13826 (if (not (eq action 'set))
13827 (setq new action)
13828 (message "Priority %c-%c, SPC to remove: "
13829 org-highest-priority org-lowest-priority)
13830 (save-match-data
13831 (setq new (read-char-exclusive))))
13832 (if (and (= (upcase org-highest-priority) org-highest-priority)
13833 (= (upcase org-lowest-priority) org-lowest-priority))
13834 (setq new (upcase new)))
13835 (cond ((equal new ?\ ) (setq remove t))
13836 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13837 (user-error "Priority must be between `%c' and `%c'"
13838 org-highest-priority org-lowest-priority))))
13839 ((eq action 'up)
13840 (setq new (if have
13841 (1- current) ; normal cycling
13842 ;; last priority was empty
13843 (if (eq last-command this-command)
13844 org-lowest-priority ; wrap around empty to lowest
13845 ;; default
13846 (if org-priority-start-cycle-with-default
13847 org-default-priority
13848 (1- org-default-priority))))))
13849 ((eq action 'down)
13850 (setq new (if have
13851 (1+ current) ; normal cycling
13852 ;; last priority was empty
13853 (if (eq last-command this-command)
13854 org-highest-priority ; wrap around empty to highest
13855 ;; default
13856 (if org-priority-start-cycle-with-default
13857 org-default-priority
13858 (1+ org-default-priority))))))
13859 (t (user-error "Invalid action")))
13860 (if (or (< (upcase new) org-highest-priority)
13861 (> (upcase new) org-lowest-priority))
13862 (if (and (memq action '(up down))
13863 (not have) (not (eq last-command this-command)))
13864 ;; `new' is from default priority
13865 (error
13866 "The default can not be set, see `org-default-priority' why")
13867 ;; normal cycling: `new' is beyond highest/lowest priority
13868 ;; and is wrapped around to the empty priority
13869 (setq remove t)))
13870 (setq news (format "%c" new))
13871 (if have
13872 (if remove
13873 (replace-match "" t t nil 1)
13874 (replace-match news t t nil 2))
13875 (if remove
13876 (user-error "No priority cookie found in line")
13877 (let ((case-fold-search nil))
13878 (looking-at org-todo-line-regexp))
13879 (if (match-end 2)
13880 (progn
13881 (goto-char (match-end 2))
13882 (insert " [#" news "]"))
13883 (goto-char (match-beginning 3))
13884 (insert "[#" news "] "))))
13885 (org-set-tags nil 'align))
13886 (if remove
13887 (message "Priority removed")
13888 (message "Priority of current item set to %s" news)))))
13890 (defun org-show-priority ()
13891 "Show the priority of the current item.
13892 This priority is composed of the main priority given with the [#A] cookies,
13893 and by additional input from the age of a schedules or deadline entry."
13894 (interactive)
13895 (let ((pri (if (eq major-mode 'org-agenda-mode)
13896 (org-get-at-bol 'priority)
13897 (save-excursion
13898 (save-match-data
13899 (beginning-of-line)
13900 (and (looking-at org-heading-regexp)
13901 (org-get-priority (match-string 0))))))))
13902 (message "Priority is %d" (if pri pri -1000))))
13904 (defun org-get-priority (s)
13905 "Find priority cookie and return priority."
13906 (save-match-data
13907 (if (functionp org-get-priority-function)
13908 (funcall org-get-priority-function)
13909 (if (not (string-match org-priority-regexp s))
13910 (* 1000 (- org-lowest-priority org-default-priority))
13911 (* 1000 (- org-lowest-priority
13912 (string-to-char (match-string 2 s))))))))
13914 ;;;; Tags
13916 (defvar org-agenda-archives-mode)
13917 (defvar org-map-continue-from nil
13918 "Position from where mapping should continue.
13919 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13921 (defvar org-scanner-tags nil
13922 "The current tag list while the tags scanner is running.")
13923 (defvar org-trust-scanner-tags nil
13924 "Should `org-get-tags-at' use the tags for the scanner.
13925 This is for internal dynamical scoping only.
13926 When this is non-nil, the function `org-get-tags-at' will return the value
13927 of `org-scanner-tags' instead of building the list by itself. This
13928 can lead to large speed-ups when the tags scanner is used in a file with
13929 many entries, and when the list of tags is retrieved, for example to
13930 obtain a list of properties. Building the tags list for each entry in such
13931 a file becomes an N^2 operation - but with this variable set, it scales
13932 as N.")
13934 (defun org-scan-tags (action matcher todo-only &optional start-level)
13935 "Sca headline tags with inheritance and produce output ACTION.
13937 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13938 or `agenda' to produce an entry list for an agenda view. It can also be
13939 a Lisp form or a function that should be called at each matched headline, in
13940 this case the return value is a list of all return values from these calls.
13942 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13943 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13944 only lines with a not-done TODO keyword are included in the output.
13945 This should be the same variable that was scoped into
13946 and set by `org-make-tags-matcher' when it constructed MATCHER.
13948 START-LEVEL can be a string with asterisks, reducing the scope to
13949 headlines matching this string."
13950 (require 'org-agenda)
13951 (let* ((re (concat "^"
13952 (if start-level
13953 ;; Get the correct level to match
13954 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13955 org-outline-regexp)
13956 " *\\(\\<\\("
13957 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13958 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13959 (props (list 'face 'default
13960 'done-face 'org-agenda-done
13961 'undone-face 'default
13962 'mouse-face 'highlight
13963 'org-not-done-regexp org-not-done-regexp
13964 'org-todo-regexp org-todo-regexp
13965 'org-complex-heading-regexp org-complex-heading-regexp
13966 'help-echo
13967 (format "mouse-2 or RET jump to org file %s"
13968 (abbreviate-file-name
13969 (or (buffer-file-name (buffer-base-buffer))
13970 (buffer-name (buffer-base-buffer)))))))
13971 (org-map-continue-from nil)
13972 lspos tags tags-list
13973 (tags-alist (list (cons 0 org-file-tags)))
13974 (llast 0) rtn rtn1 level category i txt
13975 todo marker entry priority)
13976 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13977 (setq action (list 'lambda nil action)))
13978 (save-excursion
13979 (goto-char (point-min))
13980 (when (eq action 'sparse-tree)
13981 (org-overview)
13982 (org-remove-occur-highlights))
13983 (while (let (case-fold-search)
13984 (re-search-forward re nil t))
13985 (setq org-map-continue-from nil)
13986 (catch :skip
13987 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13988 tags (if (match-end 4) (org-match-string-no-properties 4)))
13989 (goto-char (setq lspos (match-beginning 0)))
13990 (setq level (org-reduced-level (org-outline-level))
13991 category (org-get-category))
13992 (setq i llast llast level)
13993 ;; remove tag lists from same and sublevels
13994 (while (>= i level)
13995 (when (setq entry (assoc i tags-alist))
13996 (setq tags-alist (delete entry tags-alist)))
13997 (setq i (1- i)))
13998 ;; add the next tags
13999 (when tags
14000 (setq tags (org-split-string tags ":")
14001 tags-alist
14002 (cons (cons level tags) tags-alist)))
14003 ;; compile tags for current headline
14004 (setq tags-list
14005 (if org-use-tag-inheritance
14006 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14007 tags)
14008 org-scanner-tags tags-list)
14009 (when org-use-tag-inheritance
14010 (setcdr (car tags-alist)
14011 (mapcar (lambda (x)
14012 (setq x (copy-sequence x))
14013 (org-add-prop-inherited x))
14014 (cdar tags-alist))))
14015 (when (and tags org-use-tag-inheritance
14016 (or (not (eq t org-use-tag-inheritance))
14017 org-tags-exclude-from-inheritance))
14018 ;; selective inheritance, remove uninherited ones
14019 (setcdr (car tags-alist)
14020 (org-remove-uninherited-tags (cdar tags-alist))))
14021 (when (and
14023 ;; eval matcher only when the todo condition is OK
14024 (and (or (not todo-only) (member todo org-not-done-keywords))
14025 (let ((case-fold-search t) (org-trust-scanner-tags t))
14026 (eval matcher)))
14028 ;; Call the skipper, but return t if it does not skip,
14029 ;; so that the `and' form continues evaluating
14030 (progn
14031 (unless (eq action 'sparse-tree) (org-agenda-skip))
14034 ;; Check if timestamps are deselecting this entry
14035 (or (not todo-only)
14036 (and (member todo org-not-done-keywords)
14037 (or (not org-agenda-tags-todo-honor-ignore-options)
14038 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14040 ;; select this headline
14041 (cond
14042 ((eq action 'sparse-tree)
14043 (and org-highlight-sparse-tree-matches
14044 (org-get-heading) (match-end 0)
14045 (org-highlight-new-match
14046 (match-beginning 1) (match-end 1)))
14047 (org-show-context 'tags-tree))
14048 ((eq action 'agenda)
14049 (setq txt (org-agenda-format-item
14051 (concat
14052 (if (eq org-tags-match-list-sublevels 'indented)
14053 (make-string (1- level) ?.) "")
14054 (org-get-heading))
14055 level category
14056 tags-list)
14057 priority (org-get-priority txt))
14058 (goto-char lspos)
14059 (setq marker (org-agenda-new-marker))
14060 (org-add-props txt props
14061 'org-marker marker 'org-hd-marker marker 'org-category category
14062 'todo-state todo
14063 'priority priority 'type "tagsmatch")
14064 (push txt rtn))
14065 ((functionp action)
14066 (setq org-map-continue-from nil)
14067 (save-excursion
14068 (setq rtn1 (funcall action))
14069 (push rtn1 rtn)))
14070 (t (user-error "Invalid action")))
14072 ;; if we are to skip sublevels, jump to end of subtree
14073 (unless org-tags-match-list-sublevels
14074 (org-end-of-subtree t)
14075 (backward-char 1))))
14076 ;; Get the correct position from where to continue
14077 (if org-map-continue-from
14078 (goto-char org-map-continue-from)
14079 (and (= (point) lspos) (end-of-line 1)))))
14080 (when (and (eq action 'sparse-tree)
14081 (not org-sparse-tree-open-archived-trees))
14082 (org-hide-archived-subtrees (point-min) (point-max)))
14083 (nreverse rtn)))
14085 (defun org-remove-uninherited-tags (tags)
14086 "Remove all tags that are not inherited from the list TAGS."
14087 (cond
14088 ((eq org-use-tag-inheritance t)
14089 (if org-tags-exclude-from-inheritance
14090 (org-delete-all org-tags-exclude-from-inheritance tags)
14091 tags))
14092 ((not org-use-tag-inheritance) nil)
14093 ((stringp org-use-tag-inheritance)
14094 (delq nil (mapcar
14095 (lambda (x)
14096 (if (and (string-match org-use-tag-inheritance x)
14097 (not (member x org-tags-exclude-from-inheritance)))
14098 x nil))
14099 tags)))
14100 ((listp org-use-tag-inheritance)
14101 (delq nil (mapcar
14102 (lambda (x)
14103 (if (member x org-use-tag-inheritance) x nil))
14104 tags)))))
14106 (defun org-match-sparse-tree (&optional todo-only match)
14107 "Create a sparse tree according to tags string MATCH.
14108 MATCH can contain positive and negative selection of tags, like
14109 \"+WORK+URGENT-WITHBOSS\".
14110 If optional argument TODO-ONLY is non-nil, only select lines that are
14111 also TODO lines."
14112 (interactive "P")
14113 (org-agenda-prepare-buffers (list (current-buffer)))
14114 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14116 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14118 (defvar org-cached-props nil)
14119 (defun org-cached-entry-get (pom property)
14120 (if (or (eq t org-use-property-inheritance)
14121 (and (stringp org-use-property-inheritance)
14122 (string-match org-use-property-inheritance property))
14123 (and (listp org-use-property-inheritance)
14124 (member property org-use-property-inheritance)))
14125 ;; Caching is not possible, check it directly
14126 (org-entry-get pom property 'inherit)
14127 ;; Get all properties, so that we can do complicated checks easily
14128 (cdr (assoc property (or org-cached-props
14129 (setq org-cached-props
14130 (org-entry-properties pom)))))))
14132 (defun org-global-tags-completion-table (&optional files)
14133 "Return the list of all tags in all agenda buffer/files.
14134 Optional FILES argument is a list of files which can be used
14135 instead of the agenda files."
14136 (save-excursion
14137 (org-uniquify
14138 (delq nil
14139 (apply 'append
14140 (mapcar
14141 (lambda (file)
14142 (set-buffer (find-file-noselect file))
14143 (append (org-get-buffer-tags)
14144 (mapcar (lambda (x) (if (stringp (car-safe x))
14145 (list (car-safe x)) nil))
14146 org-tag-alist)))
14147 (if (and files (car files))
14148 files
14149 (org-agenda-files))))))))
14151 (defun org-make-tags-matcher (match)
14152 "Create the TAGS/TODO matcher form for the selection string MATCH.
14154 The variable `todo-only' is scoped dynamically into this function.
14155 It will be set to t if the matcher restricts matching to TODO entries,
14156 otherwise will not be touched.
14158 Returns a cons of the selection string MATCH and the constructed
14159 lisp form implementing the matcher. The matcher is to be evaluated
14160 at an Org entry, with point on the headline, and returns t if the
14161 entry matches the selection string MATCH. The returned lisp form
14162 references two variables with information about the entry, which
14163 must be bound around the form's evaluation: todo, the TODO keyword
14164 at the entry (or nil of none); and tags-list, the list of all tags
14165 at the entry including inherited ones. Additionally, the category
14166 of the entry (if any) must be specified as the text property
14167 'org-category on the headline.
14169 See also `org-scan-tags'.
14171 (declare (special todo-only))
14172 (unless (boundp 'todo-only)
14173 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14174 (unless match
14175 ;; Get a new match request, with completion against the global
14176 ;; tags table and the local tags in current buffer
14177 (let ((org-last-tags-completion-table
14178 (org-uniquify
14179 (delq nil (append (org-get-buffer-tags)
14180 (org-global-tags-completion-table))))))
14181 (setq match (org-completing-read-no-i
14182 "Match: " 'org-tags-completion-function nil nil nil
14183 'org-tags-history))))
14185 ;; Parse the string and create a lisp form
14186 (let ((match0 match)
14187 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14188 minus tag mm
14189 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14190 orterms term orlist re-p str-p level-p level-op time-p
14191 prop-p pn pv po gv rest (start 0) (ss 0))
14192 ;; Expand group tags
14193 (setq match (org-tags-expand match))
14195 ;; Check if there is a TODO part of this match, which would be the
14196 ;; part after a "/". TO make sure that this slash is not part of
14197 ;; a property value to be matched against, we also check that there
14198 ;; is no " after that slash.
14199 ;; First, find the last slash
14200 (while (string-match "/+" match ss)
14201 (setq start (match-beginning 0) ss (match-end 0)))
14202 (if (and (string-match "/+" match start)
14203 (not (save-match-data (string-match "\"" match start))))
14204 ;; match contains also a todo-matching request
14205 (progn
14206 (setq tagsmatch (substring match 0 (match-beginning 0))
14207 todomatch (substring match (match-end 0)))
14208 (if (string-match "^!" todomatch)
14209 (setq todo-only t todomatch (substring todomatch 1)))
14210 (if (string-match "^\\s-*$" todomatch)
14211 (setq todomatch nil)))
14212 ;; only matching tags
14213 (setq tagsmatch match todomatch nil))
14215 ;; Make the tags matcher
14216 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14217 (setq tagsmatcher t)
14218 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14219 (while (setq term (pop orterms))
14220 (while (and (equal (substring term -1) "\\") orterms)
14221 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14222 (while (string-match re term)
14223 (setq rest (substring term (match-end 0))
14224 minus (and (match-end 1)
14225 (equal (match-string 1 term) "-"))
14226 tag (save-match-data (replace-regexp-in-string
14227 "\\\\-" "-"
14228 (match-string 2 term)))
14229 re-p (equal (string-to-char tag) ?{)
14230 level-p (match-end 4)
14231 prop-p (match-end 5)
14232 mm (cond
14233 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14234 (level-p
14235 (setq level-op (org-op-to-function (match-string 3 term)))
14236 `(,level-op level ,(string-to-number
14237 (match-string 4 term))))
14238 (prop-p
14239 (setq pn (match-string 5 term)
14240 po (match-string 6 term)
14241 pv (match-string 7 term)
14242 re-p (equal (string-to-char pv) ?{)
14243 str-p (equal (string-to-char pv) ?\")
14244 time-p (save-match-data
14245 (string-match "^\"[[<].*[]>]\"$" pv))
14246 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14247 (if time-p (setq pv (org-matcher-time pv)))
14248 (setq po (org-op-to-function po (if time-p 'time str-p)))
14249 (cond
14250 ((equal pn "CATEGORY")
14251 (setq gv '(get-text-property (point) 'org-category)))
14252 ((equal pn "TODO")
14253 (setq gv 'todo))
14255 (setq gv `(org-cached-entry-get nil ,pn))))
14256 (if re-p
14257 (if (eq po 'org<>)
14258 `(not (string-match ,pv (or ,gv "")))
14259 `(string-match ,pv (or ,gv "")))
14260 (if str-p
14261 `(,po (or ,gv "") ,pv)
14262 `(,po (string-to-number (or ,gv ""))
14263 ,(string-to-number pv) ))))
14264 (t `(member ,tag tags-list)))
14265 mm (if minus (list 'not mm) mm)
14266 term rest)
14267 (push mm tagsmatcher))
14268 (push (if (> (length tagsmatcher) 1)
14269 (cons 'and tagsmatcher)
14270 (car tagsmatcher))
14271 orlist)
14272 (setq tagsmatcher nil))
14273 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14274 (setq tagsmatcher
14275 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14276 ;; Make the todo matcher
14277 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14278 (setq todomatcher t)
14279 (setq orterms (org-split-string todomatch "|") orlist nil)
14280 (while (setq term (pop orterms))
14281 (while (string-match re term)
14282 (setq minus (and (match-end 1)
14283 (equal (match-string 1 term) "-"))
14284 kwd (match-string 2 term)
14285 re-p (equal (string-to-char kwd) ?{)
14286 term (substring term (match-end 0))
14287 mm (if re-p
14288 `(string-match ,(substring kwd 1 -1) todo)
14289 (list 'equal 'todo kwd))
14290 mm (if minus (list 'not mm) mm))
14291 (push mm todomatcher))
14292 (push (if (> (length todomatcher) 1)
14293 (cons 'and todomatcher)
14294 (car todomatcher))
14295 orlist)
14296 (setq todomatcher nil))
14297 (setq todomatcher (if (> (length orlist) 1)
14298 (cons 'or orlist) (car orlist))))
14300 ;; Return the string and lisp forms of the matcher
14301 (setq matcher (if todomatcher
14302 (list 'and tagsmatcher todomatcher)
14303 tagsmatcher))
14304 (when todo-only
14305 (setq matcher (list 'and '(member todo org-not-done-keywords)
14306 matcher)))
14307 (cons match0 matcher)))
14309 (defun org-tags-expand (match &optional single-as-list downcased)
14310 "Expand group tags in MATCH.
14312 This replaces every group tag in MATCH with a regexp tag search.
14313 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14314 will be replaced like this:
14316 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14317 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14318 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14320 Replacing by a regexp preserves the structure of the match.
14321 E.g., this expansion
14323 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14325 will match anything tagged with \"Lab\" and \"Home\", or tagged
14326 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14328 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14329 assumed to be a single group tag, and the function will return
14330 the list of tags in this group.
14332 When DOWNCASE is non-nil, expand downcased TAGS."
14333 (if org-group-tags
14334 (let* ((case-fold-search t)
14335 (stable org-mode-syntax-table)
14336 (tal (or org-tag-groups-alist-for-agenda
14337 org-tag-groups-alist))
14338 (tal (if downcased
14339 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14340 (tml (mapcar 'car tal))
14341 (rtnmatch match) rpl)
14342 ;; @ and _ are allowed as word-components in tags
14343 (modify-syntax-entry ?@ "w" stable)
14344 (modify-syntax-entry ?_ "w" stable)
14345 (while (and tml
14346 (with-syntax-table stable
14347 (string-match
14348 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14349 (regexp-opt tml) "\\>\\)") rtnmatch)))
14350 (let* ((dir (match-string 1 rtnmatch))
14351 (tag (match-string 2 rtnmatch))
14352 (tag (if downcased (downcase tag) tag)))
14353 (setq tml (delete tag tml))
14354 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14355 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14356 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14357 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14358 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14359 (if single-as-list
14360 (or (reverse rpl) (list rtnmatch))
14361 rtnmatch))
14362 (if single-as-list (list (if downcased (downcase match) match))
14363 match)))
14365 (defun org-op-to-function (op &optional stringp)
14366 "Turn an operator into the appropriate function."
14367 (setq op
14368 (cond
14369 ((equal op "<" ) '(< string< org-time<))
14370 ((equal op ">" ) '(> org-string> org-time>))
14371 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14372 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14373 ((member op '("=" "==")) '(= string= org-time=))
14374 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14375 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14377 (defun org<> (a b) (not (= a b)))
14378 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14379 (defun org-string>= (a b) (not (string< a b)))
14380 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14381 (defun org-string<> (a b) (not (string= a b)))
14382 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14383 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14384 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14385 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14386 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14387 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14388 (defun org-2ft (s)
14389 "Convert S to a floating point time.
14390 If S is already a number, just return it. If it is a string, parse
14391 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14392 (cond
14393 ((numberp s) s)
14394 ((stringp s)
14395 (condition-case nil
14396 (float-time (apply 'encode-time (org-parse-time-string s)))
14397 (error 0.)))
14398 (t 0.)))
14400 (defun org-time-today ()
14401 "Time in seconds today at 0:00.
14402 Returns the float number of seconds since the beginning of the
14403 epoch to the beginning of today (00:00)."
14404 (float-time (apply 'encode-time
14405 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14407 (defun org-matcher-time (s)
14408 "Interpret a time comparison value."
14409 (save-match-data
14410 (cond
14411 ((string= s "<now>") (float-time))
14412 ((string= s "<today>") (org-time-today))
14413 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14414 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14415 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14416 (+ (org-time-today)
14417 (* (string-to-number (match-string 1 s))
14418 (cdr (assoc (match-string 2 s)
14419 '(("d" . 86400.0) ("w" . 604800.0)
14420 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14421 (t (org-2ft s)))))
14423 (defun org-match-any-p (re list)
14424 "Does re match any element of list?"
14425 (setq list (mapcar (lambda (x) (string-match re x)) list))
14426 (delq nil list))
14428 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14429 (defvar org-tags-overlay (make-overlay 1 1))
14430 (org-detach-overlay org-tags-overlay)
14432 (defun org-get-local-tags-at (&optional pos)
14433 "Get a list of tags defined in the current headline."
14434 (org-get-tags-at pos 'local))
14436 (defun org-get-local-tags ()
14437 "Get a list of tags defined in the current headline."
14438 (org-get-tags-at nil 'local))
14440 (defun org-get-tags-at (&optional pos local)
14441 "Get a list of all headline tags applicable at POS.
14442 POS defaults to point. If tags are inherited, the list contains
14443 the targets in the same sequence as the headlines appear, i.e.
14444 the tags of the current headline come last.
14445 When LOCAL is non-nil, only return tags from the current headline,
14446 ignore inherited ones."
14447 (interactive)
14448 (if (and org-trust-scanner-tags
14449 (or (not pos) (equal pos (point)))
14450 (not local))
14451 org-scanner-tags
14452 (let (tags ltags lastpos parent)
14453 (save-excursion
14454 (save-restriction
14455 (widen)
14456 (goto-char (or pos (point)))
14457 (save-match-data
14458 (catch 'done
14459 (condition-case nil
14460 (progn
14461 (org-back-to-heading t)
14462 (while (not (equal lastpos (point)))
14463 (setq lastpos (point))
14464 (when (looking-at
14465 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14466 (setq ltags (org-split-string
14467 (org-match-string-no-properties 1) ":"))
14468 (when parent
14469 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14470 (setq tags (append
14471 (if parent
14472 (org-remove-uninherited-tags ltags)
14473 ltags)
14474 tags)))
14475 (or org-use-tag-inheritance (throw 'done t))
14476 (if local (throw 'done t))
14477 (or (org-up-heading-safe) (error nil))
14478 (setq parent t)))
14479 (error nil)))))
14480 (if local
14481 tags
14482 (reverse (delete-dups
14483 (reverse (append
14484 (org-remove-uninherited-tags
14485 org-file-tags) tags)))))))))
14487 (defun org-add-prop-inherited (s)
14488 (add-text-properties 0 (length s) '(inherited t) s)
14491 (defun org-toggle-tag (tag &optional onoff)
14492 "Toggle the tag TAG for the current line.
14493 If ONOFF is `on' or `off', don't toggle but set to this state."
14494 (let (res current)
14495 (save-excursion
14496 (org-back-to-heading t)
14497 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14498 (point-at-eol) t)
14499 (progn
14500 (setq current (match-string 1))
14501 (replace-match ""))
14502 (setq current ""))
14503 (setq current (nreverse (org-split-string current ":")))
14504 (cond
14505 ((eq onoff 'on)
14506 (setq res t)
14507 (or (member tag current) (push tag current)))
14508 ((eq onoff 'off)
14509 (or (not (member tag current)) (setq current (delete tag current))))
14510 (t (if (member tag current)
14511 (setq current (delete tag current))
14512 (setq res t)
14513 (push tag current))))
14514 (end-of-line 1)
14515 (if current
14516 (progn
14517 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14518 (org-set-tags nil t))
14519 (delete-horizontal-space))
14520 (run-hooks 'org-after-tags-change-hook))
14521 res))
14523 (defun org-align-tags-here (to-col)
14524 ;; Assumes that this is a headline
14525 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14526 (beginning-of-line 1)
14527 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14528 (< pos (match-beginning 2)))
14529 (progn
14530 (setq tags-l (- (match-end 2) (match-beginning 2)))
14531 (goto-char (match-beginning 1))
14532 (insert " ")
14533 (delete-region (point) (1+ (match-beginning 2)))
14534 (setq ncol (max (current-column)
14535 (1+ col)
14536 (if (> to-col 0)
14537 to-col
14538 (- (abs to-col) tags-l))))
14539 (setq p (point))
14540 (insert (make-string (- ncol (current-column)) ?\ ))
14541 (setq ncol (current-column))
14542 (when indent-tabs-mode (tabify p (point-at-eol)))
14543 (org-move-to-column (min ncol col) t nil t))
14544 (goto-char pos))))
14546 (defun org-set-tags-command (&optional arg just-align)
14547 "Call the set-tags command for the current entry."
14548 (interactive "P")
14549 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14550 (org-set-tags arg just-align)
14551 (save-excursion
14552 (unless (and (org-region-active-p)
14553 org-loop-over-headlines-in-active-region)
14554 (org-back-to-heading t))
14555 (org-set-tags arg just-align))))
14557 (defun org-set-tags-to (data)
14558 "Set the tags of the current entry to DATA, replacing the current tags.
14559 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14560 If DATA is nil or the empty string, any tags will be removed."
14561 (interactive "sTags: ")
14562 (setq data
14563 (cond
14564 ((eq data nil) "")
14565 ((equal data "") "")
14566 ((stringp data)
14567 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14568 ":"))
14569 ((listp data)
14570 (concat ":" (mapconcat 'identity data ":") ":"))))
14571 (when data
14572 (save-excursion
14573 (org-back-to-heading t)
14574 (when (looking-at org-complex-heading-regexp)
14575 (if (match-end 5)
14576 (progn
14577 (goto-char (match-beginning 5))
14578 (insert data)
14579 (delete-region (point) (point-at-eol))
14580 (org-set-tags nil 'align))
14581 (goto-char (point-at-eol))
14582 (insert " " data)
14583 (org-set-tags nil 'align)))
14584 (beginning-of-line 1)
14585 (if (looking-at ".*?\\([ \t]+\\)$")
14586 (delete-region (match-beginning 1) (match-end 1))))))
14588 (defun org-align-all-tags ()
14589 "Align the tags i all headings."
14590 (interactive)
14591 (save-excursion
14592 (or (ignore-errors (org-back-to-heading t))
14593 (outline-next-heading))
14594 (if (org-at-heading-p)
14595 (org-set-tags t)
14596 (message "No headings"))))
14598 (defvar org-indent-indentation-per-level)
14599 (defun org-set-tags (&optional arg just-align)
14600 "Set the tags for the current headline.
14601 With prefix ARG, realign all tags in headings in the current buffer.
14602 When JUST-ALIGN is non-nil, only align tags.
14603 When JUST-ALIGN is 'ignore-column, align tags without trying to set
14604 the column by ignoring invisible text."
14605 (interactive "P")
14606 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14607 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14608 'region-start-level 'region))
14609 org-loop-over-headlines-in-active-region)
14610 (org-map-entries
14611 ;; We don't use ARG and JUST-ALIGN here because these args
14612 ;; are not useful when looping over headlines.
14613 `(org-set-tags)
14614 org-loop-over-headlines-in-active-region
14615 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14616 (let* ((re org-outline-regexp-bol)
14617 (current (unless arg (org-get-tags-string)))
14618 (col (current-column))
14619 (org-setting-tags t)
14620 table current-tags inherited-tags ; computed below when needed
14621 tags p0 c0 c1 rpl di tc level)
14622 (if arg
14623 (save-excursion
14624 (goto-char (point-min))
14625 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14626 (while (re-search-forward re nil t)
14627 (org-set-tags nil t)
14628 (end-of-line 1)))
14629 (message "All tags realigned to column %d" org-tags-column))
14630 (if just-align
14631 (setq tags current)
14632 ;; Get a new set of tags from the user
14633 (save-excursion
14634 (setq table (append org-tag-persistent-alist
14635 (or org-tag-alist (org-get-buffer-tags))
14636 (and
14637 org-complete-tags-always-offer-all-agenda-tags
14638 (org-global-tags-completion-table
14639 (org-agenda-files))))
14640 org-last-tags-completion-table table
14641 current-tags (org-split-string current ":")
14642 inherited-tags (nreverse
14643 (nthcdr (length current-tags)
14644 (nreverse (org-get-tags-at))))
14645 tags
14646 (if (or (eq t org-use-fast-tag-selection)
14647 (and org-use-fast-tag-selection
14648 (delq nil (mapcar 'cdr table))))
14649 (org-fast-tag-selection
14650 current-tags inherited-tags table
14651 (if org-fast-tag-selection-include-todo
14652 org-todo-key-alist))
14653 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14654 (org-trim
14655 (org-icompleting-read "Tags: "
14656 'org-tags-completion-function
14657 nil nil current 'org-tags-history))))))
14658 (while (string-match "[-+&]+" tags)
14659 ;; No boolean logic, just a list
14660 (setq tags (replace-match ":" t t tags))))
14662 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14664 (if org-tags-sort-function
14665 (setq tags (mapconcat 'identity
14666 (sort (org-split-string
14667 tags (org-re "[^[:alnum:]_@#%]+"))
14668 org-tags-sort-function) ":")))
14670 (if (string-match "\\`[\t ]*\\'" tags)
14671 (setq tags "")
14672 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14673 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14675 ;; Insert new tags at the correct column
14676 (beginning-of-line 1)
14677 (setq level (or (and (looking-at org-outline-regexp)
14678 (- (match-end 0) (point) 1))
14680 (cond
14681 ((and (equal current "") (equal tags "")))
14682 ((re-search-forward
14683 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14684 (point-at-eol) t)
14685 (if (equal tags "")
14686 (setq rpl "")
14687 (goto-char (match-beginning 0))
14688 (setq c0 (current-column)
14689 ;; compute offset for the case of org-indent-mode active
14690 di (if (org-bound-and-true-p org-indent-mode)
14691 (* (1- org-indent-indentation-per-level) (1- level))
14693 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14694 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14695 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14696 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14697 (replace-match rpl t t)
14698 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14699 tags)
14700 (t (error "Tags alignment failed")))
14701 (org-move-to-column col nil nil (not (eq just-align 'ignore-column)))
14702 (unless just-align
14703 (run-hooks 'org-after-tags-change-hook))))))
14705 (defun org-change-tag-in-region (beg end tag off)
14706 "Add or remove TAG for each entry in the region.
14707 This works in the agenda, and also in an org-mode buffer."
14708 (interactive
14709 (list (region-beginning) (region-end)
14710 (let ((org-last-tags-completion-table
14711 (if (derived-mode-p 'org-mode)
14712 (org-uniquify
14713 (delq nil (append (org-get-buffer-tags)
14714 (org-global-tags-completion-table))))
14715 (org-global-tags-completion-table))))
14716 (org-icompleting-read
14717 "Tag: " 'org-tags-completion-function nil nil nil
14718 'org-tags-history))
14719 (progn
14720 (message "[s]et or [r]emove? ")
14721 (equal (read-char-exclusive) ?r))))
14722 (if (fboundp 'deactivate-mark) (deactivate-mark))
14723 (let ((agendap (equal major-mode 'org-agenda-mode))
14724 l1 l2 m buf pos newhead (cnt 0))
14725 (goto-char end)
14726 (setq l2 (1- (org-current-line)))
14727 (goto-char beg)
14728 (setq l1 (org-current-line))
14729 (loop for l from l1 to l2 do
14730 (org-goto-line l)
14731 (setq m (get-text-property (point) 'org-hd-marker))
14732 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14733 (and agendap m))
14734 (setq buf (if agendap (marker-buffer m) (current-buffer))
14735 pos (if agendap m (point)))
14736 (with-current-buffer buf
14737 (save-excursion
14738 (save-restriction
14739 (goto-char pos)
14740 (setq cnt (1+ cnt))
14741 (org-toggle-tag tag (if off 'off 'on))
14742 (setq newhead (org-get-heading)))))
14743 (and agendap (org-agenda-change-all-lines newhead m))))
14744 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14746 (defun org-tags-completion-function (string predicate &optional flag)
14747 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14748 (confirm (lambda (x) (stringp (car x)))))
14749 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14750 (setq s1 (match-string 1 string)
14751 s2 (match-string 2 string))
14752 (setq s1 "" s2 string))
14753 (cond
14754 ((eq flag nil)
14755 ;; try completion
14756 (setq rtn (try-completion s2 ctable confirm))
14757 (if (stringp rtn)
14758 (setq rtn
14759 (concat s1 s2 (substring rtn (length s2))
14760 (if (and org-add-colon-after-tag-completion
14761 (assoc rtn ctable))
14762 ":" ""))))
14763 rtn)
14764 ((eq flag t)
14765 ;; all-completions
14766 (all-completions s2 ctable confirm))
14767 ((eq flag 'lambda)
14768 ;; exact match?
14769 (assoc s2 ctable)))))
14771 (defun org-fast-tag-insert (kwd tags face &optional end)
14772 "Insert KDW, and the TAGS, the latter with face FACE.
14773 Also insert END."
14774 (insert (format "%-12s" (concat kwd ":"))
14775 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14776 (or end "")))
14778 (defun org-fast-tag-show-exit (flag)
14779 (save-excursion
14780 (org-goto-line 3)
14781 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14782 (replace-match ""))
14783 (when flag
14784 (end-of-line 1)
14785 (org-move-to-column (- (window-width) 19) t)
14786 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14788 (defun org-set-current-tags-overlay (current prefix)
14789 "Add an overlay to CURRENT tag with PREFIX."
14790 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14791 (if (featurep 'xemacs)
14792 (org-overlay-display org-tags-overlay (concat prefix s)
14793 'secondary-selection)
14794 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14795 (org-overlay-display org-tags-overlay (concat prefix s)))))
14797 (defvar org-last-tag-selection-key nil)
14798 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14799 "Fast tag selection with single keys.
14800 CURRENT is the current list of tags in the headline, INHERITED is the
14801 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14802 possibly with grouping information. TODO-TABLE is a similar table with
14803 TODO keywords, should these have keys assigned to them.
14804 If the keys are nil, a-z are automatically assigned.
14805 Returns the new tags string, or nil to not change the current settings."
14806 (let* ((fulltable (append table todo-table))
14807 (maxlen (apply 'max (mapcar
14808 (lambda (x)
14809 (if (stringp (car x)) (string-width (car x)) 0))
14810 fulltable)))
14811 (buf (current-buffer))
14812 (expert (eq org-fast-tag-selection-single-key 'expert))
14813 (buffer-tags nil)
14814 (fwidth (+ maxlen 3 1 3))
14815 (ncol (/ (- (window-width) 4) fwidth))
14816 (i-face 'org-done)
14817 (c-face 'org-todo)
14818 tg cnt e c char c1 c2 ntable tbl rtn
14819 ov-start ov-end ov-prefix
14820 (exit-after-next org-fast-tag-selection-single-key)
14821 (done-keywords org-done-keywords)
14822 groups ingroup)
14823 (save-excursion
14824 (beginning-of-line 1)
14825 (if (looking-at
14826 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14827 (setq ov-start (match-beginning 1)
14828 ov-end (match-end 1)
14829 ov-prefix "")
14830 (setq ov-start (1- (point-at-eol))
14831 ov-end (1+ ov-start))
14832 (skip-chars-forward "^\n\r")
14833 (setq ov-prefix
14834 (concat
14835 (buffer-substring (1- (point)) (point))
14836 (if (> (current-column) org-tags-column)
14838 (make-string (- org-tags-column (current-column)) ?\ ))))))
14839 (move-overlay org-tags-overlay ov-start ov-end)
14840 (save-window-excursion
14841 (if expert
14842 (set-buffer (get-buffer-create " *Org tags*"))
14843 (delete-other-windows)
14844 (split-window-vertically)
14845 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14846 (erase-buffer)
14847 (org-set-local 'org-done-keywords done-keywords)
14848 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14849 (org-fast-tag-insert "Current" current c-face "\n\n")
14850 (org-fast-tag-show-exit exit-after-next)
14851 (org-set-current-tags-overlay current ov-prefix)
14852 (setq tbl fulltable char ?a cnt 0)
14853 (while (setq e (pop tbl))
14854 (cond
14855 ((equal (car e) :startgroup)
14856 (push '() groups) (setq ingroup t)
14857 (when (not (= cnt 0))
14858 (setq cnt 0)
14859 (insert "\n"))
14860 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14861 ((equal (car e) :endgroup)
14862 (setq ingroup nil cnt 0)
14863 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14864 ((equal e '(:newline))
14865 (when (not (= cnt 0))
14866 (setq cnt 0)
14867 (insert "\n")
14868 (setq e (car tbl))
14869 (while (equal (car tbl) '(:newline))
14870 (insert "\n")
14871 (setq tbl (cdr tbl)))))
14872 ((equal e '(:grouptags)) nil)
14874 (setq tg (copy-sequence (car e)) c2 nil)
14875 (if (cdr e)
14876 (setq c (cdr e))
14877 ;; automatically assign a character.
14878 (setq c1 (string-to-char
14879 (downcase (substring
14880 tg (if (= (string-to-char tg) ?@) 1 0)))))
14881 (if (or (rassoc c1 ntable) (rassoc c1 table))
14882 (while (or (rassoc char ntable) (rassoc char table))
14883 (setq char (1+ char)))
14884 (setq c2 c1))
14885 (setq c (or c2 char)))
14886 (if ingroup (push tg (car groups)))
14887 (setq tg (org-add-props tg nil 'face
14888 (cond
14889 ((not (assoc tg table))
14890 (org-get-todo-face tg))
14891 ((member tg current) c-face)
14892 ((member tg inherited) i-face))))
14893 (if (equal (caar tbl) :grouptags)
14894 (org-add-props tg nil 'face 'org-tag-group))
14895 (if (and (= cnt 0) (not ingroup)) (insert " "))
14896 (insert "[" c "] " tg (make-string
14897 (- fwidth 4 (length tg)) ?\ ))
14898 (push (cons tg c) ntable)
14899 (when (= (setq cnt (1+ cnt)) ncol)
14900 (insert "\n")
14901 (if ingroup (insert " "))
14902 (setq cnt 0)))))
14903 (setq ntable (nreverse ntable))
14904 (insert "\n")
14905 (goto-char (point-min))
14906 (if (not expert) (org-fit-window-to-buffer))
14907 (setq rtn
14908 (catch 'exit
14909 (while t
14910 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14911 (if (not groups) "no " "")
14912 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14913 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14914 (setq org-last-tag-selection-key c)
14915 (cond
14916 ((= c ?\r) (throw 'exit t))
14917 ((= c ?!)
14918 (setq groups (not groups))
14919 (goto-char (point-min))
14920 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14921 ((= c ?\C-c)
14922 (if (not expert)
14923 (org-fast-tag-show-exit
14924 (setq exit-after-next (not exit-after-next)))
14925 (setq expert nil)
14926 (delete-other-windows)
14927 (set-window-buffer (split-window-vertically) " *Org tags*")
14928 (org-switch-to-buffer-other-window " *Org tags*")
14929 (org-fit-window-to-buffer)))
14930 ((or (= c ?\C-g)
14931 (and (= c ?q) (not (rassoc c ntable))))
14932 (org-detach-overlay org-tags-overlay)
14933 (setq quit-flag t))
14934 ((= c ?\ )
14935 (setq current nil)
14936 (if exit-after-next (setq exit-after-next 'now)))
14937 ((= c ?\t)
14938 (condition-case nil
14939 (setq tg (org-icompleting-read
14940 "Tag: "
14941 (or buffer-tags
14942 (with-current-buffer buf
14943 (org-get-buffer-tags)))))
14944 (quit (setq tg "")))
14945 (when (string-match "\\S-" tg)
14946 (add-to-list 'buffer-tags (list tg))
14947 (if (member tg current)
14948 (setq current (delete tg current))
14949 (push tg current)))
14950 (if exit-after-next (setq exit-after-next 'now)))
14951 ((setq e (rassoc c todo-table) tg (car e))
14952 (with-current-buffer buf
14953 (save-excursion (org-todo tg)))
14954 (if exit-after-next (setq exit-after-next 'now)))
14955 ((setq e (rassoc c ntable) tg (car e))
14956 (if (member tg current)
14957 (setq current (delete tg current))
14958 (loop for g in groups do
14959 (if (member tg g)
14960 (mapc (lambda (x)
14961 (setq current (delete x current)))
14962 g)))
14963 (push tg current))
14964 (if exit-after-next (setq exit-after-next 'now))))
14966 ;; Create a sorted list
14967 (setq current
14968 (sort current
14969 (lambda (a b)
14970 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14971 (if (eq exit-after-next 'now) (throw 'exit t))
14972 (goto-char (point-min))
14973 (beginning-of-line 2)
14974 (delete-region (point) (point-at-eol))
14975 (org-fast-tag-insert "Current" current c-face)
14976 (org-set-current-tags-overlay current ov-prefix)
14977 (while (re-search-forward
14978 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14979 (setq tg (match-string 1))
14980 (add-text-properties
14981 (match-beginning 1) (match-end 1)
14982 (list 'face
14983 (cond
14984 ((member tg current) c-face)
14985 ((member tg inherited) i-face)
14986 (t (get-text-property (match-beginning 1) 'face))))))
14987 (goto-char (point-min)))))
14988 (org-detach-overlay org-tags-overlay)
14989 (if rtn
14990 (mapconcat 'identity current ":")
14991 nil))))
14993 (defun org-get-tags-string ()
14994 "Get the TAGS string in the current headline."
14995 (unless (org-at-heading-p t)
14996 (user-error "Not on a heading"))
14997 (save-excursion
14998 (beginning-of-line 1)
14999 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15000 (org-match-string-no-properties 1)
15001 "")))
15003 (defun org-get-tags ()
15004 "Get the list of tags specified in the current headline."
15005 (org-split-string (org-get-tags-string) ":"))
15007 (defun org-get-buffer-tags ()
15008 "Get a table of all tags used in the buffer, for completion."
15009 (let (tags)
15010 (save-excursion
15011 (goto-char (point-min))
15012 (while (re-search-forward
15013 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
15014 (when (equal (char-after (point-at-bol 0)) ?*)
15015 (mapc (lambda (x) (add-to-list 'tags x))
15016 (org-split-string (org-match-string-no-properties 1) ":")))))
15017 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
15018 (mapcar 'list tags)))
15020 ;;;; The mapping API
15022 (defun org-map-entries (func &optional match scope &rest skip)
15023 "Call FUNC at each headline selected by MATCH in SCOPE.
15025 FUNC is a function or a lisp form. The function will be called without
15026 arguments, with the cursor positioned at the beginning of the headline.
15027 The return values of all calls to the function will be collected and
15028 returned as a list.
15030 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15031 does not need to preserve point. After evaluation, the cursor will be
15032 moved to the end of the line (presumably of the headline of the
15033 processed entry) and search continues from there. Under some
15034 circumstances, this may not produce the wanted results. For example,
15035 if you have removed (e.g. archived) the current (sub)tree it could
15036 mean that the next entry will be skipped entirely. In such cases, you
15037 can specify the position from where search should continue by making
15038 FUNC set the variable `org-map-continue-from' to the desired buffer
15039 position.
15041 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15042 Only headlines that are matched by this query will be considered during
15043 the iteration. When MATCH is nil or t, all headlines will be
15044 visited by the iteration.
15046 SCOPE determines the scope of this command. It can be any of:
15048 nil The current buffer, respecting the restriction if any
15049 tree The subtree started with the entry at point
15050 region The entries within the active region, if any
15051 region-start-level
15052 The entries within the active region, but only those at
15053 the same level than the first one.
15054 file The current buffer, without restriction
15055 file-with-archives
15056 The current buffer, and any archives associated with it
15057 agenda All agenda files
15058 agenda-with-archives
15059 All agenda files with any archive files associated with them
15060 \(file1 file2 ...)
15061 If this is a list, all files in the list will be scanned
15063 The remaining args are treated as settings for the skipping facilities of
15064 the scanner. The following items can be given here:
15066 archive skip trees with the archive tag
15067 comment skip trees with the COMMENT keyword
15068 function or Emacs Lisp form:
15069 will be used as value for `org-agenda-skip-function', so
15070 whenever the function returns a position, FUNC will not be
15071 called for that entry and search will continue from the
15072 position returned
15074 If your function needs to retrieve the tags including inherited tags
15075 at the *current* entry, you can use the value of the variable
15076 `org-scanner-tags' which will be much faster than getting the value
15077 with `org-get-tags-at'. If your function gets properties with
15078 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15079 to t around the call to `org-entry-properties' to get the same speedup.
15080 Note that if your function moves around to retrieve tags and properties at
15081 a *different* entry, you cannot use these techniques."
15082 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15083 (not (org-region-active-p)))
15084 (let* ((org-agenda-archives-mode nil) ; just to make sure
15085 (org-agenda-skip-archived-trees (memq 'archive skip))
15086 (org-agenda-skip-comment-trees (memq 'comment skip))
15087 (org-agenda-skip-function
15088 (car (org-delete-all '(comment archive) skip)))
15089 (org-tags-match-list-sublevels t)
15090 (start-level (eq scope 'region-start-level))
15091 matcher file res
15092 org-todo-keywords-for-agenda
15093 org-done-keywords-for-agenda
15094 org-todo-keyword-alist-for-agenda
15095 org-tag-alist-for-agenda
15096 todo-only)
15098 (cond
15099 ((eq match t) (setq matcher t))
15100 ((eq match nil) (setq matcher t))
15101 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15103 (save-window-excursion
15104 (save-restriction
15105 (cond ((eq scope 'tree)
15106 (org-back-to-heading t)
15107 (org-narrow-to-subtree)
15108 (setq scope nil))
15109 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15110 (org-region-active-p))
15111 ;; If needed, set start-level to a string like "2"
15112 (when start-level
15113 (save-excursion
15114 (goto-char (region-beginning))
15115 (unless (org-at-heading-p) (outline-next-heading))
15116 (setq start-level (org-current-level))))
15117 (narrow-to-region (region-beginning)
15118 (save-excursion
15119 (goto-char (region-end))
15120 (unless (and (bolp) (org-at-heading-p))
15121 (outline-next-heading))
15122 (point)))
15123 (setq scope nil)))
15125 (if (not scope)
15126 (progn
15127 (org-agenda-prepare-buffers
15128 (list (buffer-file-name (current-buffer))))
15129 (setq res (org-scan-tags func matcher todo-only start-level)))
15130 ;; Get the right scope
15131 (cond
15132 ((and scope (listp scope) (symbolp (car scope)))
15133 (setq scope (eval scope)))
15134 ((eq scope 'agenda)
15135 (setq scope (org-agenda-files t)))
15136 ((eq scope 'agenda-with-archives)
15137 (setq scope (org-agenda-files t))
15138 (setq scope (org-add-archive-files scope)))
15139 ((eq scope 'file)
15140 (setq scope (list (buffer-file-name))))
15141 ((eq scope 'file-with-archives)
15142 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15143 (org-agenda-prepare-buffers scope)
15144 (while (setq file (pop scope))
15145 (with-current-buffer (org-find-base-buffer-visiting file)
15146 (save-excursion
15147 (save-restriction
15148 (widen)
15149 (goto-char (point-min))
15150 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15151 res)))
15153 ;;;; Properties
15155 ;;; Setting and retrieving properties
15157 (defconst org-special-properties
15158 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15159 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15160 "The special properties valid in Org-mode.
15162 These are properties that are not defined in the property drawer,
15163 but in some other way.")
15165 (defconst org-default-properties
15166 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15167 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15168 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15169 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15170 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15171 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15172 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15173 "Some properties that are used by Org-mode for various purposes.
15174 Being in this list makes sure that they are offered for completion.")
15176 (defun org-property-action ()
15177 "Do an action on properties."
15178 (interactive)
15179 (let (c)
15180 (org-at-property-p)
15181 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15182 (setq c (read-char-exclusive))
15183 (cond
15184 ((equal c ?s)
15185 (call-interactively 'org-set-property))
15186 ((equal c ?d)
15187 (call-interactively 'org-delete-property))
15188 ((equal c ?D)
15189 (call-interactively 'org-delete-property-globally))
15190 ((equal c ?c)
15191 (call-interactively 'org-compute-property-at-point))
15192 (t (user-error "No such property action %c" c)))))
15194 (defun org-inc-effort ()
15195 "Increment the value of the effort property in the current entry."
15196 (interactive)
15197 (org-set-effort nil t))
15199 (defvar org-clock-effort) ;; Defined in org-clock.el
15200 (defvar org-clock-current-task) ;; Defined in org-clock.el
15201 (defun org-set-effort (&optional value increment)
15202 "Set the effort property of the current entry.
15203 With numerical prefix arg, use the nth allowed value, 0 stands for the
15204 10th allowed value.
15206 When INCREMENT is non-nil, set the property to the next allowed value."
15207 (interactive "P")
15208 (if (equal value 0) (setq value 10))
15209 (let* ((completion-ignore-case t)
15210 (prop org-effort-property)
15211 (cur (org-entry-get nil prop))
15212 (allowed (org-property-get-allowed-values nil prop 'table))
15213 (existing (mapcar 'list (org-property-values prop)))
15214 (heading (nth 4 (org-heading-components)))
15216 (val (cond
15217 ((stringp value) value)
15218 ((and allowed (integerp value))
15219 (or (car (nth (1- value) allowed))
15220 (car (org-last allowed))))
15221 ((and allowed increment)
15222 (or (caadr (member (list cur) allowed))
15223 (user-error "Allowed effort values are not set")))
15224 (allowed
15225 (message "Select 1-9,0, [RET%s]: %s"
15226 (if cur (concat "=" cur) "")
15227 (mapconcat 'car allowed " "))
15228 (setq rpl (read-char-exclusive))
15229 (if (equal rpl ?\r)
15231 (setq rpl (- rpl ?0))
15232 (if (equal rpl 0) (setq rpl 10))
15233 (if (and (> rpl 0) (<= rpl (length allowed)))
15234 (car (nth (1- rpl) allowed))
15235 (org-completing-read "Effort: " allowed nil))))
15237 (let (org-completion-use-ido org-completion-use-iswitchb)
15238 (org-completing-read
15239 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15240 (concat "[" cur "]") "")
15241 ": ")
15242 existing nil nil "" nil cur))))))
15243 (unless (equal (org-entry-get nil prop) val)
15244 (org-entry-put nil prop val))
15245 (save-excursion
15246 (org-back-to-heading t)
15247 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15248 (when (string= heading org-clock-current-task)
15249 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15250 (org-clock-update-mode-line))
15251 (message "%s is now %s" prop val)))
15253 (defun org-at-property-p ()
15254 "Is cursor inside a property drawer?"
15255 (save-excursion
15256 (when (equal 'node-property (car (org-element-at-point)))
15257 (beginning-of-line 1)
15258 (looking-at org-property-re))))
15260 (defun org-get-property-block (&optional beg end force)
15261 "Return the (beg . end) range of the body of the property drawer.
15262 BEG and END are the beginning and end of the current subtree, or of
15263 the part before the first headline. If they are not given, they will
15264 be found. If the drawer does not exist and FORCE is non-nil, create
15265 the drawer."
15266 (catch 'exit
15267 (save-excursion
15268 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15269 (progn (org-back-to-heading t) (point))))
15270 (end (or end (and (not (outline-next-heading)) (point-max))
15271 (point))))
15272 (goto-char beg)
15273 (if (re-search-forward org-property-start-re end t)
15274 (setq beg (1+ (match-end 0)))
15275 (if force
15276 (save-excursion
15277 (org-insert-property-drawer)
15278 (setq end (progn (outline-next-heading) (point))))
15279 (throw 'exit nil))
15280 (goto-char beg)
15281 (if (re-search-forward org-property-start-re end t)
15282 (setq beg (1+ (match-end 0)))))
15283 (if (re-search-forward org-property-end-re end t)
15284 (setq end (match-beginning 0))
15285 (or force (throw 'exit nil))
15286 (goto-char beg)
15287 (setq end beg)
15288 (org-indent-line)
15289 (insert ":END:\n"))
15290 (cons beg end)))))
15292 (defun org-entry-properties (&optional pom which specific)
15293 "Get all properties of the entry at point-or-marker POM.
15294 This includes the TODO keyword, the tags, time strings for deadline,
15295 scheduled, and clocking, and any additional properties defined in the
15296 entry. The return value is an alist, keys may occur multiple times
15297 if the property key was used several times.
15298 POM may also be nil, in which case the current entry is used.
15299 If WHICH is nil or `all', get all properties. If WHICH is
15300 `special' or `standard', only get that subclass. If WHICH
15301 is a string only get exactly this property. SPECIFIC can be a string, the
15302 specific property we are interested in. Specifying it can speed
15303 things up because then unnecessary parsing is avoided."
15304 (setq which (or which 'all))
15305 (org-with-wide-buffer
15306 (org-with-point-at pom
15307 (let ((clockstr (substring org-clock-string 0 -1))
15308 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15309 (case-fold-search nil)
15310 beg end range props sum-props key key1 value string clocksum clocksumt)
15311 (when (and (derived-mode-p 'org-mode)
15312 (ignore-errors (org-back-to-heading t)))
15313 (setq beg (point))
15314 (setq sum-props (get-text-property (point) 'org-summaries))
15315 (setq clocksum (get-text-property (point) :org-clock-minutes)
15316 clocksumt (get-text-property (point) :org-clock-minutes-today))
15317 (outline-next-heading)
15318 (setq end (point))
15319 (when (memq which '(all special))
15320 ;; Get the special properties, like TODO and tags
15321 (goto-char beg)
15322 (when (and (or (not specific) (string= specific "TODO"))
15323 (looking-at org-todo-line-regexp) (match-end 2))
15324 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15325 (when (and (or (not specific) (string= specific "PRIORITY"))
15326 (looking-at org-priority-regexp))
15327 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15328 (when (or (not specific) (string= specific "FILE"))
15329 (push (cons "FILE" buffer-file-name) props))
15330 (when (and (or (not specific) (string= specific "TAGS"))
15331 (setq value (org-get-tags-string))
15332 (string-match "\\S-" value))
15333 (push (cons "TAGS" value) props))
15334 (when (and (or (not specific) (string= specific "ALLTAGS"))
15335 (setq value (org-get-tags-at)))
15336 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15337 ":"))
15338 props))
15339 (when (or (not specific) (string= specific "BLOCKED"))
15340 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15341 (when (or (not specific)
15342 (member specific
15343 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15344 "TIMESTAMP" "TIMESTAMP_IA")))
15345 (catch 'match
15346 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15347 (setq key (if (match-end 1)
15348 (substring (org-match-string-no-properties 1)
15349 0 -1))
15350 string (if (equal key clockstr)
15351 (org-trim
15352 (buffer-substring-no-properties
15353 (match-beginning 3) (goto-char
15354 (point-at-eol))))
15355 (substring (org-match-string-no-properties 3)
15356 1 -1)))
15357 ;; Get the correct property name from the key. This is
15358 ;; necessary if the user has configured time keywords.
15359 (setq key1 (concat key ":"))
15360 (cond
15361 ((not key)
15362 (setq key
15363 (if (= (char-after (match-beginning 3)) ?\[)
15364 "TIMESTAMP_IA" "TIMESTAMP")))
15365 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15366 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15367 ((equal key1 org-closed-string) (setq key "CLOSED"))
15368 ((equal key1 org-clock-string) (setq key "CLOCK")))
15369 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15370 (progn
15371 (push (cons key string) props)
15372 ;; no need to search further if match is found
15373 (throw 'match t))
15374 (when (or (equal key "CLOCK") (not (assoc key props)))
15375 (push (cons key string) props)))))))
15377 (when (memq which '(all standard))
15378 ;; Get the standard properties, like :PROP: ...
15379 (setq range (org-get-property-block beg end))
15380 (when range
15381 (goto-char (car range))
15382 (while (re-search-forward org-property-re
15383 (cdr range) t)
15384 (setq key (org-match-string-no-properties 2)
15385 value (org-trim (or (org-match-string-no-properties 3) "")))
15386 (unless (member key excluded)
15387 (push (cons key (or value "")) props)))))
15388 (if clocksum
15389 (push (cons "CLOCKSUM"
15390 (org-columns-number-to-string (/ (float clocksum) 60.)
15391 'add_times))
15392 props))
15393 (if clocksumt
15394 (push (cons "CLOCKSUM_T"
15395 (org-columns-number-to-string (/ (float clocksumt) 60.)
15396 'add_times))
15397 props))
15398 (unless (assoc "CATEGORY" props)
15399 (push (cons "CATEGORY" (org-get-category)) props))
15400 (append sum-props (nreverse props)))))))
15402 (defun org-entry-get (pom property &optional inherit literal-nil)
15403 "Get value of PROPERTY for entry or content at point-or-marker POM.
15404 If INHERIT is non-nil and the entry does not have the property,
15405 then also check higher levels of the hierarchy.
15406 If INHERIT is the symbol `selective', use inheritance only if the setting
15407 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15408 If the property is present but empty, the return value is the empty string.
15409 If the property is not present at all, nil is returned.
15411 Return the value as a string.
15413 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15414 do not interpret it as the list atom nil. This is used for inheritance
15415 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15416 (org-with-point-at pom
15417 (if (and inherit (if (eq inherit 'selective)
15418 (org-property-inherit-p property)
15420 (org-entry-get-with-inheritance property literal-nil)
15421 (if (member property org-special-properties)
15422 ;; We need a special property. Use `org-entry-properties'
15423 ;; to retrieve it, but specify the wanted property
15424 (cdr (assoc property (org-entry-properties nil 'special property)))
15425 (org-with-wide-buffer
15426 (let ((range (org-get-property-block)))
15427 (when (and range (not (eq (car range) (cdr range))))
15428 (let* ((props
15429 (list (or (assoc property org-file-properties)
15430 (assoc property org-global-properties)
15431 (assoc property org-global-properties-fixed))))
15432 (ap (lambda (key)
15433 (when (re-search-forward
15434 (org-re-property key) (cdr range) t)
15435 (setq props
15436 (org-update-property-plist
15438 (if (match-end 3)
15439 (org-match-string-no-properties 3) "")
15440 props)))))
15441 val)
15442 (goto-char (car range))
15443 (funcall ap property)
15444 (goto-char (car range))
15445 (while (funcall ap (concat property "+")))
15446 (setq val (cdr (assoc property props)))
15447 (when val (if literal-nil val (org-not-nil val)))))))))))
15449 (defun org-property-or-variable-value (var &optional inherit)
15450 "Check if there is a property fixing the value of VAR.
15451 If yes, return this value. If not, return the current value of the variable."
15452 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15453 (if (and prop (stringp prop) (string-match "\\S-" prop))
15454 (read prop)
15455 (symbol-value var))))
15457 (defun org-entry-delete (pom property)
15458 "Delete the property PROPERTY from entry at point-or-marker POM."
15459 (unless (member property org-special-properties)
15460 (org-with-point-at pom
15461 (let ((range (org-get-property-block)))
15462 (if (and range
15463 (goto-char (car range))
15464 (re-search-forward
15465 (org-re-property property)
15466 (cdr range) t))
15467 (progn
15468 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15469 (org-remove-empty-drawer-at (car range))
15471 nil)))))
15473 ;; Multi-values properties are properties that contain multiple values
15474 ;; These values are assumed to be single words, separated by whitespace.
15475 (defun org-entry-add-to-multivalued-property (pom property value)
15476 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15477 (let* ((old (org-entry-get pom property))
15478 (values (and old (org-split-string old "[ \t]"))))
15479 (setq value (org-entry-protect-space value))
15480 (unless (member value values)
15481 (setq values (append values (list value)))
15482 (org-entry-put pom property
15483 (mapconcat 'identity values " ")))))
15485 (defun org-entry-remove-from-multivalued-property (pom property value)
15486 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15487 (let* ((old (org-entry-get pom property))
15488 (values (and old (org-split-string old "[ \t]"))))
15489 (setq value (org-entry-protect-space value))
15490 (when (member value values)
15491 (setq values (delete value values))
15492 (org-entry-put pom property
15493 (mapconcat 'identity values " ")))))
15495 (defun org-entry-member-in-multivalued-property (pom property value)
15496 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15497 (let* ((old (org-entry-get pom property))
15498 (values (and old (org-split-string old "[ \t]"))))
15499 (setq value (org-entry-protect-space value))
15500 (member value values)))
15502 (defun org-entry-get-multivalued-property (pom property)
15503 "Return a list of values in a multivalued property."
15504 (let* ((value (org-entry-get pom property))
15505 (values (and value (org-split-string value "[ \t]"))))
15506 (mapcar 'org-entry-restore-space values)))
15508 (defun org-entry-put-multivalued-property (pom property &rest values)
15509 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15510 VALUES should be a list of strings. Spaces will be protected."
15511 (org-entry-put pom property
15512 (mapconcat 'org-entry-protect-space values " "))
15513 (let* ((value (org-entry-get pom property))
15514 (values (and value (org-split-string value "[ \t]"))))
15515 (mapcar 'org-entry-restore-space values)))
15517 (defun org-entry-protect-space (s)
15518 "Protect spaces and newline in string S."
15519 (while (string-match " " s)
15520 (setq s (replace-match "%20" t t s)))
15521 (while (string-match "\n" s)
15522 (setq s (replace-match "%0A" t t s)))
15525 (defun org-entry-restore-space (s)
15526 "Restore spaces and newline in string S."
15527 (while (string-match "%20" s)
15528 (setq s (replace-match " " t t s)))
15529 (while (string-match "%0A" s)
15530 (setq s (replace-match "\n" t t s)))
15533 (defvar org-entry-property-inherited-from (make-marker)
15534 "Marker pointing to the entry from where a property was inherited.
15535 Each call to `org-entry-get-with-inheritance' will set this marker to the
15536 location of the entry where the inheritance search matched. If there was
15537 no match, the marker will point nowhere.
15538 Note that also `org-entry-get' calls this function, if the INHERIT flag
15539 is set.")
15541 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15542 "Get PROPERTY of entry or content at point, search higher levels if needed.
15543 The search will stop at the first ancestor which has the property defined.
15544 If the value found is \"nil\", return nil to show that the property
15545 should be considered as undefined (this is the meaning of nil here).
15546 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15547 (move-marker org-entry-property-inherited-from nil)
15548 (let (tmp)
15549 (save-excursion
15550 (save-restriction
15551 (widen)
15552 (catch 'ex
15553 (while t
15554 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15555 (or (ignore-errors (org-back-to-heading t))
15556 (goto-char (point-min)))
15557 (move-marker org-entry-property-inherited-from (point))
15558 (throw 'ex tmp))
15559 (or (ignore-errors (org-up-heading-safe))
15560 (throw 'ex nil))))))
15561 (setq tmp (or tmp
15562 (cdr (assoc property org-file-properties))
15563 (cdr (assoc property org-global-properties))
15564 (cdr (assoc property org-global-properties-fixed))))
15565 (if literal-nil tmp (org-not-nil tmp))))
15567 (defvar org-property-changed-functions nil
15568 "Hook called when the value of a property has changed.
15569 Each hook function should accept two arguments, the name of the property
15570 and the new value.")
15572 (defun org-entry-put (pom property value)
15573 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15574 If the value is `nil', it is converted to the empty string.
15575 If it is not a string, an error is raised."
15576 (cond ((null value) (setq value ""))
15577 ((not (stringp value))
15578 (error "Properties values should be strings.")))
15579 (org-with-point-at pom
15580 (org-back-to-heading t)
15581 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15582 range)
15583 (cond
15584 ((equal property "TODO")
15585 (when (and (string-match "\\S-" value)
15586 (not (member value org-todo-keywords-1)))
15587 (user-error "\"%s\" is not a valid TODO state" value))
15588 (if (or (not value)
15589 (not (string-match "\\S-" value)))
15590 (setq value 'none))
15591 (org-todo value)
15592 (org-set-tags nil 'align))
15593 ((equal property "PRIORITY")
15594 (org-priority (if (and value (string-match "\\S-" value))
15595 (string-to-char value) ?\ ))
15596 (org-set-tags nil 'align))
15597 ((equal property "CLOCKSUM")
15598 (if (not (re-search-forward
15599 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15600 (error "Cannot find a clock log")
15601 (goto-char (- (match-end 1) 2))
15602 (cond
15603 ((eq value 'earlier) (org-timestamp-down))
15604 ((eq value 'later) (org-timestamp-up)))
15605 (org-clock-sum-current-item)))
15606 ((equal property "SCHEDULED")
15607 (if (re-search-forward org-scheduled-time-regexp end t)
15608 (cond
15609 ((eq value 'earlier) (org-timestamp-change -1 'day))
15610 ((eq value 'later) (org-timestamp-change 1 'day))
15611 (t (call-interactively 'org-schedule)))
15612 (call-interactively 'org-schedule)))
15613 ((equal property "DEADLINE")
15614 (if (re-search-forward org-deadline-time-regexp end t)
15615 (cond
15616 ((eq value 'earlier) (org-timestamp-change -1 'day))
15617 ((eq value 'later) (org-timestamp-change 1 'day))
15618 (t (call-interactively 'org-deadline)))
15619 (call-interactively 'org-deadline)))
15620 ((member property org-special-properties)
15621 (error "The %s property can not yet be set with `org-entry-put'"
15622 property))
15623 (t ; a non-special property
15624 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15625 (setq range (org-get-property-block beg end 'force))
15626 (goto-char (car range))
15627 (if (re-search-forward
15628 (org-re-property property) (cdr range) t)
15629 (progn
15630 (delete-region (match-beginning 0) (match-end 0))
15631 (goto-char (match-beginning 0)))
15632 (goto-char (cdr range))
15633 (insert "\n")
15634 (backward-char 1)
15635 (org-indent-line))
15636 (insert ":" property ":")
15637 (and value (insert " " value))
15638 (org-indent-line)))))
15639 (run-hook-with-args 'org-property-changed-functions property value)))
15641 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15642 "Get all property keys in the current buffer.
15643 With INCLUDE-SPECIALS, also list the special properties that reflect things
15644 like tags and TODO state.
15645 With INCLUDE-DEFAULTS, also include properties that has special meaning
15646 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15647 and others.
15648 With INCLUDE-COLUMNS, also include property names given in COLUMN
15649 formats in the current buffer."
15650 (let (rtn range cfmt s p)
15651 (save-excursion
15652 (save-restriction
15653 (widen)
15654 (goto-char (point-min))
15655 (while (re-search-forward org-property-start-re nil t)
15656 (setq range (org-get-property-block))
15657 (goto-char (car range))
15658 (while (re-search-forward org-property-re
15659 (cdr range) t)
15660 (add-to-list 'rtn (org-match-string-no-properties 2)))
15661 (outline-next-heading))))
15663 (when include-specials
15664 (setq rtn (append org-special-properties rtn)))
15666 (when include-defaults
15667 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15668 (add-to-list 'rtn org-effort-property))
15670 (when include-columns
15671 (save-excursion
15672 (save-restriction
15673 (widen)
15674 (goto-char (point-min))
15675 (while (re-search-forward
15676 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15677 nil t)
15678 (setq cfmt (match-string 2) s 0)
15679 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15680 cfmt s)
15681 (setq s (match-end 0)
15682 p (match-string 1 cfmt))
15683 (unless (or (equal p "ITEM")
15684 (member p org-special-properties))
15685 (add-to-list 'rtn (match-string 1 cfmt))))))))
15687 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15689 (defun org-property-values (key)
15690 "Return a list of all values of property KEY in the current buffer."
15691 (save-excursion
15692 (save-restriction
15693 (widen)
15694 (goto-char (point-min))
15695 (let ((re (org-re-property key))
15696 values)
15697 (while (re-search-forward re nil t)
15698 (add-to-list 'values (org-trim (match-string 3))))
15699 (delete "" values)))))
15701 (defun org-insert-property-drawer ()
15702 "Insert a property drawer into the current entry."
15703 (org-back-to-heading t)
15704 (looking-at org-outline-regexp)
15705 (let ((indent (if org-adapt-indentation
15706 (- (match-end 0) (match-beginning 0))
15708 (beg (point))
15709 (re (concat "^[ \t]*" org-keyword-time-regexp))
15710 end hiddenp)
15711 (outline-next-heading)
15712 (setq end (point))
15713 (goto-char beg)
15714 (while (re-search-forward re end t))
15715 (setq hiddenp (outline-invisible-p))
15716 (end-of-line 1)
15717 (and (equal (char-after) ?\n) (forward-char 1))
15718 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15719 (if (member (match-string 1) '("CLOCK:" ":END:"))
15720 ;; just skip this line
15721 (beginning-of-line 2)
15722 ;; Drawer start, find the end
15723 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15724 (beginning-of-line 1)))
15725 (org-skip-over-state-notes)
15726 (skip-chars-backward " \t\n\r")
15727 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15728 (forward-char 1))
15729 (goto-char (point-at-eol))
15730 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15731 (beginning-of-line 0)
15732 (org-indent-to-column indent)
15733 (beginning-of-line 2)
15734 (org-indent-to-column indent)
15735 (beginning-of-line 0)
15736 (if hiddenp
15737 (save-excursion
15738 (org-back-to-heading t)
15739 (hide-entry))
15740 (org-flag-drawer t))))
15742 (defun org-insert-drawer (&optional arg drawer)
15743 "Insert a drawer at point.
15745 Optional argument DRAWER, when non-nil, is a string representing
15746 drawer's name. Otherwise, the user is prompted for a name.
15748 If a region is active, insert the drawer around that region
15749 instead.
15751 Point is left between drawer's boundaries."
15752 (interactive "P")
15753 (let* ((drawer (if arg "PROPERTIES"
15754 (or drawer (read-from-minibuffer "Drawer: ")))))
15755 (cond
15756 ;; With C-u, fall back on `org-insert-property-drawer'
15757 (arg (org-insert-property-drawer))
15759 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15760 (user-error "Invalid drawer name"))
15761 ;; With an active region, insert a drawer at point.
15762 ((not (org-region-active-p))
15763 (progn
15764 (unless (bolp) (insert "\n"))
15765 (insert (format ":%s:\n\n:END:\n" drawer))
15766 (forward-line -2)))
15767 ;; Otherwise, insert the drawer at point
15769 (let ((rbeg (region-beginning))
15770 (rend (copy-marker (region-end))))
15771 (unwind-protect
15772 (progn
15773 (goto-char rbeg)
15774 (beginning-of-line)
15775 (when (save-excursion
15776 (re-search-forward org-outline-regexp-bol rend t))
15777 (user-error "Drawers cannot contain headlines"))
15778 ;; Position point at the beginning of the first
15779 ;; non-blank line in region. Insert drawer's opening
15780 ;; there, then indent it.
15781 (org-skip-whitespace)
15782 (beginning-of-line)
15783 (insert ":" drawer ":\n")
15784 (forward-line -1)
15785 (indent-for-tab-command)
15786 ;; Move point to the beginning of the first blank line
15787 ;; after the last non-blank line in region. Insert
15788 ;; drawer's closing, then indent it.
15789 (goto-char rend)
15790 (skip-chars-backward " \r\t\n")
15791 (insert "\n:END:")
15792 (deactivate-mark t)
15793 (indent-for-tab-command)
15794 (unless (eolp) (insert "\n")))
15795 ;; Clear marker, whatever the outcome of insertion is.
15796 (set-marker rend nil)))))))
15798 (defvar org-property-set-functions-alist nil
15799 "Property set function alist.
15800 Each entry should have the following format:
15802 (PROPERTY . READ-FUNCTION)
15804 The read function will be called with the same argument as
15805 `org-completing-read'.")
15807 (defun org-set-property-function (property)
15808 "Get the function that should be used to set PROPERTY.
15809 This is computed according to `org-property-set-functions-alist'."
15810 (or (cdr (assoc property org-property-set-functions-alist))
15811 'org-completing-read))
15813 (defun org-read-property-value (property)
15814 "Read PROPERTY value from user."
15815 (let* ((completion-ignore-case t)
15816 (allowed (org-property-get-allowed-values nil property 'table))
15817 (cur (org-entry-get nil property))
15818 (prompt (concat property " value"
15819 (if (and cur (string-match "\\S-" cur))
15820 (concat " [" cur "]") "") ": "))
15821 (set-function (org-set-property-function property))
15822 (val (if allowed
15823 (funcall set-function prompt allowed nil
15824 (not (get-text-property 0 'org-unrestricted
15825 (caar allowed))))
15826 (let (org-completion-use-ido org-completion-use-iswitchb)
15827 (funcall set-function prompt
15828 (mapcar 'list (org-property-values property))
15829 nil nil "" nil cur)))))
15830 (if (equal val "")
15832 val)))
15834 (defvar org-last-set-property nil)
15835 (defvar org-last-set-property-value nil)
15836 (defun org-read-property-name ()
15837 "Read a property name."
15838 (let* ((completion-ignore-case t)
15839 (keys (org-buffer-property-keys nil t t))
15840 (default-prop (or (save-excursion
15841 (save-match-data
15842 (beginning-of-line)
15843 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15844 (null (string= (match-string 1) "END"))
15845 (match-string 1))))
15846 org-last-set-property))
15847 (property (org-icompleting-read
15848 (concat "Property"
15849 (if default-prop (concat " [" default-prop "]") "")
15850 ": ")
15851 (mapcar 'list keys)
15852 nil nil nil nil
15853 default-prop)))
15854 (if (member property keys)
15855 property
15856 (or (cdr (assoc (downcase property)
15857 (mapcar (lambda (x) (cons (downcase x) x))
15858 keys)))
15859 property))))
15861 (defun org-set-property-and-value (use-last)
15862 "Allow to set [PROPERTY]: [value] direction from prompt.
15863 When use-default, don't even ask, just use the last
15864 \"[PROPERTY]: [value]\" string from the history."
15865 (interactive "P")
15866 (let* ((completion-ignore-case t)
15867 (pv (or (and use-last org-last-set-property-value)
15868 (org-completing-read
15869 "Enter a \"[Property]: [value]\" pair: "
15870 nil nil nil nil nil
15871 org-last-set-property-value)))
15872 prop val)
15873 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15874 (setq prop (match-string 1 pv)
15875 val (match-string 2 pv))
15876 (org-set-property prop val))))
15878 (defun org-set-property (property value)
15879 "In the current entry, set PROPERTY to VALUE.
15880 When called interactively, this will prompt for a property name, offering
15881 completion on existing and default properties. And then it will prompt
15882 for a value, offering completion either on allowed values (via an inherited
15883 xxx_ALL property) or on existing values in other instances of this property
15884 in the current file."
15885 (interactive (list nil nil))
15886 (let* ((property (or property (org-read-property-name)))
15887 (value (or value (org-read-property-value property)))
15888 (fn (cdr (assoc property org-properties-postprocess-alist))))
15889 (setq org-last-set-property property)
15890 (setq org-last-set-property-value (concat property ": " value))
15891 ;; Possibly postprocess the inserted value:
15892 (when fn (setq value (funcall fn value)))
15893 (unless (equal (org-entry-get nil property) value)
15894 (org-entry-put nil property value))))
15896 (defun org-delete-property (property)
15897 "In the current entry, delete PROPERTY."
15898 (interactive
15899 (let* ((completion-ignore-case t)
15900 (prop (org-icompleting-read "Property: "
15901 (org-entry-properties nil 'standard))))
15902 (list prop)))
15903 (message "Property %s %s" property
15904 (if (org-entry-delete nil property)
15905 "deleted"
15906 "was not present in the entry")))
15908 (defun org-delete-property-globally (property)
15909 "Remove PROPERTY globally, from all entries."
15910 (interactive
15911 (let* ((completion-ignore-case t)
15912 (prop (org-icompleting-read
15913 "Globally remove property: "
15914 (mapcar 'list (org-buffer-property-keys)))))
15915 (list prop)))
15916 (save-excursion
15917 (save-restriction
15918 (widen)
15919 (goto-char (point-min))
15920 (let ((cnt 0))
15921 (while (re-search-forward
15922 (org-re-property property)
15923 nil t)
15924 (setq cnt (1+ cnt))
15925 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15926 (message "Property \"%s\" removed from %d entries" property cnt)))))
15928 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15930 (defun org-compute-property-at-point ()
15931 "Compute the property at point.
15932 This looks for an enclosing column format, extracts the operator and
15933 then applies it to the property in the column format's scope."
15934 (interactive)
15935 (unless (org-at-property-p)
15936 (user-error "Not at a property"))
15937 (let ((prop (org-match-string-no-properties 2)))
15938 (org-columns-get-format-and-top-level)
15939 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15940 (user-error "No operator defined for property %s" prop))
15941 (org-columns-compute prop)))
15943 (defvar org-property-allowed-value-functions nil
15944 "Hook for functions supplying allowed values for a specific property.
15945 The functions must take a single argument, the name of the property, and
15946 return a flat list of allowed values. If \":ETC\" is one of
15947 the values, this means that these values are intended as defaults for
15948 completion, but that other values should be allowed too.
15949 The functions must return nil if they are not responsible for this
15950 property.")
15952 (defun org-property-get-allowed-values (pom property &optional table)
15953 "Get allowed values for the property PROPERTY.
15954 When TABLE is non-nil, return an alist that can directly be used for
15955 completion."
15956 (let (vals)
15957 (cond
15958 ((equal property "TODO")
15959 (setq vals (org-with-point-at pom
15960 (append org-todo-keywords-1 '("")))))
15961 ((equal property "PRIORITY")
15962 (let ((n org-lowest-priority))
15963 (while (>= n org-highest-priority)
15964 (push (char-to-string n) vals)
15965 (setq n (1- n)))))
15966 ((member property org-special-properties))
15967 ((setq vals (run-hook-with-args-until-success
15968 'org-property-allowed-value-functions property)))
15970 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15971 (when (and vals (string-match "\\S-" vals))
15972 (setq vals (car (read-from-string (concat "(" vals ")"))))
15973 (setq vals (mapcar (lambda (x)
15974 (cond ((stringp x) x)
15975 ((numberp x) (number-to-string x))
15976 ((symbolp x) (symbol-name x))
15977 (t "???")))
15978 vals)))))
15979 (when (member ":ETC" vals)
15980 (setq vals (remove ":ETC" vals))
15981 (org-add-props (car vals) '(org-unrestricted t)))
15982 (if table (mapcar 'list vals) vals)))
15984 (defun org-property-previous-allowed-value (&optional previous)
15985 "Switch to the next allowed value for this property."
15986 (interactive)
15987 (org-property-next-allowed-value t))
15989 (defun org-property-next-allowed-value (&optional previous)
15990 "Switch to the next allowed value for this property."
15991 (interactive)
15992 (unless (org-at-property-p)
15993 (user-error "Not at a property"))
15994 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15995 (key (match-string 2))
15996 (value (match-string 3))
15997 (allowed (or (org-property-get-allowed-values (point) key)
15998 (and (member value '("[ ]" "[-]" "[X]"))
15999 '("[ ]" "[X]"))))
16000 (heading (save-match-data (nth 4 (org-heading-components))))
16001 nval)
16002 (unless allowed
16003 (user-error "Allowed values for this property have not been defined"))
16004 (if previous (setq allowed (reverse allowed)))
16005 (if (member value allowed)
16006 (setq nval (car (cdr (member value allowed)))))
16007 (setq nval (or nval (car allowed)))
16008 (if (equal nval value)
16009 (user-error "Only one allowed value for this property"))
16010 (org-at-property-p)
16011 (replace-match (concat " :" key ": " nval) t t)
16012 (org-indent-line)
16013 (beginning-of-line 1)
16014 (skip-chars-forward " \t")
16015 (when (equal prop org-effort-property)
16016 (save-excursion
16017 (org-back-to-heading t)
16018 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
16019 (when (string= org-clock-current-task heading)
16020 (setq org-clock-effort nval)
16021 (org-clock-update-mode-line)))
16022 (run-hook-with-args 'org-property-changed-functions key nval)))
16024 (defun org-find-olp (path &optional this-buffer)
16025 "Return a marker pointing to the entry at outline path OLP.
16026 If anything goes wrong, throw an error.
16027 You can wrap this call to catch the error like this:
16029 (condition-case msg
16030 (org-mobile-locate-entry (match-string 4))
16031 (error (nth 1 msg)))
16033 The return value will then be either a string with the error message,
16034 or a marker if everything is OK.
16036 If THIS-BUFFER is set, the outline path does not contain a file,
16037 only headings."
16038 (let* ((file (if this-buffer buffer-file-name (pop path)))
16039 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16040 (level 1)
16041 (lmin 1)
16042 (lmax 1)
16043 limit re end found pos heading cnt flevel)
16044 (unless buffer (error "File not found :%s" file))
16045 (with-current-buffer buffer
16046 (save-excursion
16047 (save-restriction
16048 (widen)
16049 (setq limit (point-max))
16050 (goto-char (point-min))
16051 (while (setq heading (pop path))
16052 (setq re (format org-complex-heading-regexp-format
16053 (regexp-quote heading)))
16054 (setq cnt 0 pos (point))
16055 (while (re-search-forward re end t)
16056 (setq level (- (match-end 1) (match-beginning 1)))
16057 (if (and (>= level lmin) (<= level lmax))
16058 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16059 (when (= cnt 0) (error "Heading not found on level %d: %s"
16060 lmax heading))
16061 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16062 lmax heading))
16063 (goto-char found)
16064 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16065 (setq end (save-excursion (org-end-of-subtree t t))))
16066 (when (org-at-heading-p)
16067 (point-marker)))))))
16069 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16070 "Find node HEADING in BUFFER.
16071 Return a marker to the heading if it was found, or nil if not.
16072 If POS-ONLY is set, return just the position instead of a marker.
16074 The heading text must match exact, but it may have a TODO keyword,
16075 a priority cookie and tags in the standard locations."
16076 (with-current-buffer (or buffer (current-buffer))
16077 (save-excursion
16078 (save-restriction
16079 (widen)
16080 (goto-char (point-min))
16081 (let (case-fold-search)
16082 (if (re-search-forward
16083 (format org-complex-heading-regexp-format
16084 (regexp-quote heading)) nil t)
16085 (if pos-only
16086 (match-beginning 0)
16087 (move-marker (make-marker) (match-beginning 0)))))))))
16089 (defun org-find-exact-heading-in-directory (heading &optional dir)
16090 "Find Org node headline HEADING in all .org files in directory DIR.
16091 When the target headline is found, return a marker to this location."
16092 (let ((files (directory-files (or dir default-directory)
16093 nil "\\`[^.#].*\\.org\\'"))
16094 file visiting m buffer)
16095 (catch 'found
16096 (while (setq file (pop files))
16097 (message "trying %s" file)
16098 (setq visiting (org-find-base-buffer-visiting file))
16099 (setq buffer (or visiting (find-file-noselect file)))
16100 (setq m (org-find-exact-headline-in-buffer
16101 heading buffer))
16102 (when (and (not m) (not visiting)) (kill-buffer buffer))
16103 (and m (throw 'found m))))))
16105 (defun org-find-entry-with-id (ident)
16106 "Locate the entry that contains the ID property with exact value IDENT.
16107 IDENT can be a string, a symbol or a number, this function will search for
16108 the string representation of it.
16109 Return the position where this entry starts, or nil if there is no such entry."
16110 (interactive "sID: ")
16111 (let ((id (cond
16112 ((stringp ident) ident)
16113 ((symbol-name ident) (symbol-name ident))
16114 ((numberp ident) (number-to-string ident))
16115 (t (error "IDENT %s must be a string, symbol or number" ident))))
16116 (case-fold-search nil))
16117 (save-excursion
16118 (save-restriction
16119 (widen)
16120 (goto-char (point-min))
16121 (when (re-search-forward
16122 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16123 nil t)
16124 (org-back-to-heading t)
16125 (point))))))
16127 ;;;; Timestamps
16129 (defvar org-last-changed-timestamp nil)
16130 (defvar org-last-inserted-timestamp nil
16131 "The last time stamp inserted with `org-insert-time-stamp'.")
16132 (defvar org-ts-what) ; dynamically scoped parameter
16134 (defun org-time-stamp (arg &optional inactive)
16135 "Prompt for a date/time and insert a time stamp.
16136 If the user specifies a time like HH:MM or if this command is
16137 called with at least one prefix argument, the time stamp contains
16138 the date and the time. Otherwise, only the date is be included.
16140 All parts of a date not specified by the user is filled in from
16141 the current date/time. So if you just press return without
16142 typing anything, the time stamp will represent the current
16143 date/time.
16145 If there is already a timestamp at the cursor, it will be
16146 modified.
16148 With two universal prefix arguments, insert an active timestamp
16149 with the current time without prompting the user.
16151 When called from lisp, the timestamp is inactive if INACTIVE is
16152 non-nil."
16153 (interactive "P")
16154 (let* ((ts nil)
16155 (default-time
16156 ;; Default time is either today, or, when entering a range,
16157 ;; the range start.
16158 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16159 (save-excursion
16160 (re-search-backward
16161 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16162 (- (point) 20) t)))
16163 (apply 'encode-time (org-parse-time-string (match-string 1)))
16164 (current-time)))
16165 (default-input (and ts (org-get-compact-tod ts)))
16166 (repeater (save-excursion
16167 (save-match-data
16168 (beginning-of-line)
16169 (when (re-search-forward
16170 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16171 (save-excursion (progn (end-of-line) (point))) t)
16172 (match-string 0)))))
16173 org-time-was-given org-end-time-was-given time)
16174 (cond
16175 ((and (org-at-timestamp-p t)
16176 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16177 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16178 (insert "--")
16179 (setq time (let ((this-command this-command))
16180 (org-read-date arg 'totime nil nil
16181 default-time default-input inactive)))
16182 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16183 ((org-at-timestamp-p t)
16184 (setq time (let ((this-command this-command))
16185 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16186 (when (org-at-timestamp-p t) ; just to get the match data
16187 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16188 (replace-match "")
16189 (setq org-last-changed-timestamp
16190 (org-insert-time-stamp
16191 time (or org-time-was-given arg)
16192 inactive nil nil (list org-end-time-was-given)))
16193 (when repeater (goto-char (1- (point))) (insert " " repeater)
16194 (setq org-last-changed-timestamp
16195 (concat (substring org-last-inserted-timestamp 0 -1)
16196 " " repeater ">"))))
16197 (message "Timestamp updated"))
16198 ((equal arg '(16))
16199 (org-insert-time-stamp (current-time) t inactive))
16201 (setq time (let ((this-command this-command))
16202 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16203 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16204 nil nil (list org-end-time-was-given))))))
16206 ;; FIXME: can we use this for something else, like computing time differences?
16207 (defun org-get-compact-tod (s)
16208 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16209 (let* ((t1 (match-string 1 s))
16210 (h1 (string-to-number (match-string 2 s)))
16211 (m1 (string-to-number (match-string 3 s)))
16212 (t2 (and (match-end 4) (match-string 5 s)))
16213 (h2 (and t2 (string-to-number (match-string 6 s))))
16214 (m2 (and t2 (string-to-number (match-string 7 s))))
16215 dh dm)
16216 (if (not t2)
16218 (setq dh (- h2 h1) dm (- m2 m1))
16219 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16220 (concat t1 "+" (number-to-string dh)
16221 (and (/= 0 dm) (format ":%02d" dm)))))))
16223 (defun org-time-stamp-inactive (&optional arg)
16224 "Insert an inactive time stamp.
16225 An inactive time stamp is enclosed in square brackets instead of angle
16226 brackets. It is inactive in the sense that it does not trigger agenda entries,
16227 does not link to the calendar and cannot be changed with the S-cursor keys.
16228 So these are more for recording a certain time/date."
16229 (interactive "P")
16230 (org-time-stamp arg 'inactive))
16232 (defvar org-date-ovl (make-overlay 1 1))
16233 (overlay-put org-date-ovl 'face 'org-date-selected)
16234 (org-detach-overlay org-date-ovl)
16236 (defvar org-ans1) ; dynamically scoped parameter
16237 (defvar org-ans2) ; dynamically scoped parameter
16239 (defvar org-plain-time-of-day-regexp) ; defined below
16241 (defvar org-overriding-default-time nil) ; dynamically scoped
16242 (defvar org-read-date-overlay nil)
16243 (defvar org-dcst nil) ; dynamically scoped
16244 (defvar org-read-date-history nil)
16245 (defvar org-read-date-final-answer nil)
16246 (defvar org-read-date-analyze-futurep nil)
16247 (defvar org-read-date-analyze-forced-year nil)
16248 (defvar org-read-date-inactive)
16250 (defvar org-read-date-minibuffer-local-map
16251 (let* ((org-replace-disputed-keys nil)
16252 (map (make-sparse-keymap)))
16253 (set-keymap-parent map minibuffer-local-map)
16254 (org-defkey map (kbd ".")
16255 (lambda () (interactive)
16256 ;; Are we at the beginning of the prompt?
16257 (if (looking-back "^[^:]+: ")
16258 (org-eval-in-calendar '(calendar-goto-today))
16259 (insert "."))))
16260 (org-defkey map (kbd "C-.")
16261 (lambda () (interactive)
16262 (org-eval-in-calendar '(calendar-goto-today))))
16263 (org-defkey map [(meta shift left)]
16264 (lambda () (interactive)
16265 (org-eval-in-calendar '(calendar-backward-month 1))))
16266 (org-defkey map [(meta shift right)]
16267 (lambda () (interactive)
16268 (org-eval-in-calendar '(calendar-forward-month 1))))
16269 (org-defkey map [(meta shift up)]
16270 (lambda () (interactive)
16271 (org-eval-in-calendar '(calendar-backward-year 1))))
16272 (org-defkey map [(meta shift down)]
16273 (lambda () (interactive)
16274 (org-eval-in-calendar '(calendar-forward-year 1))))
16275 (org-defkey map [?\e (shift left)]
16276 (lambda () (interactive)
16277 (org-eval-in-calendar '(calendar-backward-month 1))))
16278 (org-defkey map [?\e (shift right)]
16279 (lambda () (interactive)
16280 (org-eval-in-calendar '(calendar-forward-month 1))))
16281 (org-defkey map [?\e (shift up)]
16282 (lambda () (interactive)
16283 (org-eval-in-calendar '(calendar-backward-year 1))))
16284 (org-defkey map [?\e (shift down)]
16285 (lambda () (interactive)
16286 (org-eval-in-calendar '(calendar-forward-year 1))))
16287 (org-defkey map [(shift up)]
16288 (lambda () (interactive)
16289 (org-eval-in-calendar '(calendar-backward-week 1))))
16290 (org-defkey map [(shift down)]
16291 (lambda () (interactive)
16292 (org-eval-in-calendar '(calendar-forward-week 1))))
16293 (org-defkey map [(shift left)]
16294 (lambda () (interactive)
16295 (org-eval-in-calendar '(calendar-backward-day 1))))
16296 (org-defkey map [(shift right)]
16297 (lambda () (interactive)
16298 (org-eval-in-calendar '(calendar-forward-day 1))))
16299 (org-defkey map "!"
16300 (lambda () (interactive)
16301 (org-eval-in-calendar '(diary-view-entries))
16302 (message "")))
16303 (org-defkey map ">"
16304 (lambda () (interactive)
16305 (org-eval-in-calendar '(scroll-calendar-left 1))))
16306 (org-defkey map "<"
16307 (lambda () (interactive)
16308 (org-eval-in-calendar '(scroll-calendar-right 1))))
16309 (org-defkey map "\C-v"
16310 (lambda () (interactive)
16311 (org-eval-in-calendar
16312 '(calendar-scroll-left-three-months 1))))
16313 (org-defkey map "\M-v"
16314 (lambda () (interactive)
16315 (org-eval-in-calendar
16316 '(calendar-scroll-right-three-months 1))))
16317 map)
16318 "Keymap for minibuffer commands when using `org-read-date'.")
16320 (defvar org-def)
16321 (defvar org-defdecode)
16322 (defvar org-with-time)
16324 (defun org-read-date (&optional org-with-time to-time from-string prompt
16325 default-time default-input inactive)
16326 "Read a date, possibly a time, and make things smooth for the user.
16327 The prompt will suggest to enter an ISO date, but you can also enter anything
16328 which will at least partially be understood by `parse-time-string'.
16329 Unrecognized parts of the date will default to the current day, month, year,
16330 hour and minute. If this command is called to replace a timestamp at point,
16331 or to enter the second timestamp of a range, the default time is taken
16332 from the existing stamp. Furthermore, the command prefers the future,
16333 so if you are giving a date where the year is not given, and the day-month
16334 combination is already past in the current year, it will assume you
16335 mean next year. For details, see the manual. A few examples:
16337 3-2-5 --> 2003-02-05
16338 feb 15 --> currentyear-02-15
16339 2/15 --> currentyear-02-15
16340 sep 12 9 --> 2009-09-12
16341 12:45 --> today 12:45
16342 22 sept 0:34 --> currentyear-09-22 0:34
16343 12 --> currentyear-currentmonth-12
16344 Fri --> nearest Friday after today
16345 -Tue --> last Tuesday
16346 etc.
16348 Furthermore you can specify a relative date by giving, as the *first* thing
16349 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16350 change in days weeks, months, years.
16351 With a single plus or minus, the date is relative to today. With a double
16352 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16353 +4d --> four days from today
16354 +4 --> same as above
16355 +2w --> two weeks from today
16356 ++5 --> five days from default date
16358 The function understands only English month and weekday abbreviations.
16360 While prompting, a calendar is popped up - you can also select the
16361 date with the mouse (button 1). The calendar shows a period of three
16362 months. To scroll it to other months, use the keys `>' and `<'.
16363 If you don't like the calendar, turn it off with
16364 \(setq org-read-date-popup-calendar nil)
16366 With optional argument TO-TIME, the date will immediately be converted
16367 to an internal time.
16368 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16369 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16370 still enter a time, and this function will inform the calling routine
16371 about this change. The calling routine may then choose to change the
16372 format used to insert the time stamp into the buffer to include the time.
16373 With optional argument FROM-STRING, read from this string instead from
16374 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16375 the time/date that is used for everything that is not specified by the
16376 user."
16377 (require 'parse-time)
16378 (let* ((org-time-stamp-rounding-minutes
16379 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16380 (org-dcst org-display-custom-times)
16381 (ct (org-current-time))
16382 (org-def (or org-overriding-default-time default-time ct))
16383 (org-defdecode (decode-time org-def))
16384 (dummy (progn
16385 (when (< (nth 2 org-defdecode) org-extend-today-until)
16386 (setcar (nthcdr 2 org-defdecode) -1)
16387 (setcar (nthcdr 1 org-defdecode) 59)
16388 (setq org-def (apply 'encode-time org-defdecode)
16389 org-defdecode (decode-time org-def)))))
16390 (mouse-autoselect-window nil) ; Don't let the mouse jump
16391 (calendar-frame-setup nil)
16392 (calendar-setup nil)
16393 (calendar-move-hook nil)
16394 (calendar-view-diary-initially-flag nil)
16395 (calendar-view-holidays-initially-flag nil)
16396 (timestr (format-time-string
16397 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16398 (prompt (concat (if prompt (concat prompt " ") "")
16399 (format "Date+time [%s]: " timestr)))
16400 ans (org-ans0 "") org-ans1 org-ans2 final)
16402 (cond
16403 (from-string (setq ans from-string))
16404 (org-read-date-popup-calendar
16405 (save-excursion
16406 (save-window-excursion
16407 (calendar)
16408 (org-eval-in-calendar '(setq cursor-type nil) t)
16409 (unwind-protect
16410 (progn
16411 (calendar-forward-day (- (time-to-days org-def)
16412 (calendar-absolute-from-gregorian
16413 (calendar-current-date))))
16414 (org-eval-in-calendar nil t)
16415 (let* ((old-map (current-local-map))
16416 (map (copy-keymap calendar-mode-map))
16417 (minibuffer-local-map
16418 (copy-keymap org-read-date-minibuffer-local-map)))
16419 (org-defkey map (kbd "RET") 'org-calendar-select)
16420 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16421 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16422 (unwind-protect
16423 (progn
16424 (use-local-map map)
16425 (setq org-read-date-inactive inactive)
16426 (add-hook 'post-command-hook 'org-read-date-display)
16427 (setq org-ans0 (read-string prompt default-input
16428 'org-read-date-history nil))
16429 ;; org-ans0: from prompt
16430 ;; org-ans1: from mouse click
16431 ;; org-ans2: from calendar motion
16432 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16433 (remove-hook 'post-command-hook 'org-read-date-display)
16434 (use-local-map old-map)
16435 (when org-read-date-overlay
16436 (delete-overlay org-read-date-overlay)
16437 (setq org-read-date-overlay nil)))))
16438 (bury-buffer "*Calendar*")))))
16440 (t ; Naked prompt only
16441 (unwind-protect
16442 (setq ans (read-string prompt default-input
16443 'org-read-date-history timestr))
16444 (when org-read-date-overlay
16445 (delete-overlay org-read-date-overlay)
16446 (setq org-read-date-overlay nil)))))
16448 (setq final (org-read-date-analyze ans org-def org-defdecode))
16450 (when org-read-date-analyze-forced-year
16451 (message "Year was forced into %s"
16452 (if org-read-date-force-compatible-dates
16453 "compatible range (1970-2037)"
16454 "range representable on this machine"))
16455 (ding))
16457 ;; One round trip to get rid of 34th of August and stuff like that....
16458 (setq final (decode-time (apply 'encode-time final)))
16460 (setq org-read-date-final-answer ans)
16462 (if to-time
16463 (apply 'encode-time final)
16464 (if (and (boundp 'org-time-was-given) org-time-was-given)
16465 (format "%04d-%02d-%02d %02d:%02d"
16466 (nth 5 final) (nth 4 final) (nth 3 final)
16467 (nth 2 final) (nth 1 final))
16468 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16470 (defun org-read-date-display ()
16471 "Display the current date prompt interpretation in the minibuffer."
16472 (when org-read-date-display-live
16473 (when org-read-date-overlay
16474 (delete-overlay org-read-date-overlay))
16475 (when (minibufferp (current-buffer))
16476 (save-excursion
16477 (end-of-line 1)
16478 (while (not (equal (buffer-substring
16479 (max (point-min) (- (point) 4)) (point))
16480 " "))
16481 (insert " ")))
16482 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16483 " " (or org-ans1 org-ans2)))
16484 (org-end-time-was-given nil)
16485 (f (org-read-date-analyze ans org-def org-defdecode))
16486 (fmts (if org-dcst
16487 org-time-stamp-custom-formats
16488 org-time-stamp-formats))
16489 (fmt (if (or org-with-time
16490 (and (boundp 'org-time-was-given) org-time-was-given))
16491 (cdr fmts)
16492 (car fmts)))
16493 (txt (format-time-string fmt (apply 'encode-time f)))
16494 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16495 (txt (concat "=> " txt)))
16496 (when (and org-end-time-was-given
16497 (string-match org-plain-time-of-day-regexp txt))
16498 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16499 org-end-time-was-given
16500 (substring txt (match-end 0)))))
16501 (when org-read-date-analyze-futurep
16502 (setq txt (concat txt " (=>F)")))
16503 (setq org-read-date-overlay
16504 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16505 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16507 (defun org-read-date-analyze (ans org-def org-defdecode)
16508 "Analyze the combined answer of the date prompt."
16509 ;; FIXME: cleanup and comment
16510 (let ((nowdecode (decode-time (current-time)))
16511 delta deltan deltaw deltadef year month day
16512 hour minute second wday pm h2 m2 tl wday1
16513 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16514 (setq org-read-date-analyze-futurep nil
16515 org-read-date-analyze-forced-year nil)
16516 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16517 (setq ans "+0"))
16519 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16520 (setq ans (replace-match "" t t ans)
16521 deltan (car delta)
16522 deltaw (nth 1 delta)
16523 deltadef (nth 2 delta)))
16525 ;; Check if there is an iso week date in there. If yes, store the
16526 ;; info and postpone interpreting it until the rest of the parsing
16527 ;; is done.
16528 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16529 (setq iso-year (if (match-end 1)
16530 (org-small-year-to-year
16531 (string-to-number (match-string 1 ans))))
16532 iso-weekday (if (match-end 3)
16533 (string-to-number (match-string 3 ans)))
16534 iso-week (string-to-number (match-string 2 ans)))
16535 (setq ans (replace-match "" t t ans)))
16537 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16538 (when (string-match
16539 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16540 (setq year (if (match-end 2)
16541 (string-to-number (match-string 2 ans))
16542 (progn (setq kill-year t)
16543 (string-to-number (format-time-string "%Y"))))
16544 month (string-to-number (match-string 3 ans))
16545 day (string-to-number (match-string 4 ans)))
16546 (if (< year 100) (setq year (+ 2000 year)))
16547 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16548 t nil ans)))
16550 ;; Help matching dotted european dates
16551 (when (string-match
16552 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16553 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16554 (setq kill-year t)
16555 (string-to-number (format-time-string "%Y")))
16556 day (string-to-number (match-string 1 ans))
16557 month (string-to-number (match-string 2 ans))
16558 ans (replace-match (format "%04d-%02d-%02d" year month day)
16559 t nil ans)))
16561 ;; Help matching american dates, like 5/30 or 5/30/7
16562 (when (string-match
16563 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16564 (setq year (if (match-end 4)
16565 (string-to-number (match-string 4 ans))
16566 (progn (setq kill-year t)
16567 (string-to-number (format-time-string "%Y"))))
16568 month (string-to-number (match-string 1 ans))
16569 day (string-to-number (match-string 2 ans)))
16570 (if (< year 100) (setq year (+ 2000 year)))
16571 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16572 t nil ans)))
16573 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16574 ;; If there is a time with am/pm, and *no* time without it, we convert
16575 ;; so that matching will be successful.
16576 (loop for i from 1 to 2 do ; twice, for end time as well
16577 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16578 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16579 (setq hour (string-to-number (match-string 1 ans))
16580 minute (if (match-end 3)
16581 (string-to-number (match-string 3 ans))
16583 pm (equal ?p
16584 (string-to-char (downcase (match-string 4 ans)))))
16585 (if (and (= hour 12) (not pm))
16586 (setq hour 0)
16587 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16588 (setq ans (replace-match (format "%02d:%02d" hour minute)
16589 t t ans))))
16591 ;; Check if a time range is given as a duration
16592 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16593 (setq hour (string-to-number (match-string 1 ans))
16594 h2 (+ hour (string-to-number (match-string 3 ans)))
16595 minute (string-to-number (match-string 2 ans))
16596 m2 (+ minute (if (match-end 5) (string-to-number
16597 (match-string 5 ans))0)))
16598 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16599 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16600 t t ans)))
16602 ;; Check if there is a time range
16603 (when (boundp 'org-end-time-was-given)
16604 (setq org-time-was-given nil)
16605 (when (and (string-match org-plain-time-of-day-regexp ans)
16606 (match-end 8))
16607 (setq org-end-time-was-given (match-string 8 ans))
16608 (setq ans (concat (substring ans 0 (match-beginning 7))
16609 (substring ans (match-end 7))))))
16611 (setq tl (parse-time-string ans)
16612 day (or (nth 3 tl) (nth 3 org-defdecode))
16613 month (or (nth 4 tl)
16614 (if (and org-read-date-prefer-future
16615 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16616 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16617 (nth 4 org-defdecode)))
16618 year (or (and (not kill-year) (nth 5 tl))
16619 (if (and org-read-date-prefer-future
16620 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16621 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16622 (nth 5 org-defdecode)))
16623 hour (or (nth 2 tl) (nth 2 org-defdecode))
16624 minute (or (nth 1 tl) (nth 1 org-defdecode))
16625 second (or (nth 0 tl) 0)
16626 wday (nth 6 tl))
16628 (when (and (eq org-read-date-prefer-future 'time)
16629 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16630 (equal day (nth 3 nowdecode))
16631 (equal month (nth 4 nowdecode))
16632 (equal year (nth 5 nowdecode))
16633 (nth 2 tl)
16634 (or (< (nth 2 tl) (nth 2 nowdecode))
16635 (and (= (nth 2 tl) (nth 2 nowdecode))
16636 (nth 1 tl)
16637 (< (nth 1 tl) (nth 1 nowdecode)))))
16638 (setq day (1+ day)
16639 futurep t))
16641 ;; Special date definitions below
16642 (cond
16643 (iso-week
16644 ;; There was an iso week
16645 (require 'cal-iso)
16646 (setq futurep nil)
16647 (setq year (or iso-year year)
16648 day (or iso-weekday wday 1)
16649 wday nil ; to make sure that the trigger below does not match
16650 iso-date (calendar-gregorian-from-absolute
16651 (calendar-absolute-from-iso
16652 (list iso-week day year))))
16653 ; FIXME: Should we also push ISO weeks into the future?
16654 ; (when (and org-read-date-prefer-future
16655 ; (not iso-year)
16656 ; (< (calendar-absolute-from-gregorian iso-date)
16657 ; (time-to-days (current-time))))
16658 ; (setq year (1+ year)
16659 ; iso-date (calendar-gregorian-from-absolute
16660 ; (calendar-absolute-from-iso
16661 ; (list iso-week day year)))))
16662 (setq month (car iso-date)
16663 year (nth 2 iso-date)
16664 day (nth 1 iso-date)))
16665 (deltan
16666 (setq futurep nil)
16667 (unless deltadef
16668 (let ((now (decode-time (current-time))))
16669 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16670 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16671 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16672 ((equal deltaw "m") (setq month (+ month deltan)))
16673 ((equal deltaw "y") (setq year (+ year deltan)))))
16674 ((and wday (not (nth 3 tl)))
16675 ;; Weekday was given, but no day, so pick that day in the week
16676 ;; on or after the derived date.
16677 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16678 (unless (equal wday wday1)
16679 (setq day (+ day (% (- wday wday1 -7) 7))))))
16680 (if (and (boundp 'org-time-was-given)
16681 (nth 2 tl))
16682 (setq org-time-was-given t))
16683 (if (< year 100) (setq year (+ 2000 year)))
16684 ;; Check of the date is representable
16685 (if org-read-date-force-compatible-dates
16686 (progn
16687 (if (< year 1970)
16688 (setq year 1970 org-read-date-analyze-forced-year t))
16689 (if (> year 2037)
16690 (setq year 2037 org-read-date-analyze-forced-year t)))
16691 (condition-case nil
16692 (ignore (encode-time second minute hour day month year))
16693 (error
16694 (setq year (nth 5 org-defdecode))
16695 (setq org-read-date-analyze-forced-year t))))
16696 (setq org-read-date-analyze-futurep futurep)
16697 (list second minute hour day month year)))
16699 (defvar parse-time-weekdays)
16700 (defun org-read-date-get-relative (s today default)
16701 "Check string S for special relative date string.
16702 TODAY and DEFAULT are internal times, for today and for a default.
16703 Return shift list (N what def-flag)
16704 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16705 N is the number of WHATs to shift.
16706 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16707 the DEFAULT date rather than TODAY."
16708 (require 'parse-time)
16709 (when (and
16710 (string-match
16711 (concat
16712 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16713 "\\([0-9]+\\)?"
16714 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16715 "\\([ \t]\\|$\\)") s)
16716 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16717 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16718 (string-to-char (substring (match-string 1 s) -1))
16719 ?+))
16720 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16721 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16722 (what (if (match-end 3) (match-string 3 s) "d"))
16723 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16724 (date (if rel default today))
16725 (wday (nth 6 (decode-time date)))
16726 delta)
16727 (if wday1
16728 (progn
16729 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16730 (if (= delta 0) (setq delta 7))
16731 (if (= dir ?-)
16732 (progn
16733 (setq delta (- delta 7))
16734 (if (= delta 0) (setq delta -7))))
16735 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16736 (list delta "d" rel))
16737 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16739 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16740 "Turn a user-specified date into the internal representation.
16741 The internal representation needed by the calendar is (month day year).
16742 This is a wrapper to handle the brain-dead convention in calendar that
16743 user function argument order change dependent on argument order."
16744 (if (boundp 'calendar-date-style)
16745 (cond
16746 ((eq calendar-date-style 'american)
16747 (list arg1 arg2 arg3))
16748 ((eq calendar-date-style 'european)
16749 (list arg2 arg1 arg3))
16750 ((eq calendar-date-style 'iso)
16751 (list arg2 arg3 arg1)))
16752 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16753 (if (org-bound-and-true-p european-calendar-style)
16754 (list arg2 arg1 arg3)
16755 (list arg1 arg2 arg3)))))
16757 (defun org-eval-in-calendar (form &optional keepdate)
16758 "Eval FORM in the calendar window and return to current window.
16759 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16760 otherwise stick to the current value of `org-ans2'."
16761 (let ((sf (selected-frame))
16762 (sw (selected-window)))
16763 (select-window (get-buffer-window "*Calendar*" t))
16764 (eval form)
16765 (when (and (not keepdate) (calendar-cursor-to-date))
16766 (let* ((date (calendar-cursor-to-date))
16767 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16768 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16769 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16770 (select-window sw)
16771 (org-select-frame-set-input-focus sf)))
16773 (defun org-calendar-select ()
16774 "Return to `org-read-date' with the date currently selected.
16775 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16776 (interactive)
16777 (when (calendar-cursor-to-date)
16778 (let* ((date (calendar-cursor-to-date))
16779 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16780 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16781 (if (active-minibuffer-window) (exit-minibuffer))))
16783 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16784 "Insert a date stamp for the date given by the internal TIME.
16785 WITH-HM means use the stamp format that includes the time of the day.
16786 INACTIVE means use square brackets instead of angular ones, so that the
16787 stamp will not contribute to the agenda.
16788 PRE and POST are optional strings to be inserted before and after the
16789 stamp.
16790 The command returns the inserted time stamp."
16791 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16792 stamp)
16793 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16794 (insert-before-markers (or pre ""))
16795 (when (listp extra)
16796 (setq extra (car extra))
16797 (if (and (stringp extra)
16798 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16799 (setq extra (format "-%02d:%02d"
16800 (string-to-number (match-string 1 extra))
16801 (string-to-number (match-string 2 extra))))
16802 (setq extra nil)))
16803 (when extra
16804 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16805 (insert-before-markers (setq stamp (format-time-string fmt time)))
16806 (insert-before-markers (or post ""))
16807 (setq org-last-inserted-timestamp stamp)))
16809 (defun org-toggle-time-stamp-overlays ()
16810 "Toggle the use of custom time stamp formats."
16811 (interactive)
16812 (setq org-display-custom-times (not org-display-custom-times))
16813 (unless org-display-custom-times
16814 (let ((p (point-min)) (bmp (buffer-modified-p)))
16815 (while (setq p (next-single-property-change p 'display))
16816 (if (and (get-text-property p 'display)
16817 (eq (get-text-property p 'face) 'org-date))
16818 (remove-text-properties
16819 p (setq p (next-single-property-change p 'display))
16820 '(display t))))
16821 (set-buffer-modified-p bmp)))
16822 (if (featurep 'xemacs)
16823 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16824 (org-restart-font-lock)
16825 (setq org-table-may-need-update t)
16826 (if org-display-custom-times
16827 (message "Time stamps are overlaid with custom format")
16828 (message "Time stamp overlays removed")))
16830 (defun org-display-custom-time (beg end)
16831 "Overlay modified time stamp format over timestamp between BEG and END."
16832 (let* ((ts (buffer-substring beg end))
16833 t1 w1 with-hm tf time str w2 (off 0))
16834 (save-match-data
16835 (setq t1 (org-parse-time-string ts t))
16836 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16837 (setq off (- (match-end 0) (match-beginning 0)))))
16838 (setq end (- end off))
16839 (setq w1 (- end beg)
16840 with-hm (and (nth 1 t1) (nth 2 t1))
16841 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16842 time (org-fix-decoded-time t1)
16843 str (org-add-props
16844 (format-time-string
16845 (substring tf 1 -1) (apply 'encode-time time))
16846 nil 'mouse-face 'highlight)
16847 w2 (length str))
16848 (if (not (= w2 w1))
16849 (add-text-properties (1+ beg) (+ 2 beg)
16850 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16851 (if (featurep 'xemacs)
16852 (progn
16853 (put-text-property beg end 'invisible t)
16854 (put-text-property beg end 'end-glyph (make-glyph str)))
16855 (put-text-property beg end 'display str))))
16857 (defun org-translate-time (string)
16858 "Translate all timestamps in STRING to custom format.
16859 But do this only if the variable `org-display-custom-times' is set."
16860 (when org-display-custom-times
16861 (save-match-data
16862 (let* ((start 0)
16863 (re org-ts-regexp-both)
16864 t1 with-hm inactive tf time str beg end)
16865 (while (setq start (string-match re string start))
16866 (setq beg (match-beginning 0)
16867 end (match-end 0)
16868 t1 (save-match-data
16869 (org-parse-time-string (substring string beg end) t))
16870 with-hm (and (nth 1 t1) (nth 2 t1))
16871 inactive (equal (substring string beg (1+ beg)) "[")
16872 tf (funcall (if with-hm 'cdr 'car)
16873 org-time-stamp-custom-formats)
16874 time (org-fix-decoded-time t1)
16875 str (format-time-string
16876 (concat
16877 (if inactive "[" "<") (substring tf 1 -1)
16878 (if inactive "]" ">"))
16879 (apply 'encode-time time))
16880 string (replace-match str t t string)
16881 start (+ start (length str)))))))
16882 string)
16884 (defun org-fix-decoded-time (time)
16885 "Set 0 instead of nil for the first 6 elements of time.
16886 Don't touch the rest."
16887 (let ((n 0))
16888 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16890 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16892 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16893 "Difference between TIMESTAMP-STRING and now in days.
16894 If SECONDS is non-nil, return the difference in seconds."
16895 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16896 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16897 (funcall fdiff (current-time)))))
16899 (defun org-deadline-close (timestamp-string &optional ndays)
16900 "Is the time in TIMESTAMP-STRING close to the current date?"
16901 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16902 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16903 (not (org-entry-is-done-p))))
16905 (defun org-get-wdays (ts &optional delay zero-delay)
16906 "Get the deadline lead time appropriate for timestring TS.
16907 When DELAY is non-nil, get the delay time for scheduled items
16908 instead of the deadline lead time. When ZERO-DELAY is non-nil
16909 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16910 don't try to find the delay cookie in the scheduled timestamp."
16911 (let ((tv (if delay org-scheduled-delay-days
16912 org-deadline-warning-days)))
16913 (cond
16914 ((or (and delay (< tv 0))
16915 (and delay zero-delay (<= tv 0))
16916 (and (not delay) (<= tv 0)))
16917 ;; Enforce this value no matter what
16918 (- tv))
16919 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16920 ;; lead time is specified.
16921 (floor (* (string-to-number (match-string 1 ts))
16922 (cdr (assoc (match-string 2 ts)
16923 '(("d" . 1) ("w" . 7)
16924 ("m" . 30.4) ("y" . 365.25)
16925 ("h" . 0.041667)))))))
16926 ;; go for the default.
16927 (t tv))))
16929 (defun org-calendar-select-mouse (ev)
16930 "Return to `org-read-date' with the date currently selected.
16931 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16932 (interactive "e")
16933 (mouse-set-point ev)
16934 (when (calendar-cursor-to-date)
16935 (let* ((date (calendar-cursor-to-date))
16936 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16937 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16938 (if (active-minibuffer-window) (exit-minibuffer))))
16940 (defun org-check-deadlines (ndays)
16941 "Check if there are any deadlines due or past due.
16942 A deadline is considered due if it happens within `org-deadline-warning-days'
16943 days from today's date. If the deadline appears in an entry marked DONE,
16944 it is not shown. The prefix arg NDAYS can be used to test that many
16945 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16946 (interactive "P")
16947 (let* ((org-warn-days
16948 (cond
16949 ((equal ndays '(4)) 100000)
16950 (ndays (prefix-numeric-value ndays))
16951 (t (abs org-deadline-warning-days))))
16952 (case-fold-search nil)
16953 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16954 (callback
16955 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16957 (message "%d deadlines past-due or due within %d days"
16958 (org-occur regexp nil callback)
16959 org-warn-days)))
16961 (defsubst org-re-timestamp (type)
16962 "Return a regexp for timestamp TYPE.
16963 Allowed values for TYPE are:
16965 all: all timestamps
16966 active: only active timestamps (<...>)
16967 inactive: only inactive timestamps ([...])
16968 scheduled: only scheduled timestamps
16969 deadline: only deadline timestamps
16970 closed: only closed time-stamps
16972 When TYPE is nil, fall back on returning a regexp that matches
16973 both scheduled and deadline timestamps."
16974 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16975 ((eq type 'active) org-ts-regexp)
16976 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16977 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16978 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16979 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16980 ((eq type 'scheduled-or-deadline)
16981 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16983 (defun org-check-before-date (date)
16984 "Check if there are deadlines or scheduled entries before DATE."
16985 (interactive (list (org-read-date)))
16986 (let ((case-fold-search nil)
16987 (regexp (org-re-timestamp org-ts-type))
16988 (callback
16989 (lambda () (time-less-p
16990 (org-time-string-to-time (match-string 1))
16991 (org-time-string-to-time date)))))
16992 (message "%d entries before %s"
16993 (org-occur regexp nil callback) date)))
16995 (defun org-check-after-date (date)
16996 "Check if there are deadlines or scheduled entries after DATE."
16997 (interactive (list (org-read-date)))
16998 (let ((case-fold-search nil)
16999 (regexp (org-re-timestamp org-ts-type))
17000 (callback
17001 (lambda () (not
17002 (time-less-p
17003 (org-time-string-to-time (match-string 1))
17004 (org-time-string-to-time date))))))
17005 (message "%d entries after %s"
17006 (org-occur regexp nil callback) date)))
17008 (defun org-check-dates-range (start-date end-date)
17009 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17010 (interactive (list (org-read-date nil nil nil "Range starts")
17011 (org-read-date nil nil nil "Range end")))
17012 (let ((case-fold-search nil)
17013 (regexp (org-re-timestamp org-ts-type))
17014 (callback
17015 (lambda ()
17016 (let ((match (match-string 1)))
17017 (and
17018 (not (time-less-p
17019 (org-time-string-to-time match)
17020 (org-time-string-to-time start-date)))
17021 (time-less-p
17022 (org-time-string-to-time match)
17023 (org-time-string-to-time end-date)))))))
17024 (message "%d entries between %s and %s"
17025 (org-occur regexp nil callback) start-date end-date)))
17027 (defun org-evaluate-time-range (&optional to-buffer)
17028 "Evaluate a time range by computing the difference between start and end.
17029 Normally the result is just printed in the echo area, but with prefix arg
17030 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17031 If the time range is actually in a table, the result is inserted into the
17032 next column.
17033 For time difference computation, a year is assumed to be exactly 365
17034 days in order to avoid rounding problems."
17035 (interactive "P")
17037 (org-clock-update-time-maybe)
17038 (save-excursion
17039 (unless (org-at-date-range-p t)
17040 (goto-char (point-at-bol))
17041 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17042 (if (not (org-at-date-range-p t))
17043 (user-error "Not at a time-stamp range, and none found in current line")))
17044 (let* ((ts1 (match-string 1))
17045 (ts2 (match-string 2))
17046 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17047 (match-end (match-end 0))
17048 (time1 (org-time-string-to-time ts1))
17049 (time2 (org-time-string-to-time ts2))
17050 (t1 (org-float-time time1))
17051 (t2 (org-float-time time2))
17052 (diff (abs (- t2 t1)))
17053 (negative (< (- t2 t1) 0))
17054 ;; (ys (floor (* 365 24 60 60)))
17055 (ds (* 24 60 60))
17056 (hs (* 60 60))
17057 (fy "%dy %dd %02d:%02d")
17058 (fy1 "%dy %dd")
17059 (fd "%dd %02d:%02d")
17060 (fd1 "%dd")
17061 (fh "%02d:%02d")
17062 y d h m align)
17063 (if havetime
17064 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17066 d (floor (/ diff ds)) diff (mod diff ds)
17067 h (floor (/ diff hs)) diff (mod diff hs)
17068 m (floor (/ diff 60)))
17069 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17071 d (floor (+ (/ diff ds) 0.5))
17072 h 0 m 0))
17073 (if (not to-buffer)
17074 (message "%s" (org-make-tdiff-string y d h m))
17075 (if (org-at-table-p)
17076 (progn
17077 (goto-char match-end)
17078 (setq align t)
17079 (and (looking-at " *|") (goto-char (match-end 0))))
17080 (goto-char match-end))
17081 (if (looking-at
17082 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17083 (replace-match ""))
17084 (if negative (insert " -"))
17085 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17086 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17087 (insert " " (format fh h m))))
17088 (if align (org-table-align))
17089 (message "Time difference inserted")))))
17091 (defun org-make-tdiff-string (y d h m)
17092 (let ((fmt "")
17093 (l nil))
17094 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17095 l (push y l)))
17096 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17097 l (push d l)))
17098 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17099 l (push h l)))
17100 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17101 l (push m l)))
17102 (apply 'format fmt (nreverse l))))
17104 (defun org-time-string-to-time (s &optional buffer pos)
17105 "Convert a timestamp string into internal time."
17106 (condition-case errdata
17107 (apply 'encode-time (org-parse-time-string s))
17108 (error (error "Bad timestamp `%s'%s\nError was: %s"
17109 s (if (not (and buffer pos))
17111 (format " at %d in buffer `%s'" pos buffer))
17112 (cdr errdata)))))
17114 (defun org-time-string-to-seconds (s)
17115 "Convert a timestamp string to a number of seconds."
17116 (org-float-time (org-time-string-to-time s)))
17118 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17119 "Convert a time stamp to an absolute day number.
17120 If there is a specifier for a cyclic time stamp, get the closest
17121 date to DAYNR.
17122 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17123 The variable `date' is bound by the calendar when this is called."
17124 (cond
17125 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17126 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17127 daynr
17128 (+ daynr 1000)))
17129 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17130 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17131 (time-to-days (current-time))) (match-string 0 s)
17132 prefer show-all))
17133 (t (time-to-days
17134 (condition-case errdata
17135 (apply 'encode-time (org-parse-time-string s))
17136 (error (error "Bad timestamp `%s'%s\nError was: %s"
17137 s (if (not (and buffer pos))
17139 (format " at %d in buffer `%s'" pos buffer))
17140 (cdr errdata))))))))
17142 (defun org-days-to-iso-week (days)
17143 "Return the iso week number."
17144 (require 'cal-iso)
17145 (car (calendar-iso-from-absolute days)))
17147 (defun org-small-year-to-year (year)
17148 "Convert 2-digit years into 4-digit years.
17149 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17150 The year 2000 cannot be abbreviated. Any year larger than 99
17151 is returned unchanged."
17152 (if (< year 38)
17153 (setq year (+ 2000 year))
17154 (if (< year 100)
17155 (setq year (+ 1900 year))))
17156 year)
17158 (defun org-time-from-absolute (d)
17159 "Return the time corresponding to date D.
17160 D may be an absolute day number, or a calendar-type list (month day year)."
17161 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17162 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17164 (defun org-calendar-holiday ()
17165 "List of holidays, for Diary display in Org-mode."
17166 (require 'holidays)
17167 (let ((hl (funcall
17168 (if (fboundp 'calendar-check-holidays)
17169 'calendar-check-holidays 'check-calendar-holidays) date)))
17170 (if hl (mapconcat 'identity hl "; "))))
17172 (defun org-diary-sexp-entry (sexp entry date)
17173 "Process a SEXP diary ENTRY for DATE."
17174 (require 'diary-lib)
17175 (let ((result (if calendar-debug-sexp
17176 (let ((stack-trace-on-error t))
17177 (eval (car (read-from-string sexp))))
17178 (condition-case nil
17179 (eval (car (read-from-string sexp)))
17180 (error
17181 (beep)
17182 (message "Bad sexp at line %d in %s: %s"
17183 (org-current-line)
17184 (buffer-file-name) sexp)
17185 (sleep-for 2))))))
17186 (cond ((stringp result) (split-string result "; "))
17187 ((and (consp result)
17188 (not (consp (cdr result)))
17189 (stringp (cdr result))) (cdr result))
17190 ((and (consp result)
17191 (stringp (car result))) result)
17192 (result entry))))
17194 (defun org-diary-to-ical-string (frombuf)
17195 "Get iCalendar entries from diary entries in buffer FROMBUF.
17196 This uses the icalendar.el library."
17197 (let* ((tmpdir (if (featurep 'xemacs)
17198 (temp-directory)
17199 temporary-file-directory))
17200 (tmpfile (make-temp-name
17201 (expand-file-name "orgics" tmpdir)))
17202 buf rtn b e)
17203 (with-current-buffer frombuf
17204 (icalendar-export-region (point-min) (point-max) tmpfile)
17205 (setq buf (find-buffer-visiting tmpfile))
17206 (set-buffer buf)
17207 (goto-char (point-min))
17208 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17209 (setq b (match-beginning 0)))
17210 (goto-char (point-max))
17211 (if (re-search-backward "^END:VEVENT" nil t)
17212 (setq e (match-end 0)))
17213 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17214 (kill-buffer buf)
17215 (delete-file tmpfile)
17216 rtn))
17218 (defun org-closest-date (start current change prefer show-all)
17219 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17220 When PREFER is `past', return a date that is either CURRENT or past.
17221 When PREFER is `future', return a date that is either CURRENT or future.
17222 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17223 ;; Make the proper lists from the dates
17224 (catch 'exit
17225 (let ((a1 '(("h" . hour)
17226 ("d" . day)
17227 ("w" . week)
17228 ("m" . month)
17229 ("y" . year)))
17230 (shour (nth 2 (org-parse-time-string start)))
17231 dn dw sday cday n1 n2 n0
17232 d m y y1 y2 date1 date2 nmonths nm ny m2)
17234 (setq start (org-date-to-gregorian start)
17235 current (org-date-to-gregorian
17236 (if show-all
17237 current
17238 (time-to-days (current-time))))
17239 sday (calendar-absolute-from-gregorian start)
17240 cday (calendar-absolute-from-gregorian current))
17242 (if (<= cday sday) (throw 'exit sday))
17244 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17245 (setq dn (string-to-number (match-string 1 change))
17246 dw (cdr (assoc (match-string 2 change) a1)))
17247 (user-error "Invalid change specifier: %s" change))
17248 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17249 (cond
17250 ((eq dw 'hour)
17251 (let ((missing-hours
17252 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17253 dn)))
17254 (setq n1 (if (zerop missing-hours) cday
17255 (- cday (1+ (floor (/ missing-hours 24)))))
17256 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17257 ((eq dw 'day)
17258 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17259 n2 (+ n1 dn)))
17260 ((eq dw 'year)
17261 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17262 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17263 (setq date1 (list m d y1)
17264 n1 (calendar-absolute-from-gregorian date1)
17265 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17266 n2 (calendar-absolute-from-gregorian date2)))
17267 ((eq dw 'month)
17268 ;; approx number of month between the two dates
17269 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17270 ;; How often does dn fit in there?
17271 (setq d (nth 1 start) m (car start) y (nth 2 start)
17272 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17273 m (+ m nm)
17274 ny (floor (/ m 12))
17275 y (+ y ny)
17276 m (- m (* ny 12)))
17277 (while (> m 12) (setq m (- m 12) y (1+ y)))
17278 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17279 (setq m2 (+ m dn) y2 y)
17280 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17281 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17282 (while (<= n2 cday)
17283 (setq n1 n2 m m2 y y2)
17284 (setq m2 (+ m dn) y2 y)
17285 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17286 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17287 ;; Make sure n1 is the earlier date
17288 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17289 (if show-all
17290 (cond
17291 ((eq prefer 'past) (if (= cday n2) n2 n1))
17292 ((eq prefer 'future) (if (= cday n1) n1 n2))
17293 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17294 (cond
17295 ((eq prefer 'past) (if (= cday n2) n2 n1))
17296 ((eq prefer 'future) (if (= cday n1) n1 n2))
17297 (t (if (= cday n1) n1 n2)))))))
17299 (defun org-date-to-gregorian (date)
17300 "Turn any specification of DATE into a Gregorian date for the calendar."
17301 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17302 ((and (listp date) (= (length date) 3)) date)
17303 ((stringp date)
17304 (setq date (org-parse-time-string date))
17305 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17306 ((listp date)
17307 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17309 (defun org-parse-time-string (s &optional nodefault)
17310 "Parse the standard Org-mode time string.
17311 This should be a lot faster than the normal `parse-time-string'.
17312 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17313 hour and minute fields will be nil if not given."
17314 (cond ((string-match org-ts-regexp0 s)
17315 (list 0
17316 (if (or (match-beginning 8) (not nodefault))
17317 (string-to-number (or (match-string 8 s) "0")))
17318 (if (or (match-beginning 7) (not nodefault))
17319 (string-to-number (or (match-string 7 s) "0")))
17320 (string-to-number (match-string 4 s))
17321 (string-to-number (match-string 3 s))
17322 (string-to-number (match-string 2 s))
17323 nil nil nil))
17324 ((string-match "^<[^>]+>$" s)
17325 (decode-time (seconds-to-time (org-matcher-time s))))
17326 (t (error "Not a standard Org-mode time string: %s" s))))
17328 (defun org-timestamp-up (&optional arg)
17329 "Increase the date item at the cursor by one.
17330 If the cursor is on the year, change the year. If it is on the month,
17331 the day or the time, change that.
17332 With prefix ARG, change by that many units."
17333 (interactive "p")
17334 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17336 (defun org-timestamp-down (&optional arg)
17337 "Decrease the date item at the cursor by one.
17338 If the cursor is on the year, change the year. If it is on the month,
17339 the day or the time, change that.
17340 With prefix ARG, change by that many units."
17341 (interactive "p")
17342 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17344 (defun org-timestamp-up-day (&optional arg)
17345 "Increase the date in the time stamp by one day.
17346 With prefix ARG, change that many days."
17347 (interactive "p")
17348 (if (and (not (org-at-timestamp-p t))
17349 (org-at-heading-p))
17350 (org-todo 'up)
17351 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17353 (defun org-timestamp-down-day (&optional arg)
17354 "Decrease the date in the time stamp by one day.
17355 With prefix ARG, change that many days."
17356 (interactive "p")
17357 (if (and (not (org-at-timestamp-p t))
17358 (org-at-heading-p))
17359 (org-todo 'down)
17360 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17362 (defun org-at-timestamp-p (&optional inactive-ok)
17363 "Determine if the cursor is in or at a timestamp."
17364 (interactive)
17365 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17366 (pos (point))
17367 (ans (or (looking-at tsr)
17368 (save-excursion
17369 (skip-chars-backward "^[<\n\r\t")
17370 (if (> (point) (point-min)) (backward-char 1))
17371 (and (looking-at tsr)
17372 (> (- (match-end 0) pos) -1))))))
17373 (and ans
17374 (boundp 'org-ts-what)
17375 (setq org-ts-what
17376 (cond
17377 ((= pos (match-beginning 0)) 'bracket)
17378 ;; Point is considered to be "on the bracket" whether
17379 ;; it's really on it or right after it.
17380 ((= pos (1- (match-end 0))) 'bracket)
17381 ((= pos (match-end 0)) 'after)
17382 ((org-pos-in-match-range pos 2) 'year)
17383 ((org-pos-in-match-range pos 3) 'month)
17384 ((org-pos-in-match-range pos 7) 'hour)
17385 ((org-pos-in-match-range pos 8) 'minute)
17386 ((or (org-pos-in-match-range pos 4)
17387 (org-pos-in-match-range pos 5)) 'day)
17388 ((and (> pos (or (match-end 8) (match-end 5)))
17389 (< pos (match-end 0)))
17390 (- pos (or (match-end 8) (match-end 5))))
17391 (t 'day))))
17392 ans))
17394 (defun org-toggle-timestamp-type ()
17395 "Toggle the type (<active> or [inactive]) of a time stamp."
17396 (interactive)
17397 (when (org-at-timestamp-p t)
17398 (let ((beg (match-beginning 0)) (end (match-end 0))
17399 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17400 (save-excursion
17401 (goto-char beg)
17402 (while (re-search-forward "[][<>]" end t)
17403 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17404 t t)))
17405 (message "Timestamp is now %sactive"
17406 (if (equal (char-after beg) ?<) "" "in")))))
17408 (defun org-at-clock-log-p nil
17409 "Is the cursor on the clock log line?"
17410 (save-excursion
17411 (move-beginning-of-line 1)
17412 (looking-at "^[ \t]*CLOCK:")))
17414 (defvar org-clock-history) ; defined in org-clock.el
17415 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17416 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17417 "Change the date in the time stamp at point.
17418 The date will be changed by N times WHAT. WHAT can be `day', `month',
17419 `year', `minute', `second'. If WHAT is not given, the cursor position
17420 in the timestamp determines what will be changed.
17421 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17422 (let ((origin (point)) origin-cat
17423 with-hm inactive
17424 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17425 org-ts-what
17426 extra rem
17427 ts time time0 fixnext clrgx)
17428 (if (not (org-at-timestamp-p t))
17429 (user-error "Not at a timestamp"))
17430 (if (and (not what) (eq org-ts-what 'bracket))
17431 (org-toggle-timestamp-type)
17432 ;; Point isn't on brackets. Remember the part of the time-stamp
17433 ;; the point was in. Indeed, size of time-stamps may change,
17434 ;; but point must be kept in the same category nonetheless.
17435 (setq origin-cat org-ts-what)
17436 (if (and (not what) (not (eq org-ts-what 'day))
17437 org-display-custom-times
17438 (get-text-property (point) 'display)
17439 (not (get-text-property (1- (point)) 'display)))
17440 (setq org-ts-what 'day))
17441 (setq org-ts-what (or what org-ts-what)
17442 inactive (= (char-after (match-beginning 0)) ?\[)
17443 ts (match-string 0))
17444 (replace-match "")
17445 (when (string-match
17446 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17448 (setq extra (match-string 1 ts))
17449 (if suppress-tmp-delay
17450 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17451 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17452 (setq with-hm t))
17453 (setq time0 (org-parse-time-string ts))
17454 (when (and updown
17455 (eq org-ts-what 'minute)
17456 (not current-prefix-arg))
17457 ;; This looks like s-up and s-down. Change by one rounding step.
17458 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17459 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17460 (setcar (cdr time0) (+ (nth 1 time0)
17461 (if (> n 0) (- rem) (- dm rem))))))
17462 (setq time
17463 (encode-time (or (car time0) 0)
17464 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17465 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17466 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17467 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17468 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17469 (nthcdr 6 time0)))
17470 (when (and (member org-ts-what '(hour minute))
17471 extra
17472 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17473 (setq extra (org-modify-ts-extra
17474 extra
17475 (if (eq org-ts-what 'hour) 2 5)
17476 n dm)))
17477 (when (integerp org-ts-what)
17478 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17479 (if (eq what 'calendar)
17480 (let ((cal-date (org-get-date-from-calendar)))
17481 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17482 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17483 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17484 (setcar time0 (or (car time0) 0))
17485 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17486 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17487 (setq time (apply 'encode-time time0))))
17488 ;; Insert the new time-stamp, and ensure point stays in the same
17489 ;; category as before (i.e. not after the last position in that
17490 ;; category).
17491 (let ((pos (point)))
17492 ;; Stay before inserted string. `save-excursion' is of no use.
17493 (setq org-last-changed-timestamp
17494 (org-insert-time-stamp time with-hm inactive nil nil extra))
17495 (goto-char pos))
17496 (save-match-data
17497 (looking-at org-ts-regexp3)
17498 (goto-char (cond
17499 ;; `day' category ends before `hour' if any, or at
17500 ;; the end of the day name.
17501 ((eq origin-cat 'day)
17502 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17503 ((eq origin-cat 'hour) (min (match-end 7) origin))
17504 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17505 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17506 ;; `year' and `month' have both fixed size: point
17507 ;; couldn't have moved into another part.
17508 (t origin))))
17509 ;; Update clock if on a CLOCK line.
17510 (org-clock-update-time-maybe)
17511 ;; Maybe adjust the closest clock in `org-clock-history'
17512 (when org-clock-adjust-closest
17513 (if (not (and (org-at-clock-log-p)
17514 (< 1 (length (delq nil (mapcar 'marker-position
17515 org-clock-history))))))
17516 (message "No clock to adjust")
17517 (cond ((save-excursion ; fix previous clock?
17518 (re-search-backward org-ts-regexp0 nil t)
17519 (org-looking-back (concat org-clock-string " \\[")))
17520 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17521 ((save-excursion ; fix next clock?
17522 (re-search-backward org-ts-regexp0 nil t)
17523 (looking-at (concat org-ts-regexp0 "\\] =>")))
17524 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17525 (save-window-excursion
17526 ;; Find closest clock to point, adjust the previous/next one in history
17527 (let* ((p (save-excursion (org-back-to-heading t)))
17528 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17529 (clfixnth
17530 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17531 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17532 (if (not clfixpos)
17533 (message "No clock to adjust")
17534 (save-excursion
17535 (org-goto-marker-or-bmk clfixpos)
17536 (org-show-subtree)
17537 (when (re-search-forward clrgx nil t)
17538 (goto-char (match-beginning 1))
17539 (let (org-clock-adjust-closest)
17540 (org-timestamp-change n org-ts-what updown))
17541 (message "Clock adjusted in %s for heading: %s"
17542 (file-name-nondirectory (buffer-file-name))
17543 (org-get-heading t t)))))))))
17544 ;; Try to recenter the calendar window, if any.
17545 (if (and org-calendar-follow-timestamp-change
17546 (get-buffer-window "*Calendar*" t)
17547 (memq org-ts-what '(day month year)))
17548 (org-recenter-calendar (time-to-days time))))))
17550 (defun org-modify-ts-extra (s pos n dm)
17551 "Change the different parts of the lead-time and repeat fields in timestamp."
17552 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17553 ng h m new rem)
17554 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17555 (cond
17556 ((or (org-pos-in-match-range pos 2)
17557 (org-pos-in-match-range pos 3))
17558 (setq m (string-to-number (match-string 3 s))
17559 h (string-to-number (match-string 2 s)))
17560 (if (org-pos-in-match-range pos 2)
17561 (setq h (+ h n))
17562 (setq n (* dm (org-no-warnings (signum n))))
17563 (when (not (= 0 (setq rem (% m dm))))
17564 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17565 (setq m (+ m n)))
17566 (if (< m 0) (setq m (+ m 60) h (1- h)))
17567 (if (> m 59) (setq m (- m 60) h (1+ h)))
17568 (setq h (min 24 (max 0 h)))
17569 (setq ng 1 new (format "-%02d:%02d" h m)))
17570 ((org-pos-in-match-range pos 6)
17571 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17572 ((org-pos-in-match-range pos 5)
17573 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17575 ((org-pos-in-match-range pos 9)
17576 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17577 ((org-pos-in-match-range pos 8)
17578 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17580 (when ng
17581 (setq s (concat
17582 (substring s 0 (match-beginning ng))
17584 (substring s (match-end ng))))))
17587 (defun org-recenter-calendar (date)
17588 "If the calendar is visible, recenter it to DATE."
17589 (let ((cwin (get-buffer-window "*Calendar*" t)))
17590 (when cwin
17591 (let ((calendar-move-hook nil))
17592 (with-selected-window cwin
17593 (calendar-goto-date (if (listp date) date
17594 (calendar-gregorian-from-absolute date))))))))
17596 (defun org-goto-calendar (&optional arg)
17597 "Go to the Emacs calendar at the current date.
17598 If there is a time stamp in the current line, go to that date.
17599 A prefix ARG can be used to force the current date."
17600 (interactive "P")
17601 (let ((tsr org-ts-regexp) diff
17602 (calendar-move-hook nil)
17603 (calendar-view-holidays-initially-flag nil)
17604 (calendar-view-diary-initially-flag nil))
17605 (if (or (org-at-timestamp-p)
17606 (save-excursion
17607 (beginning-of-line 1)
17608 (looking-at (concat ".*" tsr))))
17609 (let ((d1 (time-to-days (current-time)))
17610 (d2 (time-to-days
17611 (org-time-string-to-time (match-string 1)))))
17612 (setq diff (- d2 d1))))
17613 (calendar)
17614 (calendar-goto-today)
17615 (if (and diff (not arg)) (calendar-forward-day diff))))
17617 (defun org-get-date-from-calendar ()
17618 "Return a list (month day year) of date at point in calendar."
17619 (with-current-buffer "*Calendar*"
17620 (save-match-data
17621 (calendar-cursor-to-date))))
17623 (defun org-date-from-calendar ()
17624 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17625 If there is already a time stamp at the cursor position, update it."
17626 (interactive)
17627 (if (org-at-timestamp-p t)
17628 (org-timestamp-change 0 'calendar)
17629 (let ((cal-date (org-get-date-from-calendar)))
17630 (org-insert-time-stamp
17631 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17633 (defcustom org-effort-durations
17634 `(("h" . 60)
17635 ("d" . ,(* 60 8))
17636 ("w" . ,(* 60 8 5))
17637 ("m" . ,(* 60 8 5 4))
17638 ("y" . ,(* 60 8 5 40)))
17639 "Conversion factor to minutes for an effort modifier.
17641 Each entry has the form (MODIFIER . MINUTES).
17643 In an effort string, a number followed by MODIFIER is multiplied
17644 by the specified number of MINUTES to obtain an effort in
17645 minutes.
17647 For example, if the value of this variable is ((\"hours\" . 60)), then an
17648 effort string \"2hours\" is equivalent to 120 minutes."
17649 :group 'org-agenda
17650 :version "24.1"
17651 :type '(alist :key-type (string :tag "Modifier")
17652 :value-type (number :tag "Minutes")))
17654 (defun org-minutes-to-clocksum-string (m)
17655 "Format number of minutes as a clocksum string.
17656 The format is determined by `org-time-clocksum-format',
17657 `org-time-clocksum-use-fractional' and
17658 `org-time-clocksum-fractional-format' and
17659 `org-time-clocksum-use-effort-durations'."
17660 (let ((clocksum "")
17661 (m (round m)) ; Don't allow fractions of minutes
17662 h d w mo y fmt n)
17663 (setq h (if org-time-clocksum-use-effort-durations
17664 (cdr (assoc "h" org-effort-durations)) 60)
17665 d (if org-time-clocksum-use-effort-durations
17666 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17667 w (if org-time-clocksum-use-effort-durations
17668 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17669 mo (if org-time-clocksum-use-effort-durations
17670 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17671 y (if org-time-clocksum-use-effort-durations
17672 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17673 ;; fractional format
17674 (if org-time-clocksum-use-fractional
17675 (cond
17676 ;; single format string
17677 ((stringp org-time-clocksum-fractional-format)
17678 (format org-time-clocksum-fractional-format (/ m (float h))))
17679 ;; choice of fractional formats for different time units
17680 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17681 (> (/ (truncate m) (* y d h)) 0))
17682 (format fmt (/ m (* y d (float h)))))
17683 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17684 (> (/ (truncate m) (* mo d h)) 0))
17685 (format fmt (/ m (* mo d (float h)))))
17686 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17687 (> (/ (truncate m) (* w d h)) 0))
17688 (format fmt (/ m (* w d (float h)))))
17689 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17690 (> (/ (truncate m) (* d h)) 0))
17691 (format fmt (/ m (* d (float h)))))
17692 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17693 (> (/ (truncate m) h) 0))
17694 (format fmt (/ m (float h))))
17695 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17696 (format fmt m))
17697 ;; fall back to smallest time unit with a format
17698 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17699 (format fmt (/ m (float h))))
17700 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17701 (format fmt (/ m (* d (float h)))))
17702 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17703 (format fmt (/ m (* w d (float h)))))
17704 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17705 (format fmt (/ m (* mo d (float h)))))
17706 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17707 (format fmt (/ m (* y d (float h))))))
17708 ;; standard (non-fractional) format, with single format string
17709 (if (stringp org-time-clocksum-format)
17710 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17711 ;; separate formats components
17712 (and (setq fmt (plist-get org-time-clocksum-format :years))
17713 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17714 (plist-get org-time-clocksum-format :require-years))
17715 (setq clocksum (concat clocksum (format fmt n))
17716 m (- m (* n y d h))))
17717 (and (setq fmt (plist-get org-time-clocksum-format :months))
17718 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17719 (plist-get org-time-clocksum-format :require-months))
17720 (setq clocksum (concat clocksum (format fmt n))
17721 m (- m (* n mo d h))))
17722 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17723 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17724 (plist-get org-time-clocksum-format :require-weeks))
17725 (setq clocksum (concat clocksum (format fmt n))
17726 m (- m (* n w d h))))
17727 (and (setq fmt (plist-get org-time-clocksum-format :days))
17728 (or (> (setq n (/ (truncate m) (* d h))) 0)
17729 (plist-get org-time-clocksum-format :require-days))
17730 (setq clocksum (concat clocksum (format fmt n))
17731 m (- m (* n d h))))
17732 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17733 (or (> (setq n (/ (truncate m) h)) 0)
17734 (plist-get org-time-clocksum-format :require-hours))
17735 (setq clocksum (concat clocksum (format fmt n))
17736 m (- m (* n h))))
17737 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17738 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17739 (setq clocksum (concat clocksum (format fmt m))))
17740 ;; return formatted time duration
17741 clocksum))))
17743 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17744 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17745 "Org mode version 8.0")
17747 (defun org-hours-to-clocksum-string (n)
17748 (org-minutes-to-clocksum-string (* n 60)))
17750 (defun org-hh:mm-string-to-minutes (s)
17751 "Convert a string H:MM to a number of minutes.
17752 If the string is just a number, interpret it as minutes.
17753 In fact, the first hh:mm or number in the string will be taken,
17754 there can be extra stuff in the string.
17755 If no number is found, the return value is 0."
17756 (cond
17757 ((integerp s) s)
17758 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17759 (+ (* (string-to-number (match-string 1 s)) 60)
17760 (string-to-number (match-string 2 s))))
17761 ((string-match "\\([0-9]+\\)" s)
17762 (string-to-number (match-string 1 s)))
17763 (t 0)))
17765 (defcustom org-image-actual-width t
17766 "Should we use the actual width of images when inlining them?
17768 When set to `t', always use the image width.
17770 When set to a number, use imagemagick (when available) to set
17771 the image's width to this value.
17773 When set to a number in a list, try to get the width from any
17774 #+ATTR.* keyword if it matches a width specification like
17776 #+ATTR_HTML: :width 300px
17778 and fall back on that number if none is found.
17780 When set to nil, try to get the width from an #+ATTR.* keyword
17781 and fall back on the original width if none is found.
17783 This requires Emacs >= 24.1, build with imagemagick support."
17784 :group 'org-appearance
17785 :version "24.4"
17786 :package-version '(Org . "8.0")
17787 :type '(choice
17788 (const :tag "Use the image width" t)
17789 (integer :tag "Use a number of pixels")
17790 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17791 (const :tag "Use #+ATTR* or don't resize" nil)))
17793 (defcustom org-agenda-inhibit-startup nil
17794 "Inhibit startup when preparing agenda buffers.
17795 When this variable is `t' (the default), the initialization of
17796 the Org agenda buffers is inhibited: e.g. the visibility state
17797 is not set, the tables are not re-aligned, etc."
17798 :type 'boolean
17799 :version "24.3"
17800 :group 'org-agenda)
17802 (defcustom org-agenda-ignore-drawer-properties nil
17803 "Avoid updating text properties when building the agenda.
17804 Properties are used to prepare buffers for effort estimates, appointments,
17805 and subtree-local categories.
17806 If you don't use these in the agenda, you can add them to this list and
17807 agenda building will be a bit faster.
17808 The value is a list, with zero or more of the symbols `effort', `appt',
17809 or `category'."
17810 :type '(set :greedy t
17811 (const effort)
17812 (const appt)
17813 (const category))
17814 :version "24.3"
17815 :group 'org-agenda)
17817 (defun org-duration-string-to-minutes (s &optional output-to-string)
17818 "Convert a duration string S to minutes.
17820 A bare number is interpreted as minutes, modifiers can be set by
17821 customizing `org-effort-durations' (which see).
17823 Entries containing a colon are interpreted as H:MM by
17824 `org-hh:mm-string-to-minutes'."
17825 (let ((result 0)
17826 (re (concat "\\([0-9.]+\\) *\\("
17827 (regexp-opt (mapcar 'car org-effort-durations))
17828 "\\)")))
17829 (while (string-match re s)
17830 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17831 (string-to-number (match-string 1 s))))
17832 (setq s (replace-match "" nil t s)))
17833 (setq result (floor result))
17834 (incf result (org-hh:mm-string-to-minutes s))
17835 (if output-to-string (number-to-string result) result)))
17837 ;;;; Files
17839 (defun org-save-all-org-buffers ()
17840 "Save all Org-mode buffers without user confirmation."
17841 (interactive)
17842 (message "Saving all Org-mode buffers...")
17843 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17844 (when (featurep 'org-id) (org-id-locations-save))
17845 (message "Saving all Org-mode buffers... done"))
17847 (defun org-revert-all-org-buffers ()
17848 "Revert all Org-mode buffers.
17849 Prompt for confirmation when there are unsaved changes.
17850 Be sure you know what you are doing before letting this function
17851 overwrite your changes.
17853 This function is useful in a setup where one tracks org files
17854 with a version control system, to revert on one machine after pulling
17855 changes from another. I believe the procedure must be like this:
17857 1. M-x org-save-all-org-buffers
17858 2. Pull changes from the other machine, resolve conflicts
17859 3. M-x org-revert-all-org-buffers"
17860 (interactive)
17861 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17862 (user-error "Abort"))
17863 (save-excursion
17864 (save-window-excursion
17865 (mapc
17866 (lambda (b)
17867 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17868 (with-current-buffer b buffer-file-name))
17869 (org-pop-to-buffer-same-window b)
17870 (revert-buffer t 'no-confirm)))
17871 (buffer-list))
17872 (when (and (featurep 'org-id) org-id-track-globally)
17873 (org-id-locations-load)))))
17875 ;;;; Agenda files
17877 ;;;###autoload
17878 (defun org-switchb (&optional arg)
17879 "Switch between Org buffers.
17880 With one prefix argument, restrict available buffers to files.
17881 With two prefix arguments, restrict available buffers to agenda files.
17883 Defaults to `iswitchb' for buffer name completion.
17884 Set `org-completion-use-ido' to make it use ido instead."
17885 (interactive "P")
17886 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17887 ((equal arg '(16)) (org-buffer-list 'agenda))
17888 (t (org-buffer-list))))
17889 (org-completion-use-iswitchb org-completion-use-iswitchb)
17890 (org-completion-use-ido org-completion-use-ido))
17891 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17892 (setq org-completion-use-iswitchb t))
17893 (org-pop-to-buffer-same-window
17894 (org-icompleting-read "Org buffer: "
17895 (mapcar 'list (mapcar 'buffer-name blist))
17896 nil t))))
17898 ;;; Define some older names previously used for this functionality
17899 ;;;###autoload
17900 (defalias 'org-ido-switchb 'org-switchb)
17901 ;;;###autoload
17902 (defalias 'org-iswitchb 'org-switchb)
17904 (defun org-buffer-list (&optional predicate exclude-tmp)
17905 "Return a list of Org buffers.
17906 PREDICATE can be `export', `files' or `agenda'.
17908 export restrict the list to Export buffers.
17909 files restrict the list to buffers visiting Org files.
17910 agenda restrict the list to buffers visiting agenda files.
17912 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17913 (let* ((bfn nil)
17914 (agenda-files (and (eq predicate 'agenda)
17915 (mapcar 'file-truename (org-agenda-files t))))
17916 (filter
17917 (cond
17918 ((eq predicate 'files)
17919 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17920 ((eq predicate 'export)
17921 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17922 ((eq predicate 'agenda)
17923 (lambda (b)
17924 (with-current-buffer b
17925 (and (derived-mode-p 'org-mode)
17926 (setq bfn (buffer-file-name b))
17927 (member (file-truename bfn) agenda-files)))))
17928 (t (lambda (b) (with-current-buffer b
17929 (or (derived-mode-p 'org-mode)
17930 (string-match "\*Org .*Export"
17931 (buffer-name b)))))))))
17932 (delq nil
17933 (mapcar
17934 (lambda(b)
17935 (if (and (funcall filter b)
17936 (or (not exclude-tmp)
17937 (not (string-match "tmp" (buffer-name b)))))
17939 nil))
17940 (buffer-list)))))
17942 (defun org-agenda-files (&optional unrestricted archives)
17943 "Get the list of agenda files.
17944 Optional UNRESTRICTED means return the full list even if a restriction
17945 is currently in place.
17946 When ARCHIVES is t, include all archive files that are really being
17947 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17948 `org-agenda-archives-mode' is t."
17949 (let ((files
17950 (cond
17951 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17952 ((stringp org-agenda-files) (org-read-agenda-file-list))
17953 ((listp org-agenda-files) org-agenda-files)
17954 (t (error "Invalid value of `org-agenda-files'")))))
17955 (setq files (apply 'append
17956 (mapcar (lambda (f)
17957 (if (file-directory-p f)
17958 (directory-files
17959 f t org-agenda-file-regexp)
17960 (list f)))
17961 files)))
17962 (when org-agenda-skip-unavailable-files
17963 (setq files (delq nil
17964 (mapcar (function
17965 (lambda (file)
17966 (and (file-readable-p file) file)))
17967 files))))
17968 (when (or (eq archives t)
17969 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17970 (setq files (org-add-archive-files files)))
17971 files))
17973 (defun org-agenda-file-p (&optional file)
17974 "Return non-nil, if FILE is an agenda file.
17975 If FILE is omitted, use the file associated with the current
17976 buffer."
17977 (member (or file (buffer-file-name))
17978 (org-agenda-files t)))
17980 (defun org-edit-agenda-file-list ()
17981 "Edit the list of agenda files.
17982 Depending on setup, this either uses customize to edit the variable
17983 `org-agenda-files', or it visits the file that is holding the list. In the
17984 latter case, the buffer is set up in a way that saving it automatically kills
17985 the buffer and restores the previous window configuration."
17986 (interactive)
17987 (if (stringp org-agenda-files)
17988 (let ((cw (current-window-configuration)))
17989 (find-file org-agenda-files)
17990 (org-set-local 'org-window-configuration cw)
17991 (org-add-hook 'after-save-hook
17992 (lambda ()
17993 (set-window-configuration
17994 (prog1 org-window-configuration
17995 (kill-buffer (current-buffer))))
17996 (org-install-agenda-files-menu)
17997 (message "New agenda file list installed"))
17998 nil 'local)
17999 (message "%s" (substitute-command-keys
18000 "Edit list and finish with \\[save-buffer]")))
18001 (customize-variable 'org-agenda-files)))
18003 (defun org-store-new-agenda-file-list (list)
18004 "Set new value for the agenda file list and save it correctly."
18005 (if (stringp org-agenda-files)
18006 (let ((fe (org-read-agenda-file-list t)) b u)
18007 (while (setq b (find-buffer-visiting org-agenda-files))
18008 (kill-buffer b))
18009 (with-temp-file org-agenda-files
18010 (insert
18011 (mapconcat
18012 (lambda (f) ;; Keep un-expanded entries.
18013 (if (setq u (assoc f fe))
18014 (cdr u)
18016 list "\n")
18017 "\n")))
18018 (let ((org-mode-hook nil) (org-inhibit-startup t)
18019 (org-insert-mode-line-in-empty-file nil))
18020 (setq org-agenda-files list)
18021 (customize-save-variable 'org-agenda-files org-agenda-files))))
18023 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18024 "Read the list of agenda files from a file.
18025 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18026 filenames, used by `org-store-new-agenda-file-list' to write back
18027 un-expanded file names."
18028 (when (file-directory-p org-agenda-files)
18029 (error "`org-agenda-files' cannot be a single directory"))
18030 (when (stringp org-agenda-files)
18031 (with-temp-buffer
18032 (insert-file-contents org-agenda-files)
18033 (mapcar
18034 (lambda (f)
18035 (let ((e (expand-file-name (substitute-in-file-name f)
18036 org-directory)))
18037 (if pair-with-expansion
18038 (cons e f)
18039 e)))
18040 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18042 ;;;###autoload
18043 (defun org-cycle-agenda-files ()
18044 "Cycle through the files in `org-agenda-files'.
18045 If the current buffer visits an agenda file, find the next one in the list.
18046 If the current buffer does not, find the first agenda file."
18047 (interactive)
18048 (let* ((fs (org-agenda-files t))
18049 (files (append fs (list (car fs))))
18050 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18051 file)
18052 (unless files (user-error "No agenda files"))
18053 (catch 'exit
18054 (while (setq file (pop files))
18055 (if (equal (file-truename file) tcf)
18056 (when (car files)
18057 (find-file (car files))
18058 (throw 'exit t))))
18059 (find-file (car fs)))
18060 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18062 (defun org-agenda-file-to-front (&optional to-end)
18063 "Move/add the current file to the top of the agenda file list.
18064 If the file is not present in the list, it is added to the front. If it is
18065 present, it is moved there. With optional argument TO-END, add/move to the
18066 end of the list."
18067 (interactive "P")
18068 (let ((org-agenda-skip-unavailable-files nil)
18069 (file-alist (mapcar (lambda (x)
18070 (cons (file-truename x) x))
18071 (org-agenda-files t)))
18072 (ctf (file-truename
18073 (or buffer-file-name
18074 (user-error "Please save the current buffer to a file"))))
18075 x had)
18076 (setq x (assoc ctf file-alist) had x)
18078 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18079 (if to-end
18080 (setq file-alist (append (delq x file-alist) (list x)))
18081 (setq file-alist (cons x (delq x file-alist))))
18082 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18083 (org-install-agenda-files-menu)
18084 (message "File %s to %s of agenda file list"
18085 (if had "moved" "added") (if to-end "end" "front"))))
18087 (defun org-remove-file (&optional file)
18088 "Remove current file from the list of files in variable `org-agenda-files'.
18089 These are the files which are being checked for agenda entries.
18090 Optional argument FILE means use this file instead of the current."
18091 (interactive)
18092 (let* ((org-agenda-skip-unavailable-files nil)
18093 (file (or file buffer-file-name
18094 (user-error "Current buffer does not visit a file")))
18095 (true-file (file-truename file))
18096 (afile (abbreviate-file-name file))
18097 (files (delq nil (mapcar
18098 (lambda (x)
18099 (if (equal true-file
18100 (file-truename x))
18101 nil x))
18102 (org-agenda-files t)))))
18103 (if (not (= (length files) (length (org-agenda-files t))))
18104 (progn
18105 (org-store-new-agenda-file-list files)
18106 (org-install-agenda-files-menu)
18107 (message "Removed file: %s" afile))
18108 (message "File was not in list: %s (not removed)" afile))))
18110 (defun org-file-menu-entry (file)
18111 (vector file (list 'find-file file) t))
18113 (defun org-check-agenda-file (file)
18114 "Make sure FILE exists. If not, ask user what to do."
18115 (when (not (file-exists-p file))
18116 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18117 (abbreviate-file-name file))
18118 (let ((r (downcase (read-char-exclusive))))
18119 (cond
18120 ((equal r ?r)
18121 (org-remove-file file)
18122 (throw 'nextfile t))
18123 (t (error "Abort"))))))
18125 (defun org-get-agenda-file-buffer (file)
18126 "Get a buffer visiting FILE. If the buffer needs to be created, add
18127 it to the list of buffers which might be released later."
18128 (let ((buf (org-find-base-buffer-visiting file)))
18129 (if buf
18130 buf ; just return it
18131 ;; Make a new buffer and remember it
18132 (setq buf (find-file-noselect file))
18133 (if buf (push buf org-agenda-new-buffers))
18134 buf)))
18136 (defun org-release-buffers (blist)
18137 "Release all buffers in list, asking the user for confirmation when needed.
18138 When a buffer is unmodified, it is just killed. When modified, it is saved
18139 \(if the user agrees) and then killed."
18140 (let (buf file)
18141 (while (setq buf (pop blist))
18142 (setq file (buffer-file-name buf))
18143 (when (and (buffer-modified-p buf)
18144 file
18145 (y-or-n-p (format "Save file %s? " file)))
18146 (with-current-buffer buf (save-buffer)))
18147 (kill-buffer buf))))
18149 (defun org-agenda-prepare-buffers (files)
18150 "Create buffers for all agenda files, protect archived trees and comments."
18151 (interactive)
18152 (let ((pa '(:org-archived t))
18153 (pc '(:org-comment t))
18154 (pall '(:org-archived t :org-comment t))
18155 (inhibit-read-only t)
18156 (org-inhibit-startup org-agenda-inhibit-startup)
18157 (rea (concat ":" org-archive-tag ":"))
18158 file re pos)
18159 (setq org-tag-alist-for-agenda nil
18160 org-tag-groups-alist-for-agenda nil)
18161 (save-window-excursion
18162 (save-restriction
18163 (while (setq file (pop files))
18164 (catch 'nextfile
18165 (if (bufferp file)
18166 (set-buffer file)
18167 (org-check-agenda-file file)
18168 (set-buffer (org-get-agenda-file-buffer file)))
18169 (widen)
18170 (org-set-regexps-and-options-for-tags)
18171 (setq pos (point))
18172 (goto-char (point-min))
18173 (let ((case-fold-search t))
18174 (when (search-forward "#+setupfile" nil t)
18175 ;; Don't set all regexps and options systematically as
18176 ;; this is only run for setting agenda tags from setup
18177 ;; file
18178 (org-set-regexps-and-options)))
18179 (or (memq 'category org-agenda-ignore-drawer-properties)
18180 (org-refresh-category-properties))
18181 (or (memq 'effort org-agenda-ignore-drawer-properties)
18182 (org-refresh-properties org-effort-property 'org-effort))
18183 (or (memq 'appt org-agenda-ignore-drawer-properties)
18184 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18185 (setq org-todo-keywords-for-agenda
18186 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18187 (setq org-done-keywords-for-agenda
18188 (append org-done-keywords-for-agenda org-done-keywords))
18189 (setq org-todo-keyword-alist-for-agenda
18190 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18191 (setq org-tag-alist-for-agenda
18192 (org-uniquify
18193 (append org-tag-alist-for-agenda
18194 org-tag-alist
18195 org-tag-persistent-alist)))
18196 (if org-group-tags
18197 (setq org-tag-groups-alist-for-agenda
18198 (org-uniquify-alist
18199 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18200 (org-with-silent-modifications
18201 (save-excursion
18202 (remove-text-properties (point-min) (point-max) pall)
18203 (when org-agenda-skip-archived-trees
18204 (goto-char (point-min))
18205 (while (re-search-forward rea nil t)
18206 (if (org-at-heading-p t)
18207 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18208 (goto-char (point-min))
18209 (setq re (format org-heading-keyword-regexp-format
18210 org-comment-string))
18211 (while (re-search-forward re nil t)
18212 (add-text-properties
18213 (match-beginning 0) (org-end-of-subtree t) pc))))
18214 (goto-char pos)))))
18215 (setq org-todo-keywords-for-agenda
18216 (org-uniquify org-todo-keywords-for-agenda))
18217 (setq org-todo-keyword-alist-for-agenda
18218 (org-uniquify org-todo-keyword-alist-for-agenda))))
18221 ;;;; CDLaTeX minor mode
18223 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18224 "Keymap for the minor `org-cdlatex-mode'.")
18226 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18227 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18228 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18229 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18230 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18232 (defvar org-cdlatex-texmathp-advice-is-done nil
18233 "Flag remembering if we have applied the advice to texmathp already.")
18235 (define-minor-mode org-cdlatex-mode
18236 "Toggle the minor `org-cdlatex-mode'.
18237 This mode supports entering LaTeX environment and math in LaTeX fragments
18238 in Org-mode.
18239 \\{org-cdlatex-mode-map}"
18240 nil " OCDL" nil
18241 (when org-cdlatex-mode
18242 (require 'cdlatex)
18243 (run-hooks 'cdlatex-mode-hook)
18244 (cdlatex-compute-tables))
18245 (unless org-cdlatex-texmathp-advice-is-done
18246 (setq org-cdlatex-texmathp-advice-is-done t)
18247 (defadvice texmathp (around org-math-always-on activate)
18248 "Always return t in org-mode buffers.
18249 This is because we want to insert math symbols without dollars even outside
18250 the LaTeX math segments. If Orgmode thinks that point is actually inside
18251 an embedded LaTeX fragment, let texmathp do its job.
18252 \\[org-cdlatex-mode-map]"
18253 (interactive)
18254 (let (p)
18255 (cond
18256 ((not (derived-mode-p 'org-mode)) ad-do-it)
18257 ((eq this-command 'cdlatex-math-symbol)
18258 (setq ad-return-value t
18259 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18261 (let ((p (org-inside-LaTeX-fragment-p)))
18262 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18263 (setq ad-return-value t
18264 texmathp-why '("Org-mode embedded math" . 0))
18265 (if p ad-do-it)))))))))
18267 (defun turn-on-org-cdlatex ()
18268 "Unconditionally turn on `org-cdlatex-mode'."
18269 (org-cdlatex-mode 1))
18271 (defun org-try-cdlatex-tab ()
18272 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18273 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18274 - inside a LaTeX fragment, or
18275 - after the first word in a line, where an abbreviation expansion could
18276 insert a LaTeX environment."
18277 (when org-cdlatex-mode
18278 (cond
18279 ;; Before any word on the line: No expansion possible.
18280 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18281 ;; Just after first word on the line: Expand it. Make sure it
18282 ;; cannot happen on headlines, though.
18283 ((save-excursion
18284 (skip-chars-backward "a-zA-Z0-9*")
18285 (skip-chars-backward " \t")
18286 (and (bolp) (not (org-at-heading-p))))
18287 (cdlatex-tab) t)
18288 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18290 (defun org-cdlatex-underscore-caret (&optional arg)
18291 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18292 Revert to the normal definition outside of these fragments."
18293 (interactive "P")
18294 (if (org-inside-LaTeX-fragment-p)
18295 (call-interactively 'cdlatex-sub-superscript)
18296 (let (org-cdlatex-mode)
18297 (call-interactively (key-binding (vector last-input-event))))))
18299 (defun org-cdlatex-math-modify (&optional arg)
18300 "Execute `cdlatex-math-modify' in LaTeX fragments.
18301 Revert to the normal definition outside of these fragments."
18302 (interactive "P")
18303 (if (org-inside-LaTeX-fragment-p)
18304 (call-interactively 'cdlatex-math-modify)
18305 (let (org-cdlatex-mode)
18306 (call-interactively (key-binding (vector last-input-event))))))
18310 ;;;; LaTeX fragments
18312 (defun org-inside-LaTeX-fragment-p ()
18313 "Test if point is inside a LaTeX fragment.
18314 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18315 sequence appearing also before point.
18316 Even though the matchers for math are configurable, this function assumes
18317 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18318 delimiters are skipped when they have been removed by customization.
18319 The return value is nil, or a cons cell with the delimiter and the
18320 position of this delimiter.
18322 This function does a reasonably good job, but can locally be fooled by
18323 for example currency specifications. For example it will assume being in
18324 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18325 fragments that are properly closed, but during editing, we have to live
18326 with the uncertainty caused by missing closing delimiters. This function
18327 looks only before point, not after."
18328 (catch 'exit
18329 (let ((pos (point))
18330 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18331 (lim (progn
18332 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18333 (point)))
18334 dd-on str (start 0) m re)
18335 (goto-char pos)
18336 (when dodollar
18337 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18338 re (nth 1 (assoc "$" org-latex-regexps)))
18339 (while (string-match re str start)
18340 (cond
18341 ((= (match-end 0) (length str))
18342 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18343 ((= (match-end 0) (- (length str) 5))
18344 (throw 'exit nil))
18345 (t (setq start (match-end 0))))))
18346 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18347 (goto-char pos)
18348 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18349 (and (match-beginning 2) (throw 'exit nil))
18350 ;; count $$
18351 (while (re-search-backward "\\$\\$" lim t)
18352 (setq dd-on (not dd-on)))
18353 (goto-char pos)
18354 (if dd-on (cons "$$" m))))))
18356 (defun org-inside-latex-macro-p ()
18357 "Is point inside a LaTeX macro or its arguments?"
18358 (save-match-data
18359 (org-in-regexp
18360 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18362 (defvar org-latex-fragment-image-overlays nil
18363 "List of overlays carrying the images of latex fragments.")
18364 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18366 (defun org-remove-latex-fragment-image-overlays ()
18367 "Remove all overlays with LaTeX fragment images in current buffer."
18368 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18369 (setq org-latex-fragment-image-overlays nil))
18371 (defun org-preview-latex-fragment (&optional subtree)
18372 "Preview the LaTeX fragment at point, or all locally or globally.
18373 If the cursor is in a LaTeX fragment, create the image and overlay
18374 it over the source code. If there is no fragment at point, display
18375 all fragments in the current text, from one headline to the next. With
18376 prefix SUBTREE, display all fragments in the current subtree. With a
18377 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18378 the cursor is before the first headline,
18379 display all fragments in the buffer.
18380 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18381 (interactive "P")
18382 (unless buffer-file-name
18383 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18384 (when (display-graphic-p)
18385 (org-remove-latex-fragment-image-overlays)
18386 (save-excursion
18387 (save-restriction
18388 (let (beg end at msg)
18389 (cond
18390 ((or (equal subtree '(16))
18391 (not (save-excursion
18392 (re-search-backward org-outline-regexp-bol nil t))))
18393 (setq beg (point-min) end (point-max)
18394 msg "Creating images for buffer...%s"))
18395 ((equal subtree '(4))
18396 (org-back-to-heading)
18397 (setq beg (point) end (org-end-of-subtree t)
18398 msg "Creating images for subtree...%s"))
18400 (if (setq at (org-inside-LaTeX-fragment-p))
18401 (goto-char (max (point-min) (- (cdr at) 2)))
18402 (org-back-to-heading))
18403 (setq beg (point) end (progn (outline-next-heading) (point))
18404 msg (if at "Creating image...%s"
18405 "Creating images for entry...%s"))))
18406 (message msg "")
18407 (narrow-to-region beg end)
18408 (goto-char beg)
18409 (org-format-latex
18410 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18411 (file-name-nondirectory
18412 buffer-file-name)))
18413 default-directory 'overlays msg at 'forbuffer
18414 org-latex-create-formula-image-program)
18415 (message msg "done. Use `C-c C-c' to remove images."))))))
18417 (defun org-format-latex (prefix &optional dir overlays msg at
18418 forbuffer processing-type)
18419 "Replace LaTeX fragments with links to an image, and produce images.
18420 Some of the options can be changed using the variable
18421 `org-format-latex-options'."
18422 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18423 (let* ((prefixnodir (file-name-nondirectory prefix))
18424 (absprefix (expand-file-name prefix dir))
18425 (todir (file-name-directory absprefix))
18426 (opt org-format-latex-options)
18427 (optnew org-format-latex-options)
18428 (matchers (plist-get opt :matchers))
18429 (re-list org-latex-regexps)
18430 (cnt 0) txt hash link beg end re e checkdir
18431 string
18432 m n block-type block linkfile movefile ov)
18433 ;; Check the different regular expressions
18434 (while (setq e (pop re-list))
18435 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18436 block (if block-type "\n\n" ""))
18437 (when (member m matchers)
18438 (goto-char (point-min))
18439 (while (re-search-forward re nil t)
18440 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18441 (or (not overlays)
18442 (not (eq (get-char-property (match-beginning n)
18443 'org-overlay-type)
18444 'org-latex-overlay))))
18445 (cond
18446 ((eq processing-type 'verbatim))
18447 ((eq processing-type 'mathjax)
18448 ;; Prepare for MathJax processing.
18449 (setq string (match-string n))
18450 (when (member m '("$" "$1"))
18451 (save-excursion
18452 (delete-region (match-beginning n) (match-end n))
18453 (goto-char (match-beginning n))
18454 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18455 ((or (eq processing-type 'dvipng)
18456 (eq processing-type 'imagemagick))
18457 ;; Process to an image.
18458 (setq txt (match-string n)
18459 beg (match-beginning n) end (match-end n)
18460 cnt (1+ cnt))
18461 (let ((face (face-at-point))
18462 (fg (plist-get opt :foreground))
18463 (bg (plist-get opt :background))
18464 ;; Ensure full list is printed.
18465 print-length print-level)
18466 (when forbuffer
18467 ;; Get the colors from the face at point.
18468 (goto-char beg)
18469 (when (eq fg 'auto)
18470 (setq fg (face-attribute face :foreground nil 'default)))
18471 (when (eq bg 'auto)
18472 (setq bg (face-attribute face :background nil 'default)))
18473 (setq optnew (copy-sequence opt))
18474 (plist-put optnew :foreground fg)
18475 (plist-put optnew :background bg))
18476 (setq hash (sha1 (prin1-to-string
18477 (list org-format-latex-header
18478 org-latex-default-packages-alist
18479 org-latex-packages-alist
18480 org-format-latex-options
18481 forbuffer txt fg bg)))
18482 linkfile (format "%s_%s.png" prefix hash)
18483 movefile (format "%s_%s.png" absprefix hash)))
18484 (setq link (concat block "[[file:" linkfile "]]" block))
18485 (if msg (message msg cnt))
18486 (goto-char beg)
18487 (unless checkdir ; Ensure the directory exists.
18488 (setq checkdir t)
18489 (or (file-directory-p todir) (make-directory todir t)))
18490 (unless (file-exists-p movefile)
18491 (org-create-formula-image
18492 txt movefile optnew forbuffer processing-type))
18493 (if overlays
18494 (progn
18495 (mapc (lambda (o)
18496 (if (eq (overlay-get o 'org-overlay-type)
18497 'org-latex-overlay)
18498 (delete-overlay o)))
18499 (overlays-in beg end))
18500 (setq ov (make-overlay beg end))
18501 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18502 (if (featurep 'xemacs)
18503 (progn
18504 (overlay-put ov 'invisible t)
18505 (overlay-put
18506 ov 'end-glyph
18507 (make-glyph (vector 'png :file movefile))))
18508 (overlay-put
18509 ov 'display
18510 (list 'image :type 'png :file movefile :ascent 'center)))
18511 (push ov org-latex-fragment-image-overlays)
18512 (goto-char end))
18513 (delete-region beg end)
18514 (insert (org-add-props link
18515 (list 'org-latex-src
18516 (replace-regexp-in-string
18517 "\"" "" txt)
18518 'org-latex-src-embed-type
18519 (if block-type 'paragraph 'character))))))
18520 ((eq processing-type 'mathml)
18521 ;; Process to MathML
18522 (unless (save-match-data (org-format-latex-mathml-available-p))
18523 (user-error "LaTeX to MathML converter not configured"))
18524 (setq txt (match-string n)
18525 beg (match-beginning n) end (match-end n)
18526 cnt (1+ cnt))
18527 (if msg (message msg cnt))
18528 (goto-char beg)
18529 (delete-region beg end)
18530 (insert (org-format-latex-as-mathml
18531 txt block-type prefix dir)))
18533 (error "Unknown conversion type %s for LaTeX fragments"
18534 processing-type)))))))))
18536 (defun org-create-math-formula (latex-frag &optional mathml-file)
18537 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18538 Use `org-latex-to-mathml-convert-command'. If the conversion is
18539 sucessful, return the portion between \"<math...> </math>\"
18540 elements otherwise return nil. When MATHML-FILE is specified,
18541 write the results in to that file. When invoked as an
18542 interactive command, prompt for LATEX-FRAG, with initial value
18543 set to the current active region and echo the results for user
18544 inspection."
18545 (interactive (list (let ((frag (when (org-region-active-p)
18546 (buffer-substring-no-properties
18547 (region-beginning) (region-end)))))
18548 (read-string "LaTeX Fragment: " frag nil frag))))
18549 (unless latex-frag (error "Invalid LaTeX fragment"))
18550 (let* ((tmp-in-file (file-relative-name
18551 (make-temp-name (expand-file-name "ltxmathml-in"))))
18552 (ignore (write-region latex-frag nil tmp-in-file))
18553 (tmp-out-file (file-relative-name
18554 (make-temp-name (expand-file-name "ltxmathml-out"))))
18555 (cmd (format-spec
18556 org-latex-to-mathml-convert-command
18557 `((?j . ,(shell-quote-argument
18558 (expand-file-name org-latex-to-mathml-jar-file)))
18559 (?I . ,(shell-quote-argument tmp-in-file))
18560 (?o . ,(shell-quote-argument tmp-out-file)))))
18561 mathml shell-command-output)
18562 (when (org-called-interactively-p 'any)
18563 (unless (org-format-latex-mathml-available-p)
18564 (user-error "LaTeX to MathML converter not configured")))
18565 (message "Running %s" cmd)
18566 (setq shell-command-output (shell-command-to-string cmd))
18567 (setq mathml
18568 (when (file-readable-p tmp-out-file)
18569 (with-current-buffer (find-file-noselect tmp-out-file t)
18570 (goto-char (point-min))
18571 (when (re-search-forward
18572 (concat
18573 (regexp-quote
18574 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18575 "\\(.\\|\n\\)*"
18576 (regexp-quote "</math>")) nil t)
18577 (prog1 (match-string 0) (kill-buffer))))))
18578 (cond
18579 (mathml
18580 (setq mathml
18581 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18582 (when mathml-file
18583 (write-region mathml nil mathml-file))
18584 (when (org-called-interactively-p 'any)
18585 (message mathml)))
18586 ((message "LaTeX to MathML conversion failed")
18587 (message shell-command-output)))
18588 (delete-file tmp-in-file)
18589 (when (file-exists-p tmp-out-file)
18590 (delete-file tmp-out-file))
18591 mathml))
18593 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18594 prefix &optional dir)
18595 "Use `org-create-math-formula' but check local cache first."
18596 (let* ((absprefix (expand-file-name prefix dir))
18597 (print-length nil) (print-level nil)
18598 (formula-id (concat
18599 "formula-"
18600 (sha1
18601 (prin1-to-string
18602 (list latex-frag
18603 org-latex-to-mathml-convert-command)))))
18604 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18605 (formula-cache-dir (file-name-directory formula-cache)))
18607 (unless (file-directory-p formula-cache-dir)
18608 (make-directory formula-cache-dir t))
18610 (unless (file-exists-p formula-cache)
18611 (org-create-math-formula latex-frag formula-cache))
18613 (if (file-exists-p formula-cache)
18614 ;; Successful conversion. Return the link to MathML file.
18615 (org-add-props
18616 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18617 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18618 'org-latex-src-embed-type (if latex-frag-type
18619 'paragraph 'character)))
18620 ;; Failed conversion. Return the LaTeX fragment verbatim
18621 latex-frag)))
18623 (defun org-create-formula-image (string tofile options buffer &optional type)
18624 "Create an image from LaTeX source using dvipng or convert.
18625 This function calls either `org-create-formula-image-with-dvipng'
18626 or `org-create-formula-image-with-imagemagick' depending on the
18627 value of `org-latex-create-formula-image-program' or on the value
18628 of the optional TYPE variable.
18630 Note: ultimately these two function should be combined as they
18631 share a good deal of logic."
18632 (org-check-external-command
18633 "latex" "needed to convert LaTeX fragments to images")
18634 (funcall
18635 (case (or type org-latex-create-formula-image-program)
18636 ('dvipng
18637 (org-check-external-command
18638 "dvipng" "needed to convert LaTeX fragments to images")
18639 #'org-create-formula-image-with-dvipng)
18640 ('imagemagick
18641 (org-check-external-command
18642 "convert" "you need to install imagemagick")
18643 #'org-create-formula-image-with-imagemagick)
18644 (t (error
18645 "Invalid value of `org-latex-create-formula-image-program'")))
18646 string tofile options buffer))
18648 (declare-function org-export-get-backend "ox" (name))
18649 (declare-function org-export--get-global-options "ox" (&optional backend))
18650 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18651 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18652 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18653 (defun org-create-formula--latex-header ()
18654 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18655 (let ((info (org-combine-plists (org-export--get-global-options
18656 (org-export-get-backend 'latex))
18657 (org-export--get-inbuffer-options
18658 (org-export-get-backend 'latex)))))
18659 (org-latex-guess-babel-language
18660 (org-latex-guess-inputenc
18661 (org-splice-latex-header
18662 org-format-latex-header
18663 org-latex-default-packages-alist
18664 org-latex-packages-alist t
18665 (plist-get info :latex-header)))
18666 info)))
18668 ;; This function borrows from Ganesh Swami's latex2png.el
18669 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18670 "This calls dvipng."
18671 (require 'ox-latex)
18672 (let* ((tmpdir (if (featurep 'xemacs)
18673 (temp-directory)
18674 temporary-file-directory))
18675 (texfilebase (make-temp-name
18676 (expand-file-name "orgtex" tmpdir)))
18677 (texfile (concat texfilebase ".tex"))
18678 (dvifile (concat texfilebase ".dvi"))
18679 (pngfile (concat texfilebase ".png"))
18680 (fnh (if (featurep 'xemacs)
18681 (font-height (face-font 'default))
18682 (face-attribute 'default :height nil)))
18683 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18684 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18685 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18686 "Black"))
18687 (bg (or (plist-get options (if buffer :background :html-background))
18688 "Transparent")))
18689 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18690 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18691 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18692 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18693 (let ((latex-header (org-create-formula--latex-header)))
18694 (with-temp-file texfile
18695 (insert latex-header)
18696 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18697 (let ((dir default-directory))
18698 (condition-case nil
18699 (progn
18700 (cd tmpdir)
18701 (call-process "latex" nil nil nil texfile))
18702 (error nil))
18703 (cd dir))
18704 (if (not (file-exists-p dvifile))
18705 (progn (message "Failed to create dvi file from %s" texfile) nil)
18706 (condition-case nil
18707 (if (featurep 'xemacs)
18708 (call-process "dvipng" nil nil nil
18709 "-fg" fg "-bg" bg
18710 "-T" "tight"
18711 "-o" pngfile
18712 dvifile)
18713 (call-process "dvipng" nil nil nil
18714 "-fg" fg "-bg" bg
18715 "-D" dpi
18716 ;;"-x" scale "-y" scale
18717 "-T" "tight"
18718 "-o" pngfile
18719 dvifile))
18720 (error nil))
18721 (if (not (file-exists-p pngfile))
18722 (if org-format-latex-signal-error
18723 (error "Failed to create png file from %s" texfile)
18724 (message "Failed to create png file from %s" texfile)
18725 nil)
18726 ;; Use the requested file name and clean up
18727 (copy-file pngfile tofile 'replace)
18728 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18729 (if (file-exists-p (concat texfilebase e))
18730 (delete-file (concat texfilebase e))))
18731 pngfile))))
18733 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18734 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18735 "This calls convert, which is included into imagemagick."
18736 (require 'ox-latex)
18737 (let* ((tmpdir (if (featurep 'xemacs)
18738 (temp-directory)
18739 temporary-file-directory))
18740 (texfilebase (make-temp-name
18741 (expand-file-name "orgtex" tmpdir)))
18742 (texfile (concat texfilebase ".tex"))
18743 (pdffile (concat texfilebase ".pdf"))
18744 (pngfile (concat texfilebase ".png"))
18745 (fnh (if (featurep 'xemacs)
18746 (font-height (face-font 'default))
18747 (face-attribute 'default :height nil)))
18748 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18749 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18750 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18751 "black"))
18752 (bg (or (plist-get options (if buffer :background :html-background))
18753 "white")))
18754 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18755 (setq fg (org-latex-color-format fg)))
18756 (if (eq bg 'default) (setq bg (org-latex-color :background))
18757 (setq bg (org-latex-color-format
18758 (if (string= bg "Transparent") "white" bg))))
18759 (let ((latex-header (org-create-formula--latex-header)))
18760 (with-temp-file texfile
18761 (insert latex-header)
18762 (insert "\n\\begin{document}\n"
18763 "\\definecolor{fg}{rgb}{" fg "}\n"
18764 "\\definecolor{bg}{rgb}{" bg "}\n"
18765 "\n\\pagecolor{bg}\n"
18766 "\n{\\color{fg}\n"
18767 string
18768 "\n}\n"
18769 "\n\\end{document}\n")))
18770 (org-latex-compile texfile t)
18771 (if (not (file-exists-p pdffile))
18772 (progn (message "Failed to create pdf file from %s" texfile) nil)
18773 (condition-case nil
18774 (if (featurep 'xemacs)
18775 (call-process "convert" nil nil nil
18776 "-density" "96"
18777 "-trim"
18778 "-antialias"
18779 pdffile
18780 "-quality" "100"
18781 ;; "-sharpen" "0x1.0"
18782 pngfile)
18783 (call-process "convert" nil nil nil
18784 "-density" dpi
18785 "-trim"
18786 "-antialias"
18787 pdffile
18788 "-quality" "100"
18789 ;; "-sharpen" "0x1.0"
18790 pngfile))
18791 (error nil))
18792 (if (not (file-exists-p pngfile))
18793 (if org-format-latex-signal-error
18794 (error "Failed to create png file from %s" texfile)
18795 (message "Failed to create png file from %s" texfile)
18796 nil)
18797 ;; Use the requested file name and clean up
18798 (copy-file pngfile tofile 'replace)
18799 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18800 (if (file-exists-p (concat texfilebase e))
18801 (delete-file (concat texfilebase e))))
18802 pngfile))))
18804 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18805 "Fill a LaTeX header template TPL.
18806 In the template, the following place holders will be recognized:
18808 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18809 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18810 [PACKAGES] \\usepackage statements for PKG
18811 [NO-PACKAGES] do not include PKG
18812 [EXTRA] the string EXTRA
18813 [NO-EXTRA] do not include EXTRA
18815 For backward compatibility, if both the positive and the negative place
18816 holder is missing, the positive one (without the \"NO-\") will be
18817 assumed to be present at the end of the template.
18818 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18819 EXTRA is a string.
18820 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18821 (let (rpl (end ""))
18822 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18823 (setq rpl (if (or (match-end 1) (not def-pkg))
18824 "" (org-latex-packages-to-string def-pkg snippets-p t))
18825 tpl (replace-match rpl t t tpl))
18826 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18828 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18829 (setq rpl (if (or (match-end 1) (not pkg))
18830 "" (org-latex-packages-to-string pkg snippets-p t))
18831 tpl (replace-match rpl t t tpl))
18832 (if pkg (setq end
18833 (concat end "\n"
18834 (org-latex-packages-to-string pkg snippets-p)))))
18836 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18837 (setq rpl (if (or (match-end 1) (not extra))
18838 "" (concat extra "\n"))
18839 tpl (replace-match rpl t t tpl))
18840 (if (and extra (string-match "\\S-" extra))
18841 (setq end (concat end "\n" extra))))
18843 (if (string-match "\\S-" end)
18844 (concat tpl "\n" end)
18845 tpl)))
18847 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18848 "Turn an alist of packages into a string with the \\usepackage macros."
18849 (setq pkg (mapconcat (lambda(p)
18850 (cond
18851 ((stringp p) p)
18852 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18853 (format "%% Package %s omitted" (cadr p)))
18854 ((equal "" (car p))
18855 (format "\\usepackage{%s}" (cadr p)))
18857 (format "\\usepackage[%s]{%s}"
18858 (car p) (cadr p)))))
18860 "\n"))
18861 (if newline (concat pkg "\n") pkg))
18863 (defun org-dvipng-color (attr)
18864 "Return a RGB color specification for dvipng."
18865 (apply 'format "rgb %s %s %s"
18866 (mapcar 'org-normalize-color
18867 (if (featurep 'xemacs)
18868 (color-rgb-components
18869 (face-property 'default
18870 (cond ((eq attr :foreground) 'foreground)
18871 ((eq attr :background) 'background))))
18872 (color-values (face-attribute 'default attr nil))))))
18874 (defun org-dvipng-color-format (color-name)
18875 "Convert COLOR-NAME to a RGB color value for dvipng."
18876 (apply 'format "rgb %s %s %s"
18877 (mapcar 'org-normalize-color
18878 (color-values color-name))))
18880 (defun org-latex-color (attr)
18881 "Return a RGB color for the LaTeX color package."
18882 (apply 'format "%s,%s,%s"
18883 (mapcar 'org-normalize-color
18884 (if (featurep 'xemacs)
18885 (color-rgb-components
18886 (face-property 'default
18887 (cond ((eq attr :foreground) 'foreground)
18888 ((eq attr :background) 'background))))
18889 (color-values (face-attribute 'default attr nil))))))
18891 (defun org-latex-color-format (color-name)
18892 "Convert COLOR-NAME to a RGB color value."
18893 (apply 'format "%s,%s,%s"
18894 (mapcar 'org-normalize-color
18895 (color-values color-name))))
18897 (defun org-normalize-color (value)
18898 "Return string to be used as color value for an RGB component."
18899 (format "%g" (/ value 65535.0)))
18903 ;; Image display
18905 (defvar org-inline-image-overlays nil)
18906 (make-variable-buffer-local 'org-inline-image-overlays)
18908 (defun org-toggle-inline-images (&optional include-linked)
18909 "Toggle the display of inline images.
18910 INCLUDE-LINKED is passed to `org-display-inline-images'."
18911 (interactive "P")
18912 (if org-inline-image-overlays
18913 (progn
18914 (org-remove-inline-images)
18915 (message "Inline image display turned off"))
18916 (org-display-inline-images include-linked)
18917 (if (and (org-called-interactively-p)
18918 org-inline-image-overlays)
18919 (message "%d images displayed inline"
18920 (length org-inline-image-overlays))
18921 (message "No images to display inline"))))
18923 (defun org-redisplay-inline-images ()
18924 "Refresh the display of inline images."
18925 (interactive)
18926 (if (not org-inline-image-overlays)
18927 (org-toggle-inline-images)
18928 (org-toggle-inline-images)
18929 (org-toggle-inline-images)))
18931 (defun org-display-inline-images (&optional include-linked refresh beg end)
18932 "Display inline images.
18934 An inline image is a link which follows either of these
18935 conventions:
18937 1. Its path is a file with an extension matching return value
18938 from `image-file-name-regexp' and it has no contents.
18940 2. Its description consists in a single link of the previous
18941 type.
18943 When optional argument INCLUDE-LINKED is non-nil, also links with
18944 a text description part will be inlined. This can be nice for
18945 a quick look at those images, but it does not reflect what
18946 exported files will look like.
18948 When optional argument REFRESH is non-nil, refresh existing
18949 images between BEG and END. This will create new image displays
18950 only if necessary. BEG and END default to the buffer
18951 boundaries."
18952 (interactive "P")
18953 (when (display-graphic-p)
18954 (unless refresh
18955 (org-remove-inline-images)
18956 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18957 (org-with-wide-buffer
18958 (goto-char (or beg (point-min)))
18959 (let ((case-fold-search t)
18960 (file-extension-re (org-image-file-name-regexp)))
18961 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
18962 (let ((link (save-match-data (org-element-context))))
18963 ;; Check if we're at an inline image.
18964 (when (and (equal (org-element-property :type link) "file")
18965 (or include-linked
18966 (not (org-element-property :contents-begin link)))
18967 (let ((parent (org-element-property :parent link)))
18968 (or (not (eq (org-element-type parent) 'link))
18969 (not (cdr (org-element-contents parent)))))
18970 (org-string-match-p file-extension-re
18971 (org-element-property :path link)))
18972 (let ((file (expand-file-name (org-element-property :path link))))
18973 (when (file-exists-p file)
18974 (let ((width
18975 ;; Apply `org-image-actual-width' specifications.
18976 (cond
18977 ((not (image-type-available-p 'imagemagick)) nil)
18978 ((eq org-image-actual-width t) nil)
18979 ((listp org-image-actual-width)
18981 ;; First try to find a width among
18982 ;; attributes associated to the paragraph
18983 ;; containing link.
18984 (let ((paragraph
18985 (let ((e link))
18986 (while (and (setq e (org-element-property
18987 :parent e))
18988 (not (eq (org-element-type e)
18989 'paragraph))))
18990 e)))
18991 (when paragraph
18992 (save-excursion
18993 (goto-char (org-element-property :begin paragraph))
18994 (when (save-match-data
18995 (re-search-forward
18996 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18997 (org-element-property
18998 :post-affiliated paragraph)
19000 (string-to-number (match-string 1))))))
19001 ;; Otherwise, fall-back to provided number.
19002 (car org-image-actual-width)))
19003 ((numberp org-image-actual-width)
19004 org-image-actual-width)))
19005 (old (get-char-property-and-overlay
19006 (org-element-property :begin link)
19007 'org-image-overlay)))
19008 (if (and (car-safe old) refresh)
19009 (image-refresh (overlay-get (cdr old) 'display))
19010 (let ((image (save-match-data
19011 (create-image file
19012 (and width 'imagemagick)
19014 :width width))))
19015 (when image
19016 (let* ((link
19017 ;; If inline image is the description
19018 ;; of another link, be sure to
19019 ;; consider the latter as the one to
19020 ;; apply the overlay on.
19021 (let ((parent
19022 (org-element-property :parent link)))
19023 (if (eq (org-element-type parent) 'link)
19024 parent
19025 link)))
19026 (ov (make-overlay
19027 (org-element-property :begin link)
19028 (progn
19029 (goto-char
19030 (org-element-property :end link))
19031 (skip-chars-backward " \t")
19032 (point)))))
19033 (overlay-put ov 'display image)
19034 (overlay-put ov 'face 'default)
19035 (overlay-put ov 'org-image-overlay t)
19036 (overlay-put
19037 ov 'modification-hooks
19038 (list 'org-display-inline-remove-overlay))
19039 (push ov org-inline-image-overlays)))))))))))))))
19041 (define-obsolete-function-alias
19042 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19044 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19045 "Remove inline-display overlay if a corresponding region is modified."
19046 (let ((inhibit-modification-hooks t))
19047 (when (and ov after)
19048 (delete ov org-inline-image-overlays)
19049 (delete-overlay ov))))
19051 (defun org-remove-inline-images ()
19052 "Remove inline display of images."
19053 (interactive)
19054 (mapc 'delete-overlay org-inline-image-overlays)
19055 (setq org-inline-image-overlays nil))
19057 ;;;; Key bindings
19059 ;; Outline functions from `outline-mode-prefix-map'
19060 ;; that can be remapped in Org:
19061 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19062 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19063 (define-key org-mode-map [remap outline-forward-same-level]
19064 'org-forward-heading-same-level)
19065 (define-key org-mode-map [remap outline-backward-same-level]
19066 'org-backward-heading-same-level)
19067 (define-key org-mode-map [remap show-branches]
19068 'org-kill-note-or-show-branches)
19069 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19070 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19071 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19073 ;; Outline functions from `outline-mode-prefix-map' that can not
19074 ;; be remapped in Org:
19076 ;; - the column "key binding" shows whether the Outline function is still
19077 ;; available in Org mode on the same key that it has been bound to in
19078 ;; Outline mode:
19079 ;; - "overridden": key used for a different functionality in Org mode
19080 ;; - else: key still bound to the same Outline function in Org mode
19082 ;; | Outline function | key binding | Org replacement |
19083 ;; |------------------------------------+-------------+-----------------------|
19084 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19085 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19086 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19087 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19088 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19089 ;; | `show-entry' | overridden | no replacement |
19090 ;; | `show-children' | `C-c C-i' | visibility cycling |
19091 ;; | `show-branches' | `C-c C-k' | still same function |
19092 ;; | `show-subtree' | overridden | visibility cycling |
19093 ;; | `show-all' | overridden | no replacement |
19094 ;; | `hide-subtree' | overridden | visibility cycling |
19095 ;; | `hide-body' | overridden | no replacement |
19096 ;; | `hide-entry' | overridden | visibility cycling |
19097 ;; | `hide-leaves' | overridden | no replacement |
19098 ;; | `hide-sublevels' | overridden | no replacement |
19099 ;; | `hide-other' | overridden | no replacement |
19101 ;; Make `C-c C-x' a prefix key
19102 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19104 ;; TAB key with modifiers
19105 (org-defkey org-mode-map "\C-i" 'org-cycle)
19106 (org-defkey org-mode-map [(tab)] 'org-cycle)
19107 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19108 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19109 ;; The following line is necessary under Suse GNU/Linux
19110 (unless (featurep 'xemacs)
19111 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19112 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19113 (define-key org-mode-map [backtab] 'org-shifttab)
19115 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19116 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19117 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19119 ;; Cursor keys with modifiers
19120 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19121 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19122 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19123 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19125 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19126 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19127 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19128 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19130 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19131 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19132 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19133 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19135 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19136 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19137 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19138 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19140 ;; Babel keys
19141 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19142 (mapc (lambda (pair)
19143 (define-key org-babel-map (car pair) (cdr pair)))
19144 org-babel-key-bindings)
19146 ;;; Extra keys for tty access.
19147 ;; We only set them when really needed because otherwise the
19148 ;; menus don't show the simple keys
19150 (when (or org-use-extra-keys
19151 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19152 (not window-system))
19153 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19154 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19155 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19156 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19157 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19158 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19159 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19160 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19161 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19162 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19163 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19164 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19165 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19166 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19167 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19168 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19169 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19170 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19171 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19172 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19173 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19174 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19175 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19176 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19177 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19178 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19179 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19180 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19182 ;; All the other keys
19184 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19185 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19186 (if (boundp 'narrow-map)
19187 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19188 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19189 (if (boundp 'narrow-map)
19190 (org-defkey narrow-map "b" 'org-narrow-to-block)
19191 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19192 (if (boundp 'narrow-map)
19193 (org-defkey narrow-map "e" 'org-narrow-to-element)
19194 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19195 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19196 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19197 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19198 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19199 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19200 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19201 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19202 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19203 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19204 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19205 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19206 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19207 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19208 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19209 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19210 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19211 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19212 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19213 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19214 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19215 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19216 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19217 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19218 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19219 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19220 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19221 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19222 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19223 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19224 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19225 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19226 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19227 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19228 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19229 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19230 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19231 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19232 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19233 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19234 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19235 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19236 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19237 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19238 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19239 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19240 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19241 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19242 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19243 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19244 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19245 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19246 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19247 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19248 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19249 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19250 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19251 (org-defkey org-mode-map "\C-c^" 'org-sort)
19252 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19253 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19254 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19255 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19256 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19257 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19258 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19259 (org-defkey org-mode-map "\C-m" 'org-return)
19260 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19261 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19262 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19263 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19264 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19265 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19266 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19267 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19268 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19269 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19270 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19271 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19272 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19273 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19274 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19275 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19276 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19277 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19278 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19279 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19280 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19281 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19282 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19284 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19285 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19286 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19288 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19289 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19290 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19291 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19292 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19293 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19294 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19295 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19296 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19297 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19298 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19299 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19300 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19301 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19302 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19303 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19304 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19305 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19306 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19307 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19308 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19309 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19310 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19312 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19313 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19314 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19315 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19316 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19318 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19320 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19322 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19323 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19325 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19328 (when (featurep 'xemacs)
19329 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19332 (defconst org-speed-commands-default
19334 ("Outline Navigation")
19335 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19336 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19337 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19338 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19339 ("F" . org-next-block)
19340 ("B" . org-previous-block)
19341 ("u" . (org-speed-move-safe 'outline-up-heading))
19342 ("j" . org-goto)
19343 ("g" . (org-refile t))
19344 ("Outline Visibility")
19345 ("c" . org-cycle)
19346 ("C" . org-shifttab)
19347 (" " . org-display-outline-path)
19348 ("s" . org-narrow-to-subtree)
19349 ("=" . org-columns)
19350 ("Outline Structure Editing")
19351 ("U" . org-shiftmetaup)
19352 ("D" . org-shiftmetadown)
19353 ("r" . org-metaright)
19354 ("l" . org-metaleft)
19355 ("R" . org-shiftmetaright)
19356 ("L" . org-shiftmetaleft)
19357 ("i" . (progn (forward-char 1) (call-interactively
19358 'org-insert-heading-respect-content)))
19359 ("^" . org-sort)
19360 ("w" . org-refile)
19361 ("a" . org-archive-subtree-default-with-confirmation)
19362 ("@" . org-mark-subtree)
19363 ("#" . org-toggle-comment)
19364 ("Clock Commands")
19365 ("I" . org-clock-in)
19366 ("O" . org-clock-out)
19367 ("Meta Data Editing")
19368 ("t" . org-todo)
19369 ("," . (org-priority))
19370 ("0" . (org-priority ?\ ))
19371 ("1" . (org-priority ?A))
19372 ("2" . (org-priority ?B))
19373 ("3" . (org-priority ?C))
19374 (":" . org-set-tags-command)
19375 ("e" . org-set-effort)
19376 ("E" . org-inc-effort)
19377 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19378 (org-entry-put (point) "APPT_WARNTIME" m)))
19379 ("Agenda Views etc")
19380 ("v" . org-agenda)
19381 ("/" . org-sparse-tree)
19382 ("Misc")
19383 ("o" . org-open-at-point)
19384 ("?" . org-speed-command-help)
19385 ("<" . (org-agenda-set-restriction-lock 'subtree))
19386 (">" . (org-agenda-remove-restriction-lock))
19388 "The default speed commands.")
19390 (defun org-print-speed-command (e)
19391 (if (> (length (car e)) 1)
19392 (progn
19393 (princ "\n")
19394 (princ (car e))
19395 (princ "\n")
19396 (princ (make-string (length (car e)) ?-))
19397 (princ "\n"))
19398 (princ (car e))
19399 (princ " ")
19400 (if (symbolp (cdr e))
19401 (princ (symbol-name (cdr e)))
19402 (prin1 (cdr e)))
19403 (princ "\n")))
19405 (defun org-speed-command-help ()
19406 "Show the available speed commands."
19407 (interactive)
19408 (if (not org-use-speed-commands)
19409 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19410 (with-output-to-temp-buffer "*Help*"
19411 (princ "User-defined Speed commands\n===========================\n")
19412 (mapc 'org-print-speed-command org-speed-commands-user)
19413 (princ "\n")
19414 (princ "Built-in Speed commands\n=======================\n")
19415 (mapc 'org-print-speed-command org-speed-commands-default))
19416 (with-current-buffer "*Help*"
19417 (setq truncate-lines t))))
19419 (defun org-speed-move-safe (cmd)
19420 "Execute CMD, but make sure that the cursor always ends up in a headline.
19421 If not, return to the original position and throw an error."
19422 (interactive)
19423 (let ((pos (point)))
19424 (call-interactively cmd)
19425 (unless (and (bolp) (org-at-heading-p))
19426 (goto-char pos)
19427 (error "Boundary reached while executing %s" cmd))))
19429 (defvar org-self-insert-command-undo-counter 0)
19431 (defvar org-table-auto-blank-field) ; defined in org-table.el
19432 (defvar org-speed-command nil)
19434 (define-obsolete-function-alias
19435 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19437 (defun org-speed-command-activate (keys)
19438 "Hook for activating single-letter speed commands.
19439 `org-speed-commands-default' specifies a minimal command set.
19440 Use `org-speed-commands-user' for further customization."
19441 (when (or (and (bolp) (looking-at org-outline-regexp))
19442 (and (functionp org-use-speed-commands)
19443 (funcall org-use-speed-commands)))
19444 (cdr (assoc keys (append org-speed-commands-user
19445 org-speed-commands-default)))))
19447 (define-obsolete-function-alias
19448 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19450 (defun org-babel-speed-command-activate (keys)
19451 "Hook for activating single-letter code block commands."
19452 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19453 (cdr (assoc keys org-babel-key-bindings))))
19455 (defcustom org-speed-command-hook
19456 '(org-speed-command-default-hook org-babel-speed-command-hook)
19457 "Hook for activating speed commands at strategic locations.
19458 Hook functions are called in sequence until a valid handler is
19459 found.
19461 Each hook takes a single argument, a user-pressed command key
19462 which is also a `self-insert-command' from the global map.
19464 Within the hook, examine the cursor position and the command key
19465 and return nil or a valid handler as appropriate. Handler could
19466 be one of an interactive command, a function, or a form.
19468 Set `org-use-speed-commands' to non-nil value to enable this
19469 hook. The default setting is `org-speed-command-activate'."
19470 :group 'org-structure
19471 :version "24.1"
19472 :type 'hook)
19474 (defun org-self-insert-command (N)
19475 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19476 If the cursor is in a table looking at whitespace, the whitespace is
19477 overwritten, and the table is not marked as requiring realignment."
19478 (interactive "p")
19479 (org-check-before-invisible-edit 'insert)
19480 (cond
19481 ((and org-use-speed-commands
19482 (setq org-speed-command
19483 (run-hook-with-args-until-success
19484 'org-speed-command-hook (this-command-keys))))
19485 (cond
19486 ((commandp org-speed-command)
19487 (setq this-command org-speed-command)
19488 (call-interactively org-speed-command))
19489 ((functionp org-speed-command)
19490 (funcall org-speed-command))
19491 ((and org-speed-command (listp org-speed-command))
19492 (eval org-speed-command))
19493 (t (let (org-use-speed-commands)
19494 (call-interactively 'org-self-insert-command)))))
19495 ((and
19496 (org-table-p)
19497 (progn
19498 ;; check if we blank the field, and if that triggers align
19499 (and (featurep 'org-table) org-table-auto-blank-field
19500 (member last-command
19501 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19502 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19503 ;; got extra space, this field does not determine column width
19504 (let (org-table-may-need-update) (org-table-blank-field))
19505 ;; no extra space, this field may determine column width
19506 (org-table-blank-field)))
19508 (eq N 1)
19509 (looking-at "[^|\n]* |"))
19510 (let (org-table-may-need-update)
19511 (goto-char (1- (match-end 0)))
19512 (backward-delete-char 1)
19513 (goto-char (match-beginning 0))
19514 (self-insert-command N)))
19516 (setq org-table-may-need-update t)
19517 (self-insert-command N)
19518 (org-fix-tags-on-the-fly)
19519 (if org-self-insert-cluster-for-undo
19520 (if (not (eq last-command 'org-self-insert-command))
19521 (setq org-self-insert-command-undo-counter 1)
19522 (if (>= org-self-insert-command-undo-counter 20)
19523 (setq org-self-insert-command-undo-counter 1)
19524 (and (> org-self-insert-command-undo-counter 0)
19525 buffer-undo-list (listp buffer-undo-list)
19526 (not (cadr buffer-undo-list)) ; remove nil entry
19527 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19528 (setq org-self-insert-command-undo-counter
19529 (1+ org-self-insert-command-undo-counter))))))))
19531 (defun org-check-before-invisible-edit (kind)
19532 "Check is editing if kind KIND would be dangerous with invisible text around.
19533 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19534 ;; First, try to get out of here as quickly as possible, to reduce overhead
19535 (if (and org-catch-invisible-edits
19536 (or (not (boundp 'visible-mode)) (not visible-mode))
19537 (or (get-char-property (point) 'invisible)
19538 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19539 ;; OK, we need to take a closer look
19540 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19541 (invisible-before-point (if (bobp) nil (get-char-property
19542 (1- (point)) 'invisible)))
19543 (border-and-ok-direction
19545 ;; Check if we are acting predictably before invisible text
19546 (and invisible-at-point (not invisible-before-point)
19547 (memq kind '(insert delete-backward)))
19548 ;; Check if we are acting predictably after invisible text
19549 ;; This works not well, and I have turned it off. It seems
19550 ;; better to always show and stop after invisible text.
19551 ;; (and (not invisible-at-point) invisible-before-point
19552 ;; (memq kind '(insert delete)))
19554 (when (or (memq invisible-at-point '(outline org-hide-block t))
19555 (memq invisible-before-point '(outline org-hide-block t)))
19556 (if (eq org-catch-invisible-edits 'error)
19557 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19558 (if (and org-custom-properties-overlays
19559 (y-or-n-p "Display invisible properties in this buffer? "))
19560 (org-toggle-custom-properties-visibility)
19561 ;; Make the area visible
19562 (save-excursion
19563 (if invisible-before-point
19564 (goto-char (previous-single-char-property-change
19565 (point) 'invisible)))
19566 (org-cycle))
19567 (cond
19568 ((eq org-catch-invisible-edits 'show)
19569 ;; That's it, we do the edit after showing
19570 (message
19571 "Unfolding invisible region around point before editing")
19572 (sit-for 1))
19573 ((and (eq org-catch-invisible-edits 'smart)
19574 border-and-ok-direction)
19575 (message "Unfolding invisible region around point before editing"))
19577 ;; Don't do the edit, make the user repeat it in full visibility
19578 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19580 (defun org-fix-tags-on-the-fly ()
19581 (when (and (equal (char-after (point-at-bol)) ?*)
19582 (org-at-heading-p))
19583 (org-align-tags-here org-tags-column)))
19585 (defun org-delete-backward-char (N)
19586 "Like `delete-backward-char', insert whitespace at field end in tables.
19587 When deleting backwards, in tables this function will insert whitespace in
19588 front of the next \"|\" separator, to keep the table aligned. The table will
19589 still be marked for re-alignment if the field did fill the entire column,
19590 because, in this case the deletion might narrow the column."
19591 (interactive "p")
19592 (save-match-data
19593 (org-check-before-invisible-edit 'delete-backward)
19594 (if (and (org-table-p)
19595 (eq N 1)
19596 (string-match "|" (buffer-substring (point-at-bol) (point)))
19597 (looking-at ".*?|"))
19598 (let ((pos (point))
19599 (noalign (looking-at "[^|\n\r]* |"))
19600 (c org-table-may-need-update))
19601 (backward-delete-char N)
19602 (if (not overwrite-mode)
19603 (progn
19604 (skip-chars-forward "^|")
19605 (insert " ")
19606 (goto-char (1- pos))))
19607 ;; noalign: if there were two spaces at the end, this field
19608 ;; does not determine the width of the column.
19609 (if noalign (setq org-table-may-need-update c)))
19610 (backward-delete-char N)
19611 (org-fix-tags-on-the-fly))))
19613 (defun org-delete-char (N)
19614 "Like `delete-char', but insert whitespace at field end in tables.
19615 When deleting characters, in tables this function will insert whitespace in
19616 front of the next \"|\" separator, to keep the table aligned. The table will
19617 still be marked for re-alignment if the field did fill the entire column,
19618 because, in this case the deletion might narrow the column."
19619 (interactive "p")
19620 (save-match-data
19621 (org-check-before-invisible-edit 'delete)
19622 (if (and (org-table-p)
19623 (not (bolp))
19624 (not (= (char-after) ?|))
19625 (eq N 1))
19626 (if (looking-at ".*?|")
19627 (let ((pos (point))
19628 (noalign (looking-at "[^|\n\r]* |"))
19629 (c org-table-may-need-update))
19630 (replace-match
19631 (concat (substring (match-string 0) 1 -1) " |") nil t)
19632 (goto-char pos)
19633 ;; noalign: if there were two spaces at the end, this field
19634 ;; does not determine the width of the column.
19635 (if noalign (setq org-table-may-need-update c)))
19636 (delete-char N))
19637 (delete-char N)
19638 (org-fix-tags-on-the-fly))))
19640 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19641 (put 'org-self-insert-command 'delete-selection
19642 (lambda ()
19643 (not (run-hook-with-args-until-success
19644 'self-insert-uses-region-functions))))
19645 (put 'orgtbl-self-insert-command 'delete-selection
19646 (lambda ()
19647 (not (run-hook-with-args-until-success
19648 'self-insert-uses-region-functions))))
19649 (put 'org-delete-char 'delete-selection 'supersede)
19650 (put 'org-delete-backward-char 'delete-selection 'supersede)
19651 (put 'org-yank 'delete-selection 'yank)
19653 ;; Make `flyspell-mode' delay after some commands
19654 (put 'org-self-insert-command 'flyspell-delayed t)
19655 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19656 (put 'org-delete-char 'flyspell-delayed t)
19657 (put 'org-delete-backward-char 'flyspell-delayed t)
19659 ;; Make pabbrev-mode expand after org-mode commands
19660 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19661 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19663 (defun org-remap (map &rest commands)
19664 "In MAP, remap the functions given in COMMANDS.
19665 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19666 (let (new old)
19667 (while commands
19668 (setq old (pop commands) new (pop commands))
19669 (if (fboundp 'command-remapping)
19670 (org-defkey map (vector 'remap old) new)
19671 (substitute-key-definition old new map global-map)))))
19673 (defun org-transpose-words ()
19674 "Transpose words for Org.
19675 This uses the `org-mode-transpose-word-syntax-table' syntax
19676 table, which interprets characters in `org-emphasis-alist' as
19677 word constituents."
19678 (interactive)
19679 (with-syntax-table org-mode-transpose-word-syntax-table
19680 (call-interactively 'transpose-words)))
19681 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19683 (when (eq org-enable-table-editor 'optimized)
19684 ;; If the user wants maximum table support, we need to hijack
19685 ;; some standard editing functions
19686 (org-remap org-mode-map
19687 'self-insert-command 'org-self-insert-command
19688 'delete-char 'org-delete-char
19689 'delete-backward-char 'org-delete-backward-char)
19690 (org-defkey org-mode-map "|" 'org-force-self-insert))
19692 (defvar org-ctrl-c-ctrl-c-hook nil
19693 "Hook for functions attaching themselves to `C-c C-c'.
19695 This can be used to add additional functionality to the C-c C-c
19696 key which executes context-dependent commands. This hook is run
19697 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19698 run after the last test.
19700 Each function will be called with no arguments. The function
19701 must check if the context is appropriate for it to act. If yes,
19702 it should do its thing and then return a non-nil value. If the
19703 context is wrong, just do nothing and return nil.")
19705 (defvar org-ctrl-c-ctrl-c-final-hook nil
19706 "Hook for functions attaching themselves to `C-c C-c'.
19708 This can be used to add additional functionality to the C-c C-c
19709 key which executes context-dependent commands. This hook is run
19710 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19711 before the first test.
19713 Each function will be called with no arguments. The function
19714 must check if the context is appropriate for it to act. If yes,
19715 it should do its thing and then return a non-nil value. If the
19716 context is wrong, just do nothing and return nil.")
19718 (defvar org-tab-first-hook nil
19719 "Hook for functions to attach themselves to TAB.
19720 See `org-ctrl-c-ctrl-c-hook' for more information.
19721 This hook runs as the first action when TAB is pressed, even before
19722 `org-cycle' messes around with the `outline-regexp' to cater for
19723 inline tasks and plain list item folding.
19724 If any function in this hook returns t, any other actions that
19725 would have been caused by TAB (such as table field motion or visibility
19726 cycling) will not occur.")
19728 (defvar org-tab-after-check-for-table-hook nil
19729 "Hook for functions to attach themselves to TAB.
19730 See `org-ctrl-c-ctrl-c-hook' for more information.
19731 This hook runs after it has been established that the cursor is not in a
19732 table, but before checking if the cursor is in a headline or if global cycling
19733 should be done.
19734 If any function in this hook returns t, not other actions like visibility
19735 cycling will be done.")
19737 (defvar org-tab-after-check-for-cycling-hook nil
19738 "Hook for functions to attach themselves to TAB.
19739 See `org-ctrl-c-ctrl-c-hook' for more information.
19740 This hook runs after it has been established that not table field motion and
19741 not visibility should be done because of current context. This is probably
19742 the place where a package like yasnippets can hook in.")
19744 (defvar org-tab-before-tab-emulation-hook nil
19745 "Hook for functions to attach themselves to TAB.
19746 See `org-ctrl-c-ctrl-c-hook' for more information.
19747 This hook runs after every other options for TAB have been exhausted, but
19748 before indentation and \t insertion takes place.")
19750 (defvar org-metaleft-hook nil
19751 "Hook for functions attaching themselves to `M-left'.
19752 See `org-ctrl-c-ctrl-c-hook' for more information.")
19753 (defvar org-metaright-hook nil
19754 "Hook for functions attaching themselves to `M-right'.
19755 See `org-ctrl-c-ctrl-c-hook' for more information.")
19756 (defvar org-metaup-hook nil
19757 "Hook for functions attaching themselves to `M-up'.
19758 See `org-ctrl-c-ctrl-c-hook' for more information.")
19759 (defvar org-metadown-hook nil
19760 "Hook for functions attaching themselves to `M-down'.
19761 See `org-ctrl-c-ctrl-c-hook' for more information.")
19762 (defvar org-shiftmetaleft-hook nil
19763 "Hook for functions attaching themselves to `M-S-left'.
19764 See `org-ctrl-c-ctrl-c-hook' for more information.")
19765 (defvar org-shiftmetaright-hook nil
19766 "Hook for functions attaching themselves to `M-S-right'.
19767 See `org-ctrl-c-ctrl-c-hook' for more information.")
19768 (defvar org-shiftmetaup-hook nil
19769 "Hook for functions attaching themselves to `M-S-up'.
19770 See `org-ctrl-c-ctrl-c-hook' for more information.")
19771 (defvar org-shiftmetadown-hook nil
19772 "Hook for functions attaching themselves to `M-S-down'.
19773 See `org-ctrl-c-ctrl-c-hook' for more information.")
19774 (defvar org-metareturn-hook nil
19775 "Hook for functions attaching themselves to `M-RET'.
19776 See `org-ctrl-c-ctrl-c-hook' for more information.")
19777 (defvar org-shiftup-hook nil
19778 "Hook for functions attaching themselves to `S-up'.
19779 See `org-ctrl-c-ctrl-c-hook' for more information.")
19780 (defvar org-shiftup-final-hook nil
19781 "Hook for functions attaching themselves to `S-up'.
19782 This one runs after all other options except shift-select have been excluded.
19783 See `org-ctrl-c-ctrl-c-hook' for more information.")
19784 (defvar org-shiftdown-hook nil
19785 "Hook for functions attaching themselves to `S-down'.
19786 See `org-ctrl-c-ctrl-c-hook' for more information.")
19787 (defvar org-shiftdown-final-hook nil
19788 "Hook for functions attaching themselves to `S-down'.
19789 This one runs after all other options except shift-select have been excluded.
19790 See `org-ctrl-c-ctrl-c-hook' for more information.")
19791 (defvar org-shiftleft-hook nil
19792 "Hook for functions attaching themselves to `S-left'.
19793 See `org-ctrl-c-ctrl-c-hook' for more information.")
19794 (defvar org-shiftleft-final-hook nil
19795 "Hook for functions attaching themselves to `S-left'.
19796 This one runs after all other options except shift-select have been excluded.
19797 See `org-ctrl-c-ctrl-c-hook' for more information.")
19798 (defvar org-shiftright-hook nil
19799 "Hook for functions attaching themselves to `S-right'.
19800 See `org-ctrl-c-ctrl-c-hook' for more information.")
19801 (defvar org-shiftright-final-hook nil
19802 "Hook for functions attaching themselves to `S-right'.
19803 This one runs after all other options except shift-select have been excluded.
19804 See `org-ctrl-c-ctrl-c-hook' for more information.")
19806 (defun org-modifier-cursor-error ()
19807 "Throw an error, a modified cursor command was applied in wrong context."
19808 (user-error "This command is active in special context like tables, headlines or items"))
19810 (defun org-shiftselect-error ()
19811 "Throw an error because Shift-Cursor command was applied in wrong context."
19812 (if (and (boundp 'shift-select-mode) shift-select-mode)
19813 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19814 (user-error "This command works only in special context like headlines or timestamps")))
19816 (defun org-call-for-shift-select (cmd)
19817 (let ((this-command-keys-shift-translated t))
19818 (call-interactively cmd)))
19820 (defun org-shifttab (&optional arg)
19821 "Global visibility cycling or move to previous table field.
19822 Call `org-table-previous-field' within a table.
19823 When ARG is nil, cycle globally through visibility states.
19824 When ARG is a numeric prefix, show contents of this level."
19825 (interactive "P")
19826 (cond
19827 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19828 ((integerp arg)
19829 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19830 (message "Content view to level: %d" arg)
19831 (org-content (prefix-numeric-value arg2))
19832 (org-cycle-show-empty-lines t)
19833 (setq org-cycle-global-status 'overview)))
19834 (t (call-interactively 'org-global-cycle))))
19836 (defun org-shiftmetaleft ()
19837 "Promote subtree or delete table column.
19838 Calls `org-promote-subtree', `org-outdent-item-tree', or
19839 `org-table-delete-column', depending on context. See the
19840 individual commands for more information."
19841 (interactive)
19842 (cond
19843 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19844 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19845 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19846 ((if (not (org-region-active-p)) (org-at-item-p)
19847 (save-excursion (goto-char (region-beginning))
19848 (org-at-item-p)))
19849 (call-interactively 'org-outdent-item-tree))
19850 (t (org-modifier-cursor-error))))
19852 (defun org-shiftmetaright ()
19853 "Demote subtree or insert table column.
19854 Calls `org-demote-subtree', `org-indent-item-tree', or
19855 `org-table-insert-column', depending on context. See the
19856 individual commands for more information."
19857 (interactive)
19858 (cond
19859 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19860 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19861 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19862 ((if (not (org-region-active-p)) (org-at-item-p)
19863 (save-excursion (goto-char (region-beginning))
19864 (org-at-item-p)))
19865 (call-interactively 'org-indent-item-tree))
19866 (t (org-modifier-cursor-error))))
19868 (defun org-shiftmetaup (&optional arg)
19869 "Move subtree up or kill table row.
19870 Calls `org-move-subtree-up' or `org-table-kill-row' or
19871 `org-move-item-up' or `org-timestamp-up', depending on context.
19872 See the individual commands for more information."
19873 (interactive "P")
19874 (cond
19875 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19876 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19877 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19878 ((org-at-item-p) (call-interactively 'org-move-item-up))
19879 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19880 (call-interactively 'org-timestamp-up)))
19881 (t (call-interactively 'org-drag-line-backward))))
19883 (defun org-shiftmetadown (&optional arg)
19884 "Move subtree down or insert table row.
19885 Calls `org-move-subtree-down' or `org-table-insert-row' or
19886 `org-move-item-down' or `org-timestamp-up', depending on context.
19887 See the individual commands for more information."
19888 (interactive "P")
19889 (cond
19890 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19891 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19892 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19893 ((org-at-item-p) (call-interactively 'org-move-item-down))
19894 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19895 (call-interactively 'org-timestamp-down)))
19896 (t (call-interactively 'org-drag-line-forward))))
19898 (defsubst org-hidden-tree-error ()
19899 (user-error
19900 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19902 (defun org-metaleft (&optional arg)
19903 "Promote heading or move table column to left.
19904 Calls `org-do-promote' or `org-table-move-column', depending on context.
19905 With no specific context, calls the Emacs default `backward-word'.
19906 See the individual commands for more information."
19907 (interactive "P")
19908 (cond
19909 ((run-hook-with-args-until-success 'org-metaleft-hook))
19910 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19911 ((org-with-limited-levels
19912 (or (org-at-heading-p)
19913 (and (org-region-active-p)
19914 (save-excursion
19915 (goto-char (region-beginning))
19916 (org-at-heading-p)))))
19917 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19918 (call-interactively 'org-do-promote))
19919 ;; At an inline task.
19920 ((org-at-heading-p)
19921 (call-interactively 'org-inlinetask-promote))
19922 ((or (org-at-item-p)
19923 (and (org-region-active-p)
19924 (save-excursion
19925 (goto-char (region-beginning))
19926 (org-at-item-p))))
19927 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19928 (call-interactively 'org-outdent-item))
19929 (t (call-interactively 'backward-word))))
19931 (defun org-metaright (&optional arg)
19932 "Demote a subtree, a list item or move table column to right.
19933 In front of a drawer or a block keyword, indent it correctly.
19934 With no specific context, calls the Emacs default `forward-word'.
19935 See the individual commands for more information."
19936 (interactive "P")
19937 (cond
19938 ((run-hook-with-args-until-success 'org-metaright-hook))
19939 ((org-at-table-p) (call-interactively 'org-table-move-column))
19940 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19941 ((org-at-block-p) (call-interactively 'org-indent-block))
19942 ((org-with-limited-levels
19943 (or (org-at-heading-p)
19944 (and (org-region-active-p)
19945 (save-excursion
19946 (goto-char (region-beginning))
19947 (org-at-heading-p)))))
19948 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19949 (call-interactively 'org-do-demote))
19950 ;; At an inline task.
19951 ((org-at-heading-p)
19952 (call-interactively 'org-inlinetask-demote))
19953 ((or (org-at-item-p)
19954 (and (org-region-active-p)
19955 (save-excursion
19956 (goto-char (region-beginning))
19957 (org-at-item-p))))
19958 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19959 (call-interactively 'org-indent-item))
19960 (t (call-interactively 'forward-word))))
19962 (defun org-check-for-hidden (what)
19963 "Check if there are hidden headlines/items in the current visual line.
19964 WHAT can be either `headlines' or `items'. If the current line is
19965 an outline or item heading and it has a folded subtree below it,
19966 this function returns t, nil otherwise."
19967 (let ((re (cond
19968 ((eq what 'headlines) org-outline-regexp-bol)
19969 ((eq what 'items) (org-item-beginning-re))
19970 (t (error "This should not happen"))))
19971 beg end)
19972 (save-excursion
19973 (catch 'exit
19974 (unless (org-region-active-p)
19975 (setq beg (point-at-bol))
19976 (beginning-of-line 2)
19977 (while (and (not (eobp)) ;; this is like `next-line'
19978 (get-char-property (1- (point)) 'invisible))
19979 (beginning-of-line 2))
19980 (setq end (point))
19981 (goto-char beg)
19982 (goto-char (point-at-eol))
19983 (setq end (max end (point)))
19984 (while (re-search-forward re end t)
19985 (if (get-char-property (match-beginning 0) 'invisible)
19986 (throw 'exit t))))
19987 nil))))
19989 (defun org-metaup (&optional arg)
19990 "Move subtree up or move table row up.
19991 Calls `org-move-subtree-up' or `org-table-move-row' or
19992 `org-move-item-up', depending on context. See the individual commands
19993 for more information."
19994 (interactive "P")
19995 (cond
19996 ((run-hook-with-args-until-success 'org-metaup-hook))
19997 ((org-region-active-p)
19998 (let* ((a (min (region-beginning) (region-end)))
19999 (b (1- (max (region-beginning) (region-end))))
20000 (c (save-excursion (goto-char a)
20001 (move-beginning-of-line 0)))
20002 (d (save-excursion (goto-char a)
20003 (move-end-of-line 0) (point))))
20004 (transpose-regions a b c d)
20005 (goto-char c)))
20006 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20007 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20008 ((org-at-item-p) (call-interactively 'org-move-item-up))
20009 (t (org-drag-element-backward))))
20011 (defun org-metadown (&optional arg)
20012 "Move subtree down or move table row down.
20013 Calls `org-move-subtree-down' or `org-table-move-row' or
20014 `org-move-item-down', depending on context. See the individual
20015 commands for more information."
20016 (interactive "P")
20017 (cond
20018 ((run-hook-with-args-until-success 'org-metadown-hook))
20019 ((org-region-active-p)
20020 (let* ((a (min (region-beginning) (region-end)))
20021 (b (max (region-beginning) (region-end)))
20022 (c (save-excursion (goto-char b)
20023 (move-beginning-of-line 1)))
20024 (d (save-excursion (goto-char b)
20025 (move-end-of-line 1) (1+ (point)))))
20026 (transpose-regions a b c d)
20027 (goto-char d)))
20028 ((org-at-table-p) (call-interactively 'org-table-move-row))
20029 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20030 ((org-at-item-p) (call-interactively 'org-move-item-down))
20031 (t (org-drag-element-forward))))
20033 (defun org-shiftup (&optional arg)
20034 "Increase item in timestamp or increase priority of current headline.
20035 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20036 depending on context. See the individual commands for more information."
20037 (interactive "P")
20038 (cond
20039 ((run-hook-with-args-until-success 'org-shiftup-hook))
20040 ((and org-support-shift-select (org-region-active-p))
20041 (org-call-for-shift-select 'previous-line))
20042 ((org-at-timestamp-p t)
20043 (call-interactively (if org-edit-timestamp-down-means-later
20044 'org-timestamp-down 'org-timestamp-up)))
20045 ((and (not (eq org-support-shift-select 'always))
20046 org-enable-priority-commands
20047 (org-at-heading-p))
20048 (call-interactively 'org-priority-up))
20049 ((and (not org-support-shift-select) (org-at-item-p))
20050 (call-interactively 'org-previous-item))
20051 ((org-clocktable-try-shift 'up arg))
20052 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20053 (org-support-shift-select
20054 (org-call-for-shift-select 'previous-line))
20055 (t (org-shiftselect-error))))
20057 (defun org-shiftdown (&optional arg)
20058 "Decrease item in timestamp or decrease priority of current headline.
20059 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20060 depending on context. See the individual commands for more information."
20061 (interactive "P")
20062 (cond
20063 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20064 ((and org-support-shift-select (org-region-active-p))
20065 (org-call-for-shift-select 'next-line))
20066 ((org-at-timestamp-p t)
20067 (call-interactively (if org-edit-timestamp-down-means-later
20068 'org-timestamp-up 'org-timestamp-down)))
20069 ((and (not (eq org-support-shift-select 'always))
20070 org-enable-priority-commands
20071 (org-at-heading-p))
20072 (call-interactively 'org-priority-down))
20073 ((and (not org-support-shift-select) (org-at-item-p))
20074 (call-interactively 'org-next-item))
20075 ((org-clocktable-try-shift 'down arg))
20076 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20077 (org-support-shift-select
20078 (org-call-for-shift-select 'next-line))
20079 (t (org-shiftselect-error))))
20081 (defun org-shiftright (&optional arg)
20082 "Cycle the thing at point or in the current line, depending on context.
20083 Depending on context, this does one of the following:
20085 - switch a timestamp at point one day into the future
20086 - on a headline, switch to the next TODO keyword.
20087 - on an item, switch entire list to the next bullet type
20088 - on a property line, switch to the next allowed value
20089 - on a clocktable definition line, move time block into the future"
20090 (interactive "P")
20091 (cond
20092 ((run-hook-with-args-until-success 'org-shiftright-hook))
20093 ((and org-support-shift-select (org-region-active-p))
20094 (org-call-for-shift-select 'forward-char))
20095 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20096 ((and (not (eq org-support-shift-select 'always))
20097 (org-at-heading-p))
20098 (let ((org-inhibit-logging
20099 (not org-treat-S-cursor-todo-selection-as-state-change))
20100 (org-inhibit-blocking
20101 (not org-treat-S-cursor-todo-selection-as-state-change)))
20102 (org-call-with-arg 'org-todo 'right)))
20103 ((or (and org-support-shift-select
20104 (not (eq org-support-shift-select 'always))
20105 (org-at-item-bullet-p))
20106 (and (not org-support-shift-select) (org-at-item-p)))
20107 (org-call-with-arg 'org-cycle-list-bullet nil))
20108 ((and (not (eq org-support-shift-select 'always))
20109 (org-at-property-p))
20110 (call-interactively 'org-property-next-allowed-value))
20111 ((org-clocktable-try-shift 'right arg))
20112 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20113 (org-support-shift-select
20114 (org-call-for-shift-select 'forward-char))
20115 (t (org-shiftselect-error))))
20117 (defun org-shiftleft (&optional arg)
20118 "Cycle the thing at point or in the current line, depending on context.
20119 Depending on context, this does one of the following:
20121 - switch a timestamp at point one day into the past
20122 - on a headline, switch to the previous TODO keyword.
20123 - on an item, switch entire list to the previous bullet type
20124 - on a property line, switch to the previous allowed value
20125 - on a clocktable definition line, move time block into the past"
20126 (interactive "P")
20127 (cond
20128 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20129 ((and org-support-shift-select (org-region-active-p))
20130 (org-call-for-shift-select 'backward-char))
20131 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20132 ((and (not (eq org-support-shift-select 'always))
20133 (org-at-heading-p))
20134 (let ((org-inhibit-logging
20135 (not org-treat-S-cursor-todo-selection-as-state-change))
20136 (org-inhibit-blocking
20137 (not org-treat-S-cursor-todo-selection-as-state-change)))
20138 (org-call-with-arg 'org-todo 'left)))
20139 ((or (and org-support-shift-select
20140 (not (eq org-support-shift-select 'always))
20141 (org-at-item-bullet-p))
20142 (and (not org-support-shift-select) (org-at-item-p)))
20143 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20144 ((and (not (eq org-support-shift-select 'always))
20145 (org-at-property-p))
20146 (call-interactively 'org-property-previous-allowed-value))
20147 ((org-clocktable-try-shift 'left arg))
20148 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20149 (org-support-shift-select
20150 (org-call-for-shift-select 'backward-char))
20151 (t (org-shiftselect-error))))
20153 (defun org-shiftcontrolright ()
20154 "Switch to next TODO set."
20155 (interactive)
20156 (cond
20157 ((and org-support-shift-select (org-region-active-p))
20158 (org-call-for-shift-select 'forward-word))
20159 ((and (not (eq org-support-shift-select 'always))
20160 (org-at-heading-p))
20161 (org-call-with-arg 'org-todo 'nextset))
20162 (org-support-shift-select
20163 (org-call-for-shift-select 'forward-word))
20164 (t (org-shiftselect-error))))
20166 (defun org-shiftcontrolleft ()
20167 "Switch to previous TODO set."
20168 (interactive)
20169 (cond
20170 ((and org-support-shift-select (org-region-active-p))
20171 (org-call-for-shift-select 'backward-word))
20172 ((and (not (eq org-support-shift-select 'always))
20173 (org-at-heading-p))
20174 (org-call-with-arg 'org-todo 'previousset))
20175 (org-support-shift-select
20176 (org-call-for-shift-select 'backward-word))
20177 (t (org-shiftselect-error))))
20179 (defun org-shiftcontrolup (&optional n)
20180 "Change timestamps synchronously up in CLOCK log lines.
20181 Optional argument N tells to change by that many units."
20182 (interactive "P")
20183 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20184 (let (org-support-shift-select)
20185 (org-clock-timestamps-up n))
20186 (user-error "Not at a clock log")))
20188 (defun org-shiftcontroldown (&optional n)
20189 "Change timestamps synchronously down in CLOCK log lines.
20190 Optional argument N tells to change by that many units."
20191 (interactive "P")
20192 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20193 (let (org-support-shift-select)
20194 (org-clock-timestamps-down n))
20195 (user-error "Not at a clock log")))
20197 (defun org-ctrl-c-ret ()
20198 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20199 (interactive)
20200 (cond
20201 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20202 (t (call-interactively 'org-insert-heading))))
20204 (defun org-find-visible ()
20205 (let ((s (point)))
20206 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20207 (get-char-property s 'invisible)))
20209 (defun org-find-invisible ()
20210 (let ((s (point)))
20211 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20212 (not (get-char-property s 'invisible))))
20215 (defun org-copy-visible (beg end)
20216 "Copy the visible parts of the region."
20217 (interactive "r")
20218 (let (snippets s)
20219 (save-excursion
20220 (save-restriction
20221 (narrow-to-region beg end)
20222 (setq s (goto-char (point-min)))
20223 (while (not (= (point) (point-max)))
20224 (goto-char (org-find-invisible))
20225 (push (buffer-substring s (point)) snippets)
20226 (setq s (goto-char (org-find-visible))))))
20227 (kill-new (apply 'concat (nreverse snippets)))))
20229 (defun org-copy-special ()
20230 "Copy region in table or copy current subtree.
20231 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20232 See the individual commands for more information."
20233 (interactive)
20234 (call-interactively
20235 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20237 (defun org-cut-special ()
20238 "Cut region in table or cut current subtree.
20239 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20240 See the individual commands for more information."
20241 (interactive)
20242 (call-interactively
20243 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20245 (defun org-paste-special (arg)
20246 "Paste rectangular region into table, or past subtree relative to level.
20247 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20248 See the individual commands for more information."
20249 (interactive "P")
20250 (if (org-at-table-p)
20251 (org-table-paste-rectangle)
20252 (org-paste-subtree arg)))
20254 (defsubst org-in-fixed-width-region-p ()
20255 "Is point in a fixed-width region?"
20256 (save-match-data
20257 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20259 (defun org-edit-special (&optional arg)
20260 "Call a special editor for the element at point.
20261 When at a table, call the formula editor with `org-table-edit-formulas'.
20262 When in a source code block, call `org-edit-src-code'.
20263 When in a fixed-width region, call `org-edit-fixed-width-region'.
20264 When at an #+INCLUDE keyword, visit the included file.
20265 On a link, call `ffap' to visit the link at point.
20266 Otherwise, return a user error."
20267 (interactive "P")
20268 (let ((element (org-element-at-point)))
20269 (assert (not buffer-read-only) nil
20270 "Buffer is read-only: %s" (buffer-name))
20271 (case (org-element-type element)
20272 (src-block
20273 (if (not arg) (org-edit-src-code)
20274 (let* ((info (org-babel-get-src-block-info))
20275 (lang (nth 0 info))
20276 (params (nth 2 info))
20277 (session (cdr (assq :session params))))
20278 (if (not session) (org-edit-src-code)
20279 ;; At a src-block with a session and function called with
20280 ;; an ARG: switch to the buffer related to the inferior
20281 ;; process.
20282 (switch-to-buffer
20283 (funcall (intern (concat "org-babel-prep-session:" lang))
20284 session params))))))
20285 (keyword
20286 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20287 (find-file-other-window
20288 (org-remove-double-quotes
20289 (car (org-split-string (org-element-property :value element)))))
20290 (user-error "No special environment to edit here")))
20291 (table
20292 (if (eq (org-element-property :type element) 'table.el)
20293 (org-edit-src-code)
20294 (call-interactively 'org-table-edit-formulas)))
20295 ;; Only Org tables contain `table-row' type elements.
20296 (table-row (call-interactively 'org-table-edit-formulas))
20297 ((example-block export-block) (org-edit-src-code))
20298 (fixed-width (org-edit-fixed-width-region))
20299 (otherwise
20300 ;; No notable element at point. Though, we may be at a link,
20301 ;; which is an object. Thus, scan deeper.
20302 (if (eq (org-element-type (org-element-context element)) 'link)
20303 (call-interactively 'ffap)
20304 (user-error "No special environment to edit here"))))))
20306 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20307 (defun org-ctrl-c-ctrl-c (&optional arg)
20308 "Set tags in headline, or update according to changed information at point.
20310 This command does many different things, depending on context:
20312 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20313 this is what we do.
20315 - If the cursor is on a statistics cookie, update it.
20317 - If the cursor is in a headline, prompt for tags and insert them
20318 into the current line, aligned to `org-tags-column'. When called
20319 with prefix arg, realign all tags in the current buffer.
20321 - If the cursor is in one of the special #+KEYWORD lines, this
20322 triggers scanning the buffer for these lines and updating the
20323 information.
20325 - If the cursor is inside a table, realign the table. This command
20326 works even if the automatic table editor has been turned off.
20328 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20329 the entire table.
20331 - If the cursor is at a footnote reference or definition, jump to
20332 the corresponding definition or references, respectively.
20334 - If the cursor is a the beginning of a dynamic block, update it.
20336 - If the current buffer is a capture buffer, close note and file it.
20338 - If the cursor is on a <<<target>>>, update radio targets and
20339 corresponding links in this buffer.
20341 - If the cursor is on a numbered item in a plain list, renumber the
20342 ordered list.
20344 - If the cursor is on a checkbox, toggle it.
20346 - If the cursor is on a code block, evaluate it. The variable
20347 `org-confirm-babel-evaluate' can be used to control prompting
20348 before code block evaluation, by default every code block
20349 evaluation requires confirmation. Code block evaluation can be
20350 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20351 (interactive "P")
20352 (cond
20353 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20354 org-occur-highlights
20355 org-latex-fragment-image-overlays)
20356 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20357 (org-remove-occur-highlights)
20358 (org-remove-latex-fragment-image-overlays)
20359 (message "Temporary highlights/overlays removed from current buffer"))
20360 ((and (local-variable-p 'org-finish-function (current-buffer))
20361 (fboundp org-finish-function))
20362 (funcall org-finish-function))
20363 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20365 (let* ((context (org-element-context)) (type (org-element-type context)))
20366 ;; Test if point is within a blank line.
20367 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20368 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20369 (user-error "C-c C-c can do nothing useful at this location"))
20370 (case type
20371 ;; When at a link, act according to the parent instead.
20372 (link (setq context (org-element-property :parent context))
20373 (setq type (org-element-type context)))
20374 ;; Unsupported object types: check parent element instead.
20375 ((bold code entity export-snippet inline-babel-call inline-src-block
20376 italic latex-fragment line-break macro strike-through subscript
20377 superscript underline verbatim)
20378 (while (and (setq context (org-element-property :parent context))
20379 (not (memq (setq type (org-element-type context))
20380 '(paragraph verse-block)))))))
20381 ;; For convenience: at the first line of a paragraph on the
20382 ;; same line as an item, apply function on that item instead.
20383 (when (eq type 'paragraph)
20384 (let ((parent (org-element-property :parent context)))
20385 (when (and (eq (org-element-type parent) 'item)
20386 (= (point-at-bol) (org-element-property :begin parent)))
20387 (setq context parent type 'item))))
20388 ;; Act according to type of element or object at point.
20389 (case type
20390 (clock (org-clock-update-time-maybe))
20391 (dynamic-block
20392 (save-excursion
20393 (goto-char (org-element-property :post-affiliated context))
20394 (org-update-dblock)))
20395 (footnote-definition
20396 (goto-char (org-element-property :post-affiliated context))
20397 (call-interactively 'org-footnote-action))
20398 (footnote-reference (call-interactively 'org-footnote-action))
20399 ((headline inlinetask)
20400 (save-excursion (goto-char (org-element-property :begin context))
20401 (call-interactively 'org-set-tags)))
20402 (item
20403 ;; At an item: a double C-u set checkbox to "[-]"
20404 ;; unconditionally, whereas a single one will toggle its
20405 ;; presence. Without an universal argument, if the item
20406 ;; has a checkbox, toggle it. Otherwise repair the list.
20407 (let* ((box (org-element-property :checkbox context))
20408 (struct (org-element-property :structure context))
20409 (old-struct (copy-tree struct))
20410 (parents (org-list-parents-alist struct))
20411 (prevs (org-list-prevs-alist struct))
20412 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20413 (org-list-set-checkbox
20414 (org-element-property :begin context) struct
20415 (cond ((equal arg '(16)) "[-]")
20416 ((and (not box) (equal arg '(4))) "[ ]")
20417 ((or (not box) (equal arg '(4))) nil)
20418 ((eq box 'on) "[ ]")
20419 (t "[X]")))
20420 ;; Mimic `org-list-write-struct' but with grabbing
20421 ;; a return value from `org-list-struct-fix-box'.
20422 (org-list-struct-fix-ind struct parents 2)
20423 (org-list-struct-fix-item-end struct)
20424 (org-list-struct-fix-bul struct prevs)
20425 (org-list-struct-fix-ind struct parents)
20426 (let ((block-item
20427 (org-list-struct-fix-box struct parents prevs orderedp)))
20428 (if (and box (equal struct old-struct))
20429 (if (equal arg '(16))
20430 (message "Checkboxes already reset")
20431 (user-error "Cannot toggle this checkbox: %s"
20432 (if (eq box 'on)
20433 "all subitems checked"
20434 "unchecked subitems")))
20435 (org-list-struct-apply-struct struct old-struct)
20436 (org-update-checkbox-count-maybe))
20437 (when block-item
20438 (message "Checkboxes were removed due to empty box at line %d"
20439 (org-current-line block-item))))))
20440 (keyword
20441 (let ((org-inhibit-startup-visibility-stuff t)
20442 (org-startup-align-all-tables nil))
20443 (when (boundp 'org-table-coordinate-overlays)
20444 (mapc 'delete-overlay org-table-coordinate-overlays)
20445 (setq org-table-coordinate-overlays nil))
20446 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20447 (message "Local setup has been refreshed"))
20448 (plain-list
20449 ;; At a plain list, with a double C-u argument, set
20450 ;; checkboxes of each item to "[-]", whereas a single one
20451 ;; will toggle their presence according to the state of the
20452 ;; first item in the list. Without an argument, repair the
20453 ;; list.
20454 (let* ((begin (org-element-property :contents-begin context))
20455 (beginm (move-marker (make-marker) begin))
20456 (struct (org-element-property :structure context))
20457 (old-struct (copy-tree struct))
20458 (first-box (save-excursion
20459 (goto-char begin)
20460 (looking-at org-list-full-item-re)
20461 (match-string-no-properties 3)))
20462 (new-box (cond ((equal arg '(16)) "[-]")
20463 ((equal arg '(4)) (unless first-box "[ ]"))
20464 ((equal first-box "[X]") "[ ]")
20465 (t "[X]"))))
20466 (cond
20467 (arg
20468 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20469 (org-list-get-all-items
20470 begin struct (org-list-prevs-alist struct))))
20471 ((and first-box (eq (point) begin))
20472 ;; For convenience, when point is at bol on the first
20473 ;; item of the list and no argument is provided, simply
20474 ;; toggle checkbox of that item, if any.
20475 (org-list-set-checkbox begin struct new-box)))
20476 (org-list-write-struct
20477 struct (org-list-parents-alist struct) old-struct)
20478 (org-update-checkbox-count-maybe)
20479 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20480 ((property-drawer node-property)
20481 (call-interactively 'org-property-action))
20482 ((radio-target target)
20483 (call-interactively 'org-update-radio-target-regexp))
20484 (statistics-cookie
20485 (call-interactively 'org-update-statistics-cookies))
20486 ((table table-cell table-row)
20487 ;; At a table, recalculate every field and align it. Also
20488 ;; send the table if necessary. If the table has
20489 ;; a `table.el' type, just give up. At a table row or
20490 ;; cell, maybe recalculate line but always align table.
20491 (if (eq (org-element-property :type context) 'table.el)
20492 (message "Use C-c ' to edit table.el tables")
20493 (let ((org-enable-table-editor t))
20494 (if (or (eq type 'table)
20495 ;; Check if point is at a TBLFM line.
20496 (and (eq type 'table-row)
20497 (= (point) (org-element-property :end context))))
20498 (save-excursion
20499 (if (org-at-TBLFM-p)
20500 (progn (require 'org-table)
20501 (org-table-calc-current-TBLFM))
20502 (goto-char (org-element-property :contents-begin context))
20503 (org-call-with-arg 'org-table-recalculate (or arg t))
20504 (orgtbl-send-table 'maybe)))
20505 (org-table-maybe-eval-formula)
20506 (cond (arg (call-interactively 'org-table-recalculate))
20507 ((org-table-maybe-recalculate-line))
20508 (t (org-table-align)))))))
20509 (timestamp (org-timestamp-change 0 'day))
20510 (otherwise
20511 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20512 (user-error
20513 "C-c C-c can do nothing useful at this location")))))))))
20515 (defun org-mode-restart ()
20516 (interactive)
20517 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20518 (funcall major-mode)
20519 (hack-local-variables)
20520 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20521 (org-indent-mode -1)))
20522 (message "%s restarted" major-mode))
20524 (defun org-kill-note-or-show-branches ()
20525 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20526 (interactive)
20527 (if (not org-finish-function)
20528 (progn
20529 (hide-subtree)
20530 (call-interactively 'show-branches))
20531 (let ((org-note-abort t))
20532 (funcall org-finish-function))))
20534 (defun org-open-line (n)
20535 "Insert a new row in tables, call `open-line' elsewhere.
20536 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20537 (interactive "*p")
20538 (cond
20539 ((not org-special-ctrl-o)
20540 (open-line n))
20541 ((org-at-table-p)
20542 (org-table-insert-row))
20544 (open-line n))))
20546 (defun org-return (&optional indent)
20547 "Goto next table row or insert a newline.
20548 Calls `org-table-next-row' or `newline', depending on context.
20549 See the individual commands for more information."
20550 (interactive)
20551 (let (org-ts-what)
20552 (cond
20553 ((or (bobp) (org-in-src-block-p))
20554 (if indent (newline-and-indent) (newline)))
20555 ((org-at-table-p)
20556 (org-table-justify-field-maybe)
20557 (call-interactively 'org-table-next-row))
20558 ;; when `newline-and-indent' is called within a list, make sure
20559 ;; text moved stays inside the item.
20560 ((and (org-in-item-p) indent)
20561 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20562 (progn
20563 (save-match-data (newline))
20564 (org-indent-line-to (length (match-string 0))))
20565 (let ((ind (org-get-indentation)))
20566 (newline)
20567 (if (org-looking-back org-list-end-re)
20568 (org-indent-line)
20569 (org-indent-line-to ind)))))
20570 ((and org-return-follows-link
20571 (org-at-timestamp-p t)
20572 (not (eq org-ts-what 'after)))
20573 (org-follow-timestamp-link))
20574 ((and org-return-follows-link
20575 (let ((tprop (get-text-property (point) 'face)))
20576 (or (eq tprop 'org-link)
20577 (and (listp tprop) (memq 'org-link tprop)))))
20578 (call-interactively 'org-open-at-point))
20579 ((and (org-at-heading-p)
20580 (looking-at
20581 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20582 (org-show-entry)
20583 (end-of-line 1)
20584 (newline))
20585 (t (if indent (newline-and-indent) (newline))))))
20587 (defun org-return-indent ()
20588 "Goto next table row or insert a newline and indent.
20589 Calls `org-table-next-row' or `newline-and-indent', depending on
20590 context. See the individual commands for more information."
20591 (interactive)
20592 (org-return t))
20594 (defun org-ctrl-c-star ()
20595 "Compute table, or change heading status of lines.
20596 Calls `org-table-recalculate' or `org-toggle-heading',
20597 depending on context."
20598 (interactive)
20599 (cond
20600 ((org-at-table-p)
20601 (call-interactively 'org-table-recalculate))
20603 ;; Convert all lines in region to list items
20604 (call-interactively 'org-toggle-heading))))
20606 (defun org-ctrl-c-minus ()
20607 "Insert separator line in table or modify bullet status of line.
20608 Also turns a plain line or a region of lines into list items.
20609 Calls `org-table-insert-hline', `org-toggle-item', or
20610 `org-cycle-list-bullet', depending on context."
20611 (interactive)
20612 (cond
20613 ((org-at-table-p)
20614 (call-interactively 'org-table-insert-hline))
20615 ((org-region-active-p)
20616 (call-interactively 'org-toggle-item))
20617 ((org-in-item-p)
20618 (call-interactively 'org-cycle-list-bullet))
20620 (call-interactively 'org-toggle-item))))
20622 (defun org-toggle-item (arg)
20623 "Convert headings or normal lines to items, items to normal lines.
20624 If there is no active region, only the current line is considered.
20626 If the first non blank line in the region is a headline, convert
20627 all headlines to items, shifting text accordingly.
20629 If it is an item, convert all items to normal lines.
20631 If it is normal text, change region into a list of items.
20632 With a prefix argument ARG, change the region in a single item."
20633 (interactive "P")
20634 (let ((shift-text
20635 (function
20636 ;; Shift text in current section to IND, from point to END.
20637 ;; The function leaves point to END line.
20638 (lambda (ind end)
20639 (let ((min-i 1000) (end (copy-marker end)))
20640 ;; First determine the minimum indentation (MIN-I) of
20641 ;; the text.
20642 (save-excursion
20643 (catch 'exit
20644 (while (< (point) end)
20645 (let ((i (org-get-indentation)))
20646 (cond
20647 ;; Skip blank lines and inline tasks.
20648 ((looking-at "^[ \t]*$"))
20649 ((looking-at org-outline-regexp-bol))
20650 ;; We can't find less than 0 indentation.
20651 ((zerop i) (throw 'exit (setq min-i 0)))
20652 ((< i min-i) (setq min-i i))))
20653 (forward-line))))
20654 ;; Then indent each line so that a line indented to
20655 ;; MIN-I becomes indented to IND. Ignore blank lines
20656 ;; and inline tasks in the process.
20657 (let ((delta (- ind min-i)))
20658 (while (< (point) end)
20659 (unless (or (looking-at "^[ \t]*$")
20660 (looking-at org-outline-regexp-bol))
20661 (org-indent-line-to (+ (org-get-indentation) delta)))
20662 (forward-line)))))))
20663 (skip-blanks
20664 (function
20665 ;; Return beginning of first non-blank line, starting from
20666 ;; line at POS.
20667 (lambda (pos)
20668 (save-excursion
20669 (goto-char pos)
20670 (skip-chars-forward " \r\t\n")
20671 (point-at-bol)))))
20672 beg end)
20673 ;; Determine boundaries of changes.
20674 (if (org-region-active-p)
20675 (setq beg (funcall skip-blanks (region-beginning))
20676 end (copy-marker (region-end)))
20677 (setq beg (funcall skip-blanks (point-at-bol))
20678 end (copy-marker (point-at-eol))))
20679 ;; Depending on the starting line, choose an action on the text
20680 ;; between BEG and END.
20681 (org-with-limited-levels
20682 (save-excursion
20683 (goto-char beg)
20684 (cond
20685 ;; Case 1. Start at an item: de-itemize. Note that it only
20686 ;; happens when a region is active: `org-ctrl-c-minus'
20687 ;; would call `org-cycle-list-bullet' otherwise.
20688 ((org-at-item-p)
20689 (while (< (point) end)
20690 (when (org-at-item-p)
20691 (skip-chars-forward " \t")
20692 (delete-region (point) (match-end 0)))
20693 (forward-line)))
20694 ;; Case 2. Start at an heading: convert to items.
20695 ((org-at-heading-p)
20696 (let* ((bul (org-list-bullet-string "-"))
20697 (bul-len (length bul))
20698 (done (org-entry-is-done-p))
20699 (todo (org-entry-is-todo-p))
20700 ;; Indentation of the first heading. It should be
20701 ;; relative to the indentation of its parent, if any.
20702 (start-ind (save-excursion
20703 (cond
20704 ((not org-adapt-indentation) 0)
20705 ((not (outline-previous-heading)) 0)
20706 (t (length (match-string 0))))))
20707 ;; Level of first heading. Further headings will be
20708 ;; compared to it to determine hierarchy in the list.
20709 (ref-level (org-reduced-level (org-outline-level))))
20710 (when (or done todo) (org-todo ""))
20711 (while (< (point) end)
20712 (let* ((level (org-reduced-level (org-outline-level)))
20713 (delta (max 0 (- level ref-level))))
20714 ;; If current headline is less indented than the first
20715 ;; one, set it as reference, in order to preserve
20716 ;; subtrees.
20717 (when (< level ref-level) (setq ref-level level))
20718 (replace-match bul t t)
20719 (org-indent-line-to (+ start-ind (* delta bul-len)))
20720 (when (or done todo)
20721 (let* ((struct (org-list-struct))
20722 (old (copy-tree struct)))
20723 (org-list-set-checkbox (line-beginning-position)
20724 struct
20725 (if done "[X]" "[ ]"))
20726 (org-list-write-struct struct
20727 (org-list-parents-alist struct)
20728 old)))
20729 ;; Ensure all text down to END (or SECTION-END) belongs
20730 ;; to the newly created item.
20731 (let ((section-end (save-excursion
20732 (or (outline-next-heading) (point)))))
20733 (forward-line)
20734 (funcall shift-text
20735 (+ start-ind (* (1+ delta) bul-len))
20736 (min end section-end)))))))
20737 ;; Case 3. Normal line with ARG: make the first line of region
20738 ;; an item, and shift indentation of others lines to
20739 ;; set them as item's body.
20740 (arg (let* ((bul (org-list-bullet-string "-"))
20741 (bul-len (length bul))
20742 (ref-ind (org-get-indentation)))
20743 (skip-chars-forward " \t")
20744 (insert bul)
20745 (forward-line)
20746 (while (< (point) end)
20747 ;; Ensure that lines less indented than first one
20748 ;; still get included in item body.
20749 (funcall shift-text
20750 (+ ref-ind bul-len)
20751 (min end (save-excursion (or (outline-next-heading)
20752 (point)))))
20753 (forward-line))))
20754 ;; Case 4. Normal line without ARG: turn each non-item line
20755 ;; into an item.
20757 (while (< (point) end)
20758 (unless (or (org-at-heading-p) (org-at-item-p))
20759 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20760 (replace-match
20761 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20762 (forward-line))))))))
20764 (defun org-toggle-heading (&optional nstars)
20765 "Convert headings to normal text, or items or text to headings.
20766 If there is no active region, only convert the current line.
20768 With a \\[universal-argument] prefix, convert the whole list at
20769 point into heading.
20771 In a region:
20773 - If the first non blank line is a headline, remove the stars
20774 from all headlines in the region.
20776 - If it is a normal line, turn each and every normal line (i.e.,
20777 not an heading or an item) in the region into headings. If you
20778 want to convert only the first line of this region, use one
20779 universal prefix argument.
20781 - If it is a plain list item, turn all plain list items into headings.
20783 When converting a line into a heading, the number of stars is chosen
20784 such that the lines become children of the current entry. However,
20785 when a numeric prefix argument is given, its value determines the
20786 number of stars to add."
20787 (interactive "P")
20788 (let ((skip-blanks
20789 (function
20790 ;; Return beginning of first non-blank line, starting from
20791 ;; line at POS.
20792 (lambda (pos)
20793 (save-excursion
20794 (goto-char pos)
20795 (while (org-at-comment-p) (forward-line))
20796 (skip-chars-forward " \r\t\n")
20797 (point-at-bol)))))
20798 beg end toggled)
20799 ;; Determine boundaries of changes. If a universal prefix has
20800 ;; been given, put the list in a region. If region ends at a bol,
20801 ;; do not consider the last line to be in the region.
20803 (when (and current-prefix-arg (org-at-item-p))
20804 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20805 (org-mark-element))
20807 (if (org-region-active-p)
20808 (setq beg (funcall skip-blanks (region-beginning))
20809 end (copy-marker (save-excursion
20810 (goto-char (region-end))
20811 (if (bolp) (point) (point-at-eol)))))
20812 (setq beg (funcall skip-blanks (point-at-bol))
20813 end (copy-marker (point-at-eol))))
20814 ;; Ensure inline tasks don't count as headings.
20815 (org-with-limited-levels
20816 (save-excursion
20817 (goto-char beg)
20818 (cond
20819 ;; Case 1. Started at an heading: de-star headings.
20820 ((org-at-heading-p)
20821 (while (< (point) end)
20822 (when (org-at-heading-p t)
20823 (looking-at org-outline-regexp) (replace-match "")
20824 (setq toggled t))
20825 (forward-line)))
20826 ;; Case 2. Started at an item: change items into headlines.
20827 ;; One star will be added by `org-list-to-subtree'.
20828 ((org-at-item-p)
20829 (let* ((stars (make-string
20830 ;; subtract the star that will be added again by
20831 ;; `org-list-to-subtree'
20832 (if (numberp nstars) (1- nstars)
20833 (or (org-current-level) 0))
20834 ?*))
20835 (add-stars
20836 (cond (nstars "") ; stars from prefix only
20837 ((equal stars "") "") ; before first heading
20838 (org-odd-levels-only "*") ; inside heading, odd
20839 (t "")))) ; inside heading, oddeven
20840 (while (< (point) end)
20841 (when (org-at-item-p)
20842 ;; Pay attention to cases when region ends before list.
20843 (let* ((struct (org-list-struct))
20844 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20845 (save-restriction
20846 (narrow-to-region (point) list-end)
20847 (insert
20848 (org-list-to-subtree
20849 (org-list-parse-list t)
20850 '(:istart (concat stars add-stars (funcall get-stars depth))
20851 :icount (concat stars add-stars (funcall get-stars depth)))))))
20852 (setq toggled t))
20853 (forward-line))))
20854 ;; Case 3. Started at normal text: make every line an heading,
20855 ;; skipping headlines and items.
20856 (t (let* ((stars
20857 (make-string
20858 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20859 (add-stars
20860 (cond (nstars "") ; stars from prefix only
20861 ((equal stars "") "*") ; before first heading
20862 (org-odd-levels-only "**") ; inside heading, odd
20863 (t "*"))) ; inside heading, oddeven
20864 (rpl (concat stars add-stars " "))
20865 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20866 (while (< (point) (if (equal nstars '(4)) lend end))
20867 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20868 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20869 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20870 (forward-line)))))))
20871 (unless toggled (message "Cannot toggle heading from here"))))
20873 (defun org-meta-return (&optional arg)
20874 "Insert a new heading or wrap a region in a table.
20875 Calls `org-insert-heading' or `org-table-wrap-region', depending
20876 on context. See the individual commands for more information."
20877 (interactive "P")
20878 (org-check-before-invisible-edit 'insert)
20879 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20880 (let* ((element (org-element-at-point))
20881 (type (org-element-type element)))
20882 (when (eq type 'table-row)
20883 (setq element (org-element-property :parent element))
20884 (setq type 'table))
20885 (if (and (eq type 'table)
20886 (eq (org-element-property :type element) 'org)
20887 (>= (point) (org-element-property :contents-begin element))
20888 (< (point) (org-element-property :contents-end element)))
20889 (call-interactively 'org-table-wrap-region)
20890 (call-interactively 'org-insert-heading)))))
20892 ;;; Menu entries
20894 (defsubst org-in-subtree-not-table-p ()
20895 "Are we in a subtree and not in a table?"
20896 (and (not (org-before-first-heading-p))
20897 (not (org-at-table-p))))
20899 ;; Define the Org-mode menus
20900 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20901 '("Tbl"
20902 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20903 ["Next Field" org-cycle (org-at-table-p)]
20904 ["Previous Field" org-shifttab (org-at-table-p)]
20905 ["Next Row" org-return (org-at-table-p)]
20906 "--"
20907 ["Blank Field" org-table-blank-field (org-at-table-p)]
20908 ["Edit Field" org-table-edit-field (org-at-table-p)]
20909 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20910 "--"
20911 ("Column"
20912 ["Move Column Left" org-metaleft (org-at-table-p)]
20913 ["Move Column Right" org-metaright (org-at-table-p)]
20914 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20915 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20916 ("Row"
20917 ["Move Row Up" org-metaup (org-at-table-p)]
20918 ["Move Row Down" org-metadown (org-at-table-p)]
20919 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20920 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20921 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20922 "--"
20923 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20924 ("Rectangle"
20925 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20926 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20927 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20928 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20929 "--"
20930 ("Calculate"
20931 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20932 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20933 ["Edit Formulas" org-edit-special (org-at-table-p)]
20934 "--"
20935 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20936 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20937 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20938 "--"
20939 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20940 "--"
20941 ["Sum Column/Rectangle" org-table-sum
20942 (or (org-at-table-p) (org-region-active-p))]
20943 ["Which Column?" org-table-current-column (org-at-table-p)])
20944 ["Debug Formulas"
20945 org-table-toggle-formula-debugger
20946 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20947 ["Show Col/Row Numbers"
20948 org-table-toggle-coordinate-overlays
20949 :style toggle
20950 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20951 "--"
20952 ["Create" org-table-create (and (not (org-at-table-p))
20953 org-enable-table-editor)]
20954 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20955 ["Import from File" org-table-import (not (org-at-table-p))]
20956 ["Export to File" org-table-export (org-at-table-p)]
20957 "--"
20958 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20960 (easy-menu-define org-org-menu org-mode-map "Org menu"
20961 '("Org"
20962 ("Show/Hide"
20963 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20964 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20965 ["Sparse Tree..." org-sparse-tree t]
20966 ["Reveal Context" org-reveal t]
20967 ["Show All" show-all t]
20968 "--"
20969 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20970 "--"
20971 ["New Heading" org-insert-heading t]
20972 ("Navigate Headings"
20973 ["Up" outline-up-heading t]
20974 ["Next" outline-next-visible-heading t]
20975 ["Previous" outline-previous-visible-heading t]
20976 ["Next Same Level" outline-forward-same-level t]
20977 ["Previous Same Level" outline-backward-same-level t]
20978 "--"
20979 ["Jump" org-goto t])
20980 ("Edit Structure"
20981 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20982 "--"
20983 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20984 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20985 "--"
20986 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20987 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20988 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20989 "--"
20990 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20991 "--"
20992 ["Copy visible text" org-copy-visible t]
20993 "--"
20994 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20995 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20996 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20997 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20998 "--"
20999 ["Sort Region/Children" org-sort t]
21000 "--"
21001 ["Convert to odd levels" org-convert-to-odd-levels t]
21002 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21003 ("Editing"
21004 ["Emphasis..." org-emphasize t]
21005 ["Edit Source Example" org-edit-special t]
21006 "--"
21007 ["Footnote new/jump" org-footnote-action t]
21008 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21009 ("Archive"
21010 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21011 "--"
21012 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21013 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21014 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21016 "--"
21017 ("Hyperlinks"
21018 ["Store Link (Global)" org-store-link t]
21019 ["Find existing link to here" org-occur-link-in-agenda-files t]
21020 ["Insert Link" org-insert-link t]
21021 ["Follow Link" org-open-at-point t]
21022 "--"
21023 ["Next link" org-next-link t]
21024 ["Previous link" org-previous-link t]
21025 "--"
21026 ["Descriptive Links"
21027 org-toggle-link-display
21028 :style radio
21029 :selected org-descriptive-links
21031 ["Literal Links"
21032 org-toggle-link-display
21033 :style radio
21034 :selected (not org-descriptive-links)])
21035 "--"
21036 ("TODO Lists"
21037 ["TODO/DONE/-" org-todo t]
21038 ("Select keyword"
21039 ["Next keyword" org-shiftright (org-at-heading-p)]
21040 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21041 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21042 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21043 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21044 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21045 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21046 "--"
21047 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21048 :selected org-enforce-todo-dependencies :style toggle :active t]
21049 "Settings for tree at point"
21050 ["Do Children sequentially" org-toggle-ordered-property :style radio
21051 :selected (org-entry-get nil "ORDERED")
21052 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21053 ["Do Children parallel" org-toggle-ordered-property :style radio
21054 :selected (not (org-entry-get nil "ORDERED"))
21055 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21056 "--"
21057 ["Set Priority" org-priority t]
21058 ["Priority Up" org-shiftup t]
21059 ["Priority Down" org-shiftdown t]
21060 "--"
21061 ["Get news from all feeds" org-feed-update-all t]
21062 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21063 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21064 ("TAGS and Properties"
21065 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21066 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21067 "--"
21068 ["Set property" org-set-property (not (org-before-first-heading-p))]
21069 ["Column view of properties" org-columns t]
21070 ["Insert Column View DBlock" org-insert-columns-dblock t])
21071 ("Dates and Scheduling"
21072 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21073 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21074 ("Change Date"
21075 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21076 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21077 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21078 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21079 ["Compute Time Range" org-evaluate-time-range t]
21080 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21081 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21082 "--"
21083 ["Custom time format" org-toggle-time-stamp-overlays
21084 :style radio :selected org-display-custom-times]
21085 "--"
21086 ["Goto Calendar" org-goto-calendar t]
21087 ["Date from Calendar" org-date-from-calendar t]
21088 "--"
21089 ["Start/Restart Timer" org-timer-start t]
21090 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21091 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21092 ["Insert Timer String" org-timer t]
21093 ["Insert Timer Item" org-timer-item t])
21094 ("Logging work"
21095 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21096 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21097 ["Clock out" org-clock-out t]
21098 ["Clock cancel" org-clock-cancel t]
21099 "--"
21100 ["Mark as default task" org-clock-mark-default-task t]
21101 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21102 ["Goto running clock" org-clock-goto t]
21103 "--"
21104 ["Display times" org-clock-display t]
21105 ["Create clock table" org-clock-report t]
21106 "--"
21107 ["Record DONE time"
21108 (progn (setq org-log-done (not org-log-done))
21109 (message "Switching to %s will %s record a timestamp"
21110 (car org-done-keywords)
21111 (if org-log-done "automatically" "not")))
21112 :style toggle :selected org-log-done])
21113 "--"
21114 ["Agenda Command..." org-agenda t]
21115 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21116 ("File List for Agenda")
21117 ("Special views current file"
21118 ["TODO Tree" org-show-todo-tree t]
21119 ["Check Deadlines" org-check-deadlines t]
21120 ["Timeline" org-timeline t]
21121 ["Tags/Property tree" org-match-sparse-tree t])
21122 "--"
21123 ["Export/Publish..." org-export-dispatch t]
21124 ("LaTeX"
21125 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21126 :selected org-cdlatex-mode]
21127 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21128 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21129 ["Modify math symbol" org-cdlatex-math-modify
21130 (org-inside-LaTeX-fragment-p)]
21131 ["Insert citation" org-reftex-citation t]
21132 "--"
21133 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21134 "--"
21135 ("MobileOrg"
21136 ["Push Files and Views" org-mobile-push t]
21137 ["Get Captured and Flagged" org-mobile-pull t]
21138 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21139 "--"
21140 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21141 "--"
21142 ("Documentation"
21143 ["Show Version" org-version t]
21144 ["Info Documentation" org-info t])
21145 ("Customize"
21146 ["Browse Org Group" org-customize t]
21147 "--"
21148 ["Expand This Menu" org-create-customize-menu
21149 (fboundp 'customize-menu-create)])
21150 ["Send bug report" org-submit-bug-report t]
21151 "--"
21152 ("Refresh/Reload"
21153 ["Refresh setup current buffer" org-mode-restart t]
21154 ["Reload Org (after update)" org-reload t]
21155 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21158 (defun org-info (&optional node)
21159 "Read documentation for Org-mode in the info system.
21160 With optional NODE, go directly to that node."
21161 (interactive)
21162 (info (format "(org)%s" (or node ""))))
21164 ;;;###autoload
21165 (defun org-submit-bug-report ()
21166 "Submit a bug report on Org-mode via mail.
21168 Don't hesitate to report any problems or inaccurate documentation.
21170 If you don't have setup sending mail from (X)Emacs, please copy the
21171 output buffer into your mail program, as it gives us important
21172 information about your Org-mode version and configuration."
21173 (interactive)
21174 (require 'reporter)
21175 (org-load-modules-maybe)
21176 (org-require-autoloaded-modules)
21177 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21178 (reporter-submit-bug-report
21179 "emacs-orgmode@gnu.org"
21180 (org-version nil 'full)
21181 (let (list)
21182 (save-window-excursion
21183 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21184 (delete-other-windows)
21185 (erase-buffer)
21186 (insert "You are about to submit a bug report to the Org-mode mailing list.
21188 We would like to add your full Org-mode and Outline configuration to the
21189 bug report. This greatly simplifies the work of the maintainer and
21190 other experts on the mailing list.
21192 HOWEVER, some variables you have customized may contain private
21193 information. The names of customers, colleagues, or friends, might
21194 appear in the form of file names, tags, todo states, or search strings.
21195 If you answer yes to the prompt, you might want to check and remove
21196 such private information before sending the email.")
21197 (add-text-properties (point-min) (point-max) '(face org-warning))
21198 (when (yes-or-no-p "Include your Org-mode configuration ")
21199 (mapatoms
21200 (lambda (v)
21201 (and (boundp v)
21202 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21203 (or (and (symbol-value v)
21204 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21205 (and
21206 (get v 'custom-type) (get v 'standard-value)
21207 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21208 (push v list)))))
21209 (kill-buffer (get-buffer "*Warn about privacy*"))
21210 list))
21211 nil nil
21212 "Remember to cover the basics, that is, what you expected to happen and
21213 what in fact did happen. You don't know how to make a good report? See
21215 http://orgmode.org/manual/Feedback.html#Feedback
21217 Your bug report will be posted to the Org-mode mailing list.
21218 ------------------------------------------------------------------------")
21219 (save-excursion
21220 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21221 (replace-match "\\1Bug: \\3 [\\2]")))))
21224 (defun org-install-agenda-files-menu ()
21225 (let ((bl (buffer-list)))
21226 (save-excursion
21227 (while bl
21228 (set-buffer (pop bl))
21229 (if (derived-mode-p 'org-mode) (setq bl nil)))
21230 (when (derived-mode-p 'org-mode)
21231 (easy-menu-change
21232 '("Org") "File List for Agenda"
21233 (append
21234 (list
21235 ["Edit File List" (org-edit-agenda-file-list) t]
21236 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21237 ["Remove Current File from List" org-remove-file t]
21238 ["Cycle through agenda files" org-cycle-agenda-files t]
21239 ["Occur in all agenda files" org-occur-in-agenda-files t]
21240 "--")
21241 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21243 ;;;; Documentation
21245 (defun org-require-autoloaded-modules ()
21246 (interactive)
21247 (mapc 'require
21248 '(org-agenda org-archive org-attach org-clock org-colview org-id
21249 org-table org-timer)))
21251 ;;;###autoload
21252 (defun org-reload (&optional uncompiled)
21253 "Reload all org lisp files.
21254 With prefix arg UNCOMPILED, load the uncompiled versions."
21255 (interactive "P")
21256 (require 'loadhist)
21257 (let* ((org-dir (org-find-library-dir "org"))
21258 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21259 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21260 (remove-re (mapconcat 'identity
21261 (mapcar (lambda (f) (concat "^" f "$"))
21262 (list (if (featurep 'xemacs)
21263 "org-colview"
21264 "org-colview-xemacs")
21265 "org" "org-loaddefs" "org-version"))
21266 "\\|"))
21267 (feats (delete-dups
21268 (mapcar 'file-name-sans-extension
21269 (mapcar 'file-name-nondirectory
21270 (delq nil
21271 (mapcar 'feature-file
21272 features))))))
21273 (lfeat (append
21274 (sort
21275 (setq feats
21276 (delq nil (mapcar
21277 (lambda (f)
21278 (if (and (string-match feature-re f)
21279 (not (string-match remove-re f)))
21280 f nil))
21281 feats)))
21282 'string-lessp)
21283 (list "org-version" "org")))
21284 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21285 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21286 load-uncore load-misses)
21287 (setq load-misses
21288 (delq 't
21289 (mapcar (lambda (f)
21290 (or (org-load-noerror-mustsuffix (concat org-dir f))
21291 (and (string= org-dir contrib-dir)
21292 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21293 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21294 (add-to-list 'load-uncore f 'append)
21297 lfeat)))
21298 (if load-uncore
21299 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21300 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21301 (if load-misses
21302 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21303 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21304 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21306 ;;;###autoload
21307 (defun org-customize ()
21308 "Call the customize function with org as argument."
21309 (interactive)
21310 (org-load-modules-maybe)
21311 (org-require-autoloaded-modules)
21312 (customize-browse 'org))
21314 (defun org-create-customize-menu ()
21315 "Create a full customization menu for Org-mode, insert it into the menu."
21316 (interactive)
21317 (org-load-modules-maybe)
21318 (org-require-autoloaded-modules)
21319 (if (fboundp 'customize-menu-create)
21320 (progn
21321 (easy-menu-change
21322 '("Org") "Customize"
21323 `(["Browse Org group" org-customize t]
21324 "--"
21325 ,(customize-menu-create 'org)
21326 ["Set" Custom-set t]
21327 ["Save" Custom-save t]
21328 ["Reset to Current" Custom-reset-current t]
21329 ["Reset to Saved" Custom-reset-saved t]
21330 ["Reset to Standard Settings" Custom-reset-standard t]))
21331 (message "\"Org\"-menu now contains full customization menu"))
21332 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21334 ;;;; Miscellaneous stuff
21336 ;;; Generally useful functions
21338 (defun org-get-at-bol (property)
21339 "Get text property PROPERTY at beginning of line."
21340 (get-text-property (point-at-bol) property))
21342 (defun org-find-text-property-in-string (prop s)
21343 "Return the first non-nil value of property PROP in string S."
21344 (or (get-text-property 0 prop s)
21345 (get-text-property (or (next-single-property-change 0 prop s) 0)
21346 prop s)))
21348 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21349 "Display the given MESSAGE as a warning."
21350 (if (fboundp 'display-warning)
21351 (display-warning 'org message
21352 (if (featurep 'xemacs) 'warning :warning))
21353 (let ((buf (get-buffer-create "*Org warnings*")))
21354 (with-current-buffer buf
21355 (goto-char (point-max))
21356 (insert "Warning (Org): " message)
21357 (unless (bolp)
21358 (newline)))
21359 (display-buffer buf)
21360 (sit-for 0))))
21362 (defun org-eval (form)
21363 "Eval FORM and return result."
21364 (condition-case error
21365 (eval form)
21366 (error (format "%%![Error: %s]" error))))
21368 (defun org-in-clocktable-p ()
21369 "Check if the cursor is in a clocktable."
21370 (let ((pos (point)) start)
21371 (save-excursion
21372 (end-of-line 1)
21373 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21374 (setq start (match-beginning 0))
21375 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21376 (>= (match-end 0) pos)
21377 start))))
21379 (defun org-in-commented-line ()
21380 "Is point in a line starting with `#'?"
21381 (equal (char-after (point-at-bol)) ?#))
21383 (defun org-in-indented-comment-line ()
21384 "Is point in a line starting with `#' after some white space?"
21385 (save-excursion
21386 (save-match-data
21387 (goto-char (point-at-bol))
21388 (looking-at "[ \t]*#"))))
21390 (defun org-in-verbatim-emphasis ()
21391 (save-match-data
21392 (and (org-in-regexp org-emph-re 2)
21393 (>= (point) (match-beginning 3))
21394 (<= (point) (match-end 4))
21395 (member (match-string 3) '("=" "~")))))
21397 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21398 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21399 (if (and marker (marker-buffer marker)
21400 (buffer-live-p (marker-buffer marker)))
21401 (progn
21402 (org-pop-to-buffer-same-window (marker-buffer marker))
21403 (if (or (> marker (point-max)) (< marker (point-min)))
21404 (widen))
21405 (goto-char marker)
21406 (org-show-context 'org-goto))
21407 (if bookmark
21408 (bookmark-jump bookmark)
21409 (error "Cannot find location"))))
21411 (defun org-quote-csv-field (s)
21412 "Quote field for inclusion in CSV material."
21413 (if (string-match "[\",]" s)
21414 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21417 (defun org-force-self-insert (N)
21418 "Needed to enforce self-insert under remapping."
21419 (interactive "p")
21420 (self-insert-command N))
21422 (defun org-string-width (s)
21423 "Compute width of string, ignoring invisible characters.
21424 This ignores character with invisibility property `org-link', and also
21425 characters with property `org-cwidth', because these will become invisible
21426 upon the next fontification round."
21427 (let (b l)
21428 (when (or (eq t buffer-invisibility-spec)
21429 (assq 'org-link buffer-invisibility-spec))
21430 (while (setq b (text-property-any 0 (length s)
21431 'invisible 'org-link s))
21432 (setq s (concat (substring s 0 b)
21433 (substring s (or (next-single-property-change
21434 b 'invisible s) (length s)))))))
21435 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21436 (setq s (concat (substring s 0 b)
21437 (substring s (or (next-single-property-change
21438 b 'org-cwidth s) (length s))))))
21439 (setq l (string-width s) b -1)
21440 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21441 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21444 (defun org-shorten-string (s maxlength)
21445 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21446 If the string is shorter or has length MAXLENGTH, just return the
21447 original string. If it is longer, the functions finds a space in the
21448 string, breaks this string off at that locations and adds three dots
21449 as ellipsis. Including the ellipsis, the string will not be longer
21450 than MAXLENGTH. If finding a good breaking point in the string does
21451 not work, the string is just chopped off in the middle of a word
21452 if necessary."
21453 (if (<= (length s) maxlength)
21455 (let* ((n (max (- maxlength 4) 1))
21456 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21457 (if (string-match re s)
21458 (concat (match-string 1 s) "...")
21459 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21461 (defun org-get-indentation (&optional line)
21462 "Get the indentation of the current line, interpreting tabs.
21463 When LINE is given, assume it represents a line and compute its indentation."
21464 (if line
21465 (if (string-match "^ *" (org-remove-tabs line))
21466 (match-end 0))
21467 (save-excursion
21468 (beginning-of-line 1)
21469 (skip-chars-forward " \t")
21470 (current-column))))
21472 (defun org-get-string-indentation (s)
21473 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21474 (let ((n -1) (i 0) (w tab-width) c)
21475 (catch 'exit
21476 (while (< (setq n (1+ n)) (length s))
21477 (setq c (aref s n))
21478 (cond ((= c ?\ ) (setq i (1+ i)))
21479 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21480 (t (throw 'exit t)))))
21483 (defun org-remove-tabs (s &optional width)
21484 "Replace tabulators in S with spaces.
21485 Assumes that s is a single line, starting in column 0."
21486 (setq width (or width tab-width))
21487 (while (string-match "\t" s)
21488 (setq s (replace-match
21489 (make-string
21490 (- (* width (/ (+ (match-beginning 0) width) width))
21491 (match-beginning 0)) ?\ )
21492 t t s)))
21495 (defun org-fix-indentation (line ind)
21496 "Fix indentation in LINE.
21497 IND is a cons cell with target and minimum indentation.
21498 If the current indentation in LINE is smaller than the minimum,
21499 leave it alone. If it is larger than ind, set it to the target."
21500 (let* ((l (org-remove-tabs line))
21501 (i (org-get-indentation l))
21502 (i1 (car ind)) (i2 (cdr ind)))
21503 (if (>= i i2) (setq l (substring line i2)))
21504 (if (> i1 0)
21505 (concat (make-string i1 ?\ ) l)
21506 l)))
21508 (defun org-remove-indentation (code &optional n)
21509 "Remove the maximum common indentation from the lines in CODE.
21510 N may optionally be the number of spaces to remove."
21511 (with-temp-buffer
21512 (insert code)
21513 (org-do-remove-indentation n)
21514 (buffer-string)))
21516 (defun org-do-remove-indentation (&optional n)
21517 "Remove the maximum common indentation from the buffer."
21518 (untabify (point-min) (point-max))
21519 (let ((min 10000) re)
21520 (if n
21521 (setq min n)
21522 (goto-char (point-min))
21523 (while (re-search-forward "^ *[^ \n]" nil t)
21524 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21525 (unless (or (= min 0) (= min 10000))
21526 (setq re (format "^ \\{%d\\}" min))
21527 (goto-char (point-min))
21528 (while (re-search-forward re nil t)
21529 (replace-match "")
21530 (end-of-line 1))
21531 min)))
21533 (defun org-fill-template (template alist)
21534 "Find each %key of ALIST in TEMPLATE and replace it."
21535 (let ((case-fold-search nil)
21536 entry key value)
21537 (setq alist (sort (copy-sequence alist)
21538 (lambda (a b) (< (length (car a)) (length (car b))))))
21539 (while (setq entry (pop alist))
21540 (setq template
21541 (replace-regexp-in-string
21542 (concat "%" (regexp-quote (car entry)))
21543 (or (cdr entry) "") template t t)))
21544 template))
21546 (defun org-base-buffer (buffer)
21547 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21548 (if (not buffer)
21549 buffer
21550 (or (buffer-base-buffer buffer)
21551 buffer)))
21553 (defun org-trim (s)
21554 "Remove whitespace at beginning and end of string."
21555 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21556 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21559 (defun org-wrap (string &optional width lines)
21560 "Wrap string to either a number of lines, or a width in characters.
21561 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21562 that costs. If there is a word longer than WIDTH, the text is actually
21563 wrapped to the length of that word.
21564 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21565 many lines, whatever width that takes.
21566 The return value is a list of lines, without newlines at the end."
21567 (let* ((words (org-split-string string "[ \t\n]+"))
21568 (maxword (apply 'max (mapcar 'org-string-width words)))
21569 w ll)
21570 (cond (width
21571 (org-do-wrap words (max maxword width)))
21572 (lines
21573 (setq w maxword)
21574 (setq ll (org-do-wrap words maxword))
21575 (if (<= (length ll) lines)
21577 (setq ll words)
21578 (while (> (length ll) lines)
21579 (setq w (1+ w))
21580 (setq ll (org-do-wrap words w)))
21581 ll))
21582 (t (error "Cannot wrap this")))))
21584 (defun org-do-wrap (words width)
21585 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21586 (let (lines line)
21587 (while words
21588 (setq line (pop words))
21589 (while (and words (< (+ (length line) (length (car words))) width))
21590 (setq line (concat line " " (pop words))))
21591 (setq lines (push line lines)))
21592 (nreverse lines)))
21594 (defun org-split-string (string &optional separators)
21595 "Splits STRING into substrings at SEPARATORS.
21596 No empty strings are returned if there are matches at the beginning
21597 and end of string."
21598 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21599 (start 0)
21600 notfirst
21601 (list nil))
21602 (while (and (string-match rexp string
21603 (if (and notfirst
21604 (= start (match-beginning 0))
21605 (< start (length string)))
21606 (1+ start) start))
21607 (< (match-beginning 0) (length string)))
21608 (setq notfirst t)
21609 (or (eq (match-beginning 0) 0)
21610 (and (eq (match-beginning 0) (match-end 0))
21611 (eq (match-beginning 0) start))
21612 (setq list
21613 (cons (substring string start (match-beginning 0))
21614 list)))
21615 (setq start (match-end 0)))
21616 (or (eq start (length string))
21617 (setq list
21618 (cons (substring string start)
21619 list)))
21620 (nreverse list)))
21622 (defun org-quote-vert (s)
21623 "Replace \"|\" with \"\\vert\"."
21624 (while (string-match "|" s)
21625 (setq s (replace-match "\\vert" t t s)))
21628 (defun org-uuidgen-p (s)
21629 "Is S an ID created by UUIDGEN?"
21630 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21632 (defun org-in-src-block-p (&optional inside)
21633 "Whether point is in a code source block.
21634 When INSIDE is non-nil, don't consider we are within a src block
21635 when point is at #+BEGIN_SRC or #+END_SRC."
21636 (let ((case-fold-search t) ov)
21637 (or (and (setq ov (overlays-at (point)))
21638 (memq 'org-block-background
21639 (overlay-properties (car ov))))
21640 (and (not inside)
21641 (save-match-data
21642 (save-excursion
21643 (beginning-of-line)
21644 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21646 (defun org-context ()
21647 "Return a list of contexts of the current cursor position.
21648 If several contexts apply, all are returned.
21649 Each context entry is a list with a symbol naming the context, and
21650 two positions indicating start and end of the context. Possible
21651 contexts are:
21653 :headline anywhere in a headline
21654 :headline-stars on the leading stars in a headline
21655 :todo-keyword on a TODO keyword (including DONE) in a headline
21656 :tags on the TAGS in a headline
21657 :priority on the priority cookie in a headline
21658 :item on the first line of a plain list item
21659 :item-bullet on the bullet/number of a plain list item
21660 :checkbox on the checkbox in a plain list item
21661 :table in an org-mode table
21662 :table-special on a special filed in a table
21663 :table-table in a table.el table
21664 :clocktable in a clocktable
21665 :src-block in a source block
21666 :link on a hyperlink
21667 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21668 :target on a <<target>>
21669 :radio-target on a <<<radio-target>>>
21670 :latex-fragment on a LaTeX fragment
21671 :latex-preview on a LaTeX fragment with overlaid preview image
21673 This function expects the position to be visible because it uses font-lock
21674 faces as a help to recognize the following contexts: :table-special, :link,
21675 and :keyword."
21676 (let* ((f (get-text-property (point) 'face))
21677 (faces (if (listp f) f (list f)))
21678 (case-fold-search t)
21679 (p (point)) clist o)
21680 ;; First the large context
21681 (cond
21682 ((org-at-heading-p t)
21683 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21684 (when (progn
21685 (beginning-of-line 1)
21686 (looking-at org-todo-line-tags-regexp))
21687 (push (org-point-in-group p 1 :headline-stars) clist)
21688 (push (org-point-in-group p 2 :todo-keyword) clist)
21689 (push (org-point-in-group p 4 :tags) clist))
21690 (goto-char p)
21691 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21692 (if (looking-at "\\[#[A-Z0-9]\\]")
21693 (push (org-point-in-group p 0 :priority) clist)))
21695 ((org-at-item-p)
21696 (push (org-point-in-group p 2 :item-bullet) clist)
21697 (push (list :item (point-at-bol)
21698 (save-excursion (org-end-of-item) (point)))
21699 clist)
21700 (and (org-at-item-checkbox-p)
21701 (push (org-point-in-group p 0 :checkbox) clist)))
21703 ((org-at-table-p)
21704 (push (list :table (org-table-begin) (org-table-end)) clist)
21705 (if (memq 'org-formula faces)
21706 (push (list :table-special
21707 (previous-single-property-change p 'face)
21708 (next-single-property-change p 'face)) clist)))
21709 ((org-at-table-p 'any)
21710 (push (list :table-table) clist)))
21711 (goto-char p)
21713 (let ((case-fold-search t))
21714 ;; New the "medium" contexts: clocktables, source blocks
21715 (cond ((org-in-clocktable-p)
21716 (push (list :clocktable
21717 (and (or (looking-at "#\\+BEGIN: clocktable")
21718 (search-backward "#+BEGIN: clocktable" nil t))
21719 (match-beginning 0))
21720 (and (re-search-forward "#\\+END:?" nil t)
21721 (match-end 0))) clist))
21722 ((org-in-src-block-p)
21723 (push (list :src-block
21724 (and (or (looking-at "#\\+BEGIN_SRC")
21725 (search-backward "#+BEGIN_SRC" nil t))
21726 (match-beginning 0))
21727 (and (search-forward "#+END_SRC" nil t)
21728 (match-beginning 0))) clist))))
21729 (goto-char p)
21731 ;; Now the small context
21732 (cond
21733 ((org-at-timestamp-p)
21734 (push (org-point-in-group p 0 :timestamp) clist))
21735 ((memq 'org-link faces)
21736 (push (list :link
21737 (previous-single-property-change p 'face)
21738 (next-single-property-change p 'face)) clist))
21739 ((memq 'org-special-keyword faces)
21740 (push (list :keyword
21741 (previous-single-property-change p 'face)
21742 (next-single-property-change p 'face)) clist))
21743 ((org-at-target-p)
21744 (push (org-point-in-group p 0 :target) clist)
21745 (goto-char (1- (match-beginning 0)))
21746 (if (looking-at org-radio-target-regexp)
21747 (push (org-point-in-group p 0 :radio-target) clist))
21748 (goto-char p))
21749 ((setq o (car (delq nil
21750 (mapcar
21751 (lambda (x)
21752 (if (memq x org-latex-fragment-image-overlays) x))
21753 (overlays-at (point))))))
21754 (push (list :latex-fragment
21755 (overlay-start o) (overlay-end o)) clist)
21756 (push (list :latex-preview
21757 (overlay-start o) (overlay-end o)) clist))
21758 ((org-inside-LaTeX-fragment-p)
21759 ;; FIXME: positions wrong.
21760 (push (list :latex-fragment (point) (point)) clist)))
21762 (setq clist (nreverse (delq nil clist)))
21763 clist))
21765 ;; FIXME: Compare with at-regexp-p Do we need both?
21766 (defun org-in-regexp (re &optional nlines visually)
21767 "Check if point is inside a match of regexp.
21768 Normally only the current line is checked, but you can include NLINES extra
21769 lines both before and after point into the search.
21770 If VISUALLY is set, require that the cursor is not after the match but
21771 really on, so that the block visually is on the match."
21772 (catch 'exit
21773 (let ((pos (point))
21774 (eol (point-at-eol (+ 1 (or nlines 0))))
21775 (inc (if visually 1 0)))
21776 (save-excursion
21777 (beginning-of-line (- 1 (or nlines 0)))
21778 (while (re-search-forward re eol t)
21779 (if (and (<= (match-beginning 0) pos)
21780 (>= (+ inc (match-end 0)) pos))
21781 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21783 (defun org-at-regexp-p (regexp)
21784 "Is point inside a match of REGEXP in the current line?"
21785 (catch 'exit
21786 (save-excursion
21787 (let ((pos (point)) (end (point-at-eol)))
21788 (beginning-of-line 1)
21789 (while (re-search-forward regexp end t)
21790 (if (and (<= (match-beginning 0) pos)
21791 (>= (match-end 0) pos))
21792 (throw 'exit t)))
21793 nil))))
21795 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21796 "Non-nil when point is between matches of START-RE and END-RE.
21798 Also return a non-nil value when point is on one of the matches.
21800 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21801 buffer positions. Default values are the positions of headlines
21802 surrounding the point.
21804 The functions returns a cons cell whose car (resp. cdr) is the
21805 position before START-RE (resp. after END-RE)."
21806 (save-match-data
21807 (let ((pos (point))
21808 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21809 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21810 beg end)
21811 (save-excursion
21812 ;; Point is on a block when on START-RE or if START-RE can be
21813 ;; found before it...
21814 (and (or (org-at-regexp-p start-re)
21815 (re-search-backward start-re limit-up t))
21816 (setq beg (match-beginning 0))
21817 ;; ... and END-RE after it...
21818 (goto-char (match-end 0))
21819 (re-search-forward end-re limit-down t)
21820 (> (setq end (match-end 0)) pos)
21821 ;; ... without another START-RE in-between.
21822 (goto-char (match-beginning 0))
21823 (not (re-search-backward start-re (1+ beg) t))
21824 ;; Return value.
21825 (cons beg end))))))
21827 (defun org-in-block-p (names)
21828 "Non-nil when point belongs to a block whose name belongs to NAMES.
21830 NAMES is a list of strings containing names of blocks.
21832 Return first block name matched, or nil. Beware that in case of
21833 nested blocks, the returned name may not belong to the closest
21834 block from point."
21835 (save-match-data
21836 (catch 'exit
21837 (let ((case-fold-search t)
21838 (lim-up (save-excursion (outline-previous-heading)))
21839 (lim-down (save-excursion (outline-next-heading))))
21840 (mapc (lambda (name)
21841 (let ((n (regexp-quote name)))
21842 (when (org-between-regexps-p
21843 (concat "^[ \t]*#\\+begin_" n)
21844 (concat "^[ \t]*#\\+end_" n)
21845 lim-up lim-down)
21846 (throw 'exit n))))
21847 names))
21848 nil)))
21850 (defun org-in-drawer-p ()
21851 "Non-nil if point is within a drawer.
21852 If point is within a drawer, return it, as parsed data."
21853 (let ((element (save-match-data (org-element-at-point))))
21854 (while (and element (not (memq (org-element-type element)
21855 '(drawer property-drawer))))
21856 (setq element (org-element-property :parent element)))
21857 element))
21859 (defun org-occur-in-agenda-files (regexp &optional nlines)
21860 "Call `multi-occur' with buffers for all agenda files."
21861 (interactive "sOrg-files matching: \np")
21862 (let* ((files (org-agenda-files))
21863 (tnames (mapcar 'file-truename files))
21864 (extra org-agenda-text-search-extra-files)
21866 (when (eq (car extra) 'agenda-archives)
21867 (setq extra (cdr extra))
21868 (setq files (org-add-archive-files files)))
21869 (while (setq f (pop extra))
21870 (unless (member (file-truename f) tnames)
21871 (add-to-list 'files f 'append)
21872 (add-to-list 'tnames (file-truename f) 'append)))
21873 (multi-occur
21874 (mapcar (lambda (x)
21875 (with-current-buffer
21876 (or (get-file-buffer x) (find-file-noselect x))
21877 (widen)
21878 (current-buffer)))
21879 files)
21880 regexp)))
21882 (if (boundp 'occur-mode-find-occurrence-hook)
21883 ;; Emacs 23
21884 (add-hook 'occur-mode-find-occurrence-hook
21885 (lambda ()
21886 (when (derived-mode-p 'org-mode)
21887 (org-reveal))))
21888 ;; Emacs 22
21889 (defadvice occur-mode-goto-occurrence
21890 (after org-occur-reveal activate)
21891 (and (derived-mode-p 'org-mode) (org-reveal)))
21892 (defadvice occur-mode-goto-occurrence-other-window
21893 (after org-occur-reveal activate)
21894 (and (derived-mode-p 'org-mode) (org-reveal)))
21895 (defadvice occur-mode-display-occurrence
21896 (after org-occur-reveal activate)
21897 (when (derived-mode-p 'org-mode)
21898 (let ((pos (occur-mode-find-occurrence)))
21899 (with-current-buffer (marker-buffer pos)
21900 (save-excursion
21901 (goto-char pos)
21902 (org-reveal)))))))
21904 (defun org-occur-link-in-agenda-files ()
21905 "Create a link and search for it in the agendas.
21906 The link is not stored in `org-stored-links', it is just created
21907 for the search purpose."
21908 (interactive)
21909 (let ((link (condition-case nil
21910 (org-store-link nil)
21911 (error "Unable to create a link to here"))))
21912 (org-occur-in-agenda-files (regexp-quote link))))
21914 (defun org-reverse-string (string)
21915 "Return the reverse of STRING."
21916 (apply 'string (reverse (string-to-list string))))
21918 (defun org-uniquify-alist (alist)
21919 "Merge elements of ALIST with the same key.
21921 For example, in this alist:
21923 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21924 => '((a 1 3) (b 2))
21926 merge (a 1) and (a 3) into (a 1 3).
21928 The function returns the new ALIST."
21929 (let (rtn)
21930 (mapc
21931 (lambda (e)
21932 (let (n)
21933 (if (not (assoc (car e) rtn))
21934 (push e rtn)
21935 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21936 (setq rtn (assq-delete-all (car e) rtn))
21937 (push n rtn))))
21938 alist)
21939 rtn))
21941 (defun org-delete-all (elts list)
21942 "Remove all elements in ELTS from LIST."
21943 (while elts
21944 (setq list (delete (pop elts) list)))
21945 list)
21947 (defun org-count (cl-item cl-seq)
21948 "Count the number of occurrences of ITEM in SEQ.
21949 Taken from `count' in cl-seq.el with all keyword arguments removed."
21950 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21951 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21952 (while (< cl-start cl-end)
21953 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21954 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21955 (setq cl-start (1+ cl-start)))
21956 cl-count))
21958 (defun org-remove-if (predicate seq)
21959 "Remove everything from SEQ that fulfills PREDICATE."
21960 (let (res e)
21961 (while seq
21962 (setq e (pop seq))
21963 (if (not (funcall predicate e)) (push e res)))
21964 (nreverse res)))
21966 (defun org-remove-if-not (predicate seq)
21967 "Remove everything from SEQ that does not fulfill PREDICATE."
21968 (let (res e)
21969 (while seq
21970 (setq e (pop seq))
21971 (if (funcall predicate e) (push e res)))
21972 (nreverse res)))
21974 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21975 "Reduce two-argument FUNCTION across SEQ.
21976 Taken from `reduce' in cl-seq.el with all keyword arguments but
21977 \":initial-value\" removed."
21978 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21979 (cadr (memq :initial-value cl-keys)))
21980 (cl-seq (pop cl-seq))
21981 (t (funcall cl-func)))))
21982 (while cl-seq
21983 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21984 cl-accum))
21986 (defun org-every (pred seq)
21987 "Return true if PREDICATE is true of every element of SEQ.
21988 Adapted from `every' in cl.el."
21989 (catch 'org-every
21990 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21993 (defun org-some (pred seq)
21994 "Return true if PREDICATE is true of any element of SEQ.
21995 Adapted from `some' in cl.el."
21996 (catch 'org-some
21997 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21998 nil))
22000 (defun org-back-over-empty-lines ()
22001 "Move backwards over whitespace, to the beginning of the first empty line.
22002 Returns the number of empty lines passed."
22003 (let ((pos (point)))
22004 (if (cdr (assoc 'heading org-blank-before-new-entry))
22005 (skip-chars-backward " \t\n\r")
22006 (unless (eobp)
22007 (forward-line -1)))
22008 (beginning-of-line 2)
22009 (goto-char (min (point) pos))
22010 (count-lines (point) pos)))
22012 (defun org-skip-whitespace ()
22013 (skip-chars-forward " \t\n\r"))
22015 (defun org-point-in-group (point group &optional context)
22016 "Check if POINT is in match-group GROUP.
22017 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22018 match. If the match group does not exist or point is not inside it,
22019 return nil."
22020 (and (match-beginning group)
22021 (>= point (match-beginning group))
22022 (<= point (match-end group))
22023 (if context
22024 (list context (match-beginning group) (match-end group))
22025 t)))
22027 (defun org-switch-to-buffer-other-window (&rest args)
22028 "Switch to buffer in a second window on the current frame.
22029 In particular, do not allow pop-up frames.
22030 Returns the newly created buffer."
22031 (org-no-popups
22032 (apply 'switch-to-buffer-other-window args)))
22034 (defun org-combine-plists (&rest plists)
22035 "Create a single property list from all plists in PLISTS.
22036 The process starts by copying the first list, and then setting properties
22037 from the other lists. Settings in the last list are the most significant
22038 ones and overrule settings in the other lists."
22039 (let ((rtn (copy-sequence (pop plists)))
22040 p v ls)
22041 (while plists
22042 (setq ls (pop plists))
22043 (while ls
22044 (setq p (pop ls) v (pop ls))
22045 (setq rtn (plist-put rtn p v))))
22046 rtn))
22048 (defun org-replace-escapes (string table)
22049 "Replace %-escapes in STRING with values in TABLE.
22050 TABLE is an association list with keys like \"%a\" and string values.
22051 The sequences in STRING may contain normal field width and padding information,
22052 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22053 so values can contain further %-escapes if they are define later in TABLE."
22054 (let ((tbl (copy-alist table))
22055 (case-fold-search nil)
22056 (pchg 0)
22057 e re rpl)
22058 (while (setq e (pop tbl))
22059 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22060 (when (and (cdr e) (string-match re (cdr e)))
22061 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22062 (safe "SREF"))
22063 (add-text-properties 0 3 (list 'sref sref) safe)
22064 (setcdr e (replace-match safe t t (cdr e)))))
22065 (while (string-match re string)
22066 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22067 (cdr e)))
22068 (setq string (replace-match rpl t t string))))
22069 (while (setq pchg (next-property-change pchg string))
22070 (let ((sref (get-text-property pchg 'sref string)))
22071 (when (and sref (string-match "SREF" string pchg))
22072 (setq string (replace-match sref t t string)))))
22073 string))
22075 (defun org-sublist (list start end)
22076 "Return a section of LIST, from START to END.
22077 Counting starts at 1."
22078 (let (rtn (c start))
22079 (setq list (nthcdr (1- start) list))
22080 (while (and list (<= c end))
22081 (push (pop list) rtn)
22082 (setq c (1+ c)))
22083 (nreverse rtn)))
22085 (defun org-find-base-buffer-visiting (file)
22086 "Like `find-buffer-visiting' but always return the base buffer and
22087 not an indirect buffer."
22088 (let ((buf (or (get-file-buffer file)
22089 (find-buffer-visiting file))))
22090 (if buf
22091 (or (buffer-base-buffer buf) buf)
22092 nil)))
22094 (defun org-image-file-name-regexp (&optional extensions)
22095 "Return regexp matching the file names of images.
22096 If EXTENSIONS is given, only match these."
22097 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22098 (image-file-name-regexp)
22099 (let ((image-file-name-extensions
22100 (or extensions
22101 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22102 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22103 (concat "\\."
22104 (regexp-opt (nconc (mapcar 'upcase
22105 image-file-name-extensions)
22106 image-file-name-extensions)
22108 "\\'"))))
22110 (defun org-file-image-p (file &optional extensions)
22111 "Return non-nil if FILE is an image."
22112 (save-match-data
22113 (string-match (org-image-file-name-regexp extensions) file)))
22115 (defun org-get-cursor-date (&optional with-time)
22116 "Return the date at cursor in as a time.
22117 This works in the calendar and in the agenda, anywhere else it just
22118 returns the current time.
22119 If WITH-TIME is non-nil, returns the time of the event at point (in
22120 the agenda) or the current time of the day."
22121 (let (date day defd tp tm hod mod)
22122 (when with-time
22123 (setq tp (get-text-property (point) 'time))
22124 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22125 (setq hod (string-to-number (match-string 1 tp))
22126 mod (string-to-number (match-string 2 tp))))
22127 (or tp (setq hod (nth 2 (decode-time (current-time)))
22128 mod (nth 1 (decode-time (current-time))))))
22129 (cond
22130 ((eq major-mode 'calendar-mode)
22131 (setq date (calendar-cursor-to-date)
22132 defd (encode-time 0 (or mod 0) (or hod 0)
22133 (nth 1 date) (nth 0 date) (nth 2 date))))
22134 ((eq major-mode 'org-agenda-mode)
22135 (setq day (get-text-property (point) 'day))
22136 (if day
22137 (setq date (calendar-gregorian-from-absolute day)
22138 defd (encode-time 0 (or mod 0) (or hod 0)
22139 (nth 1 date) (nth 0 date) (nth 2 date))))))
22140 (or defd (current-time))))
22142 (defun org-mark-subtree (&optional up)
22143 "Mark the current subtree.
22144 This puts point at the start of the current subtree, and mark at
22145 the end. If a numeric prefix UP is given, move up into the
22146 hierarchy of headlines by UP levels before marking the subtree."
22147 (interactive "P")
22148 (org-with-limited-levels
22149 (cond ((org-at-heading-p) (beginning-of-line))
22150 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22151 (t (outline-previous-visible-heading 1))))
22152 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22153 (if (org-called-interactively-p 'any)
22154 (call-interactively 'org-mark-element)
22155 (org-mark-element)))
22158 ;;; Indentation
22160 (defun org-indent-line ()
22161 "Indent line depending on context."
22162 (interactive)
22163 (let* ((pos (point))
22164 (itemp (org-at-item-p))
22165 (case-fold-search t)
22166 (org-drawer-regexp (or org-drawer-regexp "\000"))
22167 (inline-task-p (and (featurep 'org-inlinetask)
22168 (org-inlinetask-in-task-p)))
22169 (inline-re (and inline-task-p
22170 (org-inlinetask-outline-regexp)))
22171 column)
22172 (if (and orgstruct-is-++ (eq pos (point)))
22173 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22174 (indent-according-to-mode))
22175 (beginning-of-line 1)
22176 (cond
22177 ;; Headings
22178 ((looking-at org-outline-regexp) (setq column 0))
22179 ;; Footnote definition
22180 ((looking-at org-footnote-definition-re) (setq column 0))
22181 ;; Literal examples
22182 ((looking-at "[ \t]*:\\( \\|$\\)")
22183 (setq column (org-get-indentation))) ; do nothing
22184 ;; Lists
22185 ((ignore-errors (goto-char (org-in-item-p)))
22186 (setq column (if itemp
22187 (org-get-indentation)
22188 (org-list-item-body-column (point))))
22189 (goto-char pos))
22190 ;; Drawers
22191 ((and (looking-at "[ \t]*:END:")
22192 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22193 (save-excursion
22194 (goto-char (1- (match-beginning 1)))
22195 (setq column (current-column))))
22196 ;; Special blocks
22197 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22198 (save-excursion
22199 (re-search-backward
22200 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22201 (setq column (org-get-indentation (match-string 0))))
22202 ((and (not (looking-at "[ \t]*#\\+begin_"))
22203 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22204 (save-excursion
22205 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22206 (setq column
22207 (cond ((equal (downcase (match-string 1)) "src")
22208 ;; src blocks: let `org-edit-src-exit' handle them
22209 (org-get-indentation))
22210 ((equal (downcase (match-string 1)) "example")
22211 (max (org-get-indentation)
22212 (org-get-indentation (match-string 0))))
22214 (org-get-indentation (match-string 0))))))
22215 ;; This line has nothing special, look at the previous relevant
22216 ;; line to compute indentation
22218 (beginning-of-line 0)
22219 (while (and (not (bobp))
22220 (not (looking-at org-table-line-regexp))
22221 (not (looking-at org-drawer-regexp))
22222 ;; When point started in an inline task, do not move
22223 ;; above task starting line.
22224 (not (and inline-task-p (looking-at inline-re)))
22225 ;; Skip drawers, blocks, empty lines, verbatim,
22226 ;; comments, tables, footnotes definitions, lists,
22227 ;; inline tasks.
22228 (or (and (looking-at "[ \t]*:END:")
22229 (re-search-backward org-drawer-regexp nil t))
22230 (and (looking-at "[ \t]*#\\+end_")
22231 (re-search-backward "[ \t]*#\\+begin_"nil t))
22232 (looking-at "[ \t]*[\n:#|]")
22233 (looking-at org-footnote-definition-re)
22234 (and (not inline-task-p)
22235 (featurep 'org-inlinetask)
22236 (org-inlinetask-in-task-p)
22237 (or (org-inlinetask-goto-beginning) t))))
22238 (beginning-of-line 0))
22239 (cond
22240 ;; There was a list item above.
22241 ((ignore-errors (goto-char (org-in-item-p)))
22242 (goto-char (org-list-get-top-point (org-list-struct)))
22243 (setq column (org-get-indentation)))
22244 ;; There was an heading above.
22245 ((looking-at "\\*+[ \t]+")
22246 (if (not org-adapt-indentation)
22247 (setq column 0)
22248 (goto-char (match-end 0))
22249 (setq column (current-column))))
22250 ;; A drawer had started and is unfinished
22251 ((looking-at org-drawer-regexp)
22252 (goto-char (1- (match-beginning 1)))
22253 (setq column (current-column)))
22254 ;; Else, nothing noticeable found: get indentation and go on.
22255 (t (setq column (org-get-indentation))))))
22256 ;; Now apply indentation and move cursor accordingly
22257 (goto-char pos)
22258 (if (<= (current-column) (current-indentation))
22259 (org-indent-line-to column)
22260 (save-excursion (org-indent-line-to column)))
22261 ;; Special polishing for properties, see `org-property-format'
22262 (setq column (current-column))
22263 (beginning-of-line 1)
22264 (if (looking-at org-property-re)
22265 (replace-match (concat (match-string 4)
22266 (format org-property-format
22267 (match-string 1) (match-string 3)))
22268 t t))
22269 (org-move-to-column column))))
22271 (defun org-indent-drawer ()
22272 "Indent the drawer at point."
22273 (interactive)
22274 (let ((p (point))
22275 (e (and (save-excursion (re-search-forward ":END:" nil t))
22276 (match-end 0)))
22277 (folded
22278 (save-excursion
22279 (end-of-line)
22280 (when (overlays-at (point))
22281 (member 'invisible (overlay-properties
22282 (car (overlays-at (point)))))))))
22283 (when folded (org-cycle))
22284 (indent-for-tab-command)
22285 (while (and (move-beginning-of-line 2) (< (point) e))
22286 (indent-for-tab-command))
22287 (goto-char p)
22288 (when folded (org-cycle)))
22289 (message "Drawer at point indented"))
22291 (defun org-indent-block ()
22292 "Indent the block at point."
22293 (interactive)
22294 (let ((p (point))
22295 (case-fold-search t)
22296 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22297 (match-end 0)))
22298 (folded
22299 (save-excursion
22300 (end-of-line)
22301 (when (overlays-at (point))
22302 (member 'invisible (overlay-properties
22303 (car (overlays-at (point)))))))))
22304 (when folded (org-cycle))
22305 (indent-for-tab-command)
22306 (while (and (move-beginning-of-line 2) (< (point) e))
22307 (indent-for-tab-command))
22308 (goto-char p)
22309 (when folded (org-cycle)))
22310 (message "Block at point indented"))
22312 (defun org-indent-region (start end)
22313 "Indent region."
22314 (interactive "r")
22315 (save-excursion
22316 (let ((line-end (org-current-line end)))
22317 (goto-char start)
22318 (while (< (org-current-line) line-end)
22319 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22320 (t (call-interactively 'org-indent-line)))
22321 (move-beginning-of-line 2)))))
22324 ;;; Filling
22326 ;; We use our own fill-paragraph and auto-fill functions.
22328 ;; `org-fill-paragraph' relies on adaptive filling and context
22329 ;; checking. Appropriate `fill-prefix' is computed with
22330 ;; `org-adaptive-fill-function'.
22332 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22333 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22334 ;; `org-adaptive-fill-function' value. Internally,
22335 ;; `org-comment-line-break-function' breaks the line.
22337 ;; `org-setup-filling' installs filling and auto-filling related
22338 ;; variables during `org-mode' initialization.
22340 (defvar org-element-paragraph-separate) ; org-element.el
22341 (defun org-setup-filling ()
22342 (require 'org-element)
22343 ;; Prevent auto-fill from inserting unwanted new items.
22344 (when (boundp 'fill-nobreak-predicate)
22345 (org-set-local
22346 'fill-nobreak-predicate
22347 (org-uniquify
22348 (append fill-nobreak-predicate
22349 '(org-fill-line-break-nobreak-p
22350 org-fill-paragraph-with-timestamp-nobreak-p)))))
22351 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22352 (org-set-local 'paragraph-start paragraph-ending)
22353 (org-set-local 'paragraph-separate paragraph-ending))
22354 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22355 (org-set-local 'auto-fill-inhibit-regexp nil)
22356 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22357 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22358 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22360 (defun org-fill-line-break-nobreak-p ()
22361 "Non-nil when a new line at point would create an Org line break."
22362 (save-excursion
22363 (skip-chars-backward "[ \t]")
22364 (skip-chars-backward "\\\\")
22365 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22367 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22368 "Non-nil when a new line at point would split a timestamp."
22369 (and (org-at-timestamp-p t)
22370 (not (looking-at org-ts-regexp-both))))
22372 (declare-function message-in-body-p "message" ())
22373 (defvar orgtbl-line-start-regexp) ; From org-table.el
22374 (defun org-adaptive-fill-function ()
22375 "Compute a fill prefix for the current line.
22376 Return fill prefix, as a string, or nil if current line isn't
22377 meant to be filled. For convenience, if `adaptive-fill-regexp'
22378 matches in paragraphs or comments, use it."
22379 (catch 'exit
22380 (when (derived-mode-p 'message-mode)
22381 (save-excursion
22382 (beginning-of-line)
22383 (cond ((or (not (message-in-body-p))
22384 (looking-at orgtbl-line-start-regexp))
22385 (throw 'exit nil))
22386 ((looking-at message-cite-prefix-regexp)
22387 (throw 'exit (match-string-no-properties 0)))
22388 ((looking-at org-outline-regexp)
22389 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22390 (org-with-wide-buffer
22391 (let* ((p (line-beginning-position))
22392 (element (save-excursion
22393 (beginning-of-line)
22394 (or (ignore-errors (org-element-at-point))
22395 (user-error "An element cannot be parsed line %d"
22396 (line-number-at-pos (point))))))
22397 (type (org-element-type element))
22398 (post-affiliated (org-element-property :post-affiliated element)))
22399 (unless (and post-affiliated (< p post-affiliated))
22400 (case type
22401 (comment
22402 (save-excursion
22403 (beginning-of-line)
22404 (looking-at "[ \t]*")
22405 (concat (match-string 0) "# ")))
22406 (footnote-definition "")
22407 ((item plain-list)
22408 (make-string (org-list-item-body-column
22409 (or post-affiliated
22410 (org-element-property :begin element)))
22411 ? ))
22412 (paragraph
22413 ;; Fill prefix is usually the same as the current line,
22414 ;; unless the paragraph is at the beginning of an item.
22415 (let ((parent (org-element-property :parent element)))
22416 (save-excursion
22417 (beginning-of-line)
22418 (cond ((eq (org-element-type parent) 'item)
22419 (make-string (org-list-item-body-column
22420 (org-element-property :begin parent))
22421 ? ))
22422 ((and adaptive-fill-regexp
22423 ;; Locally disable
22424 ;; `adaptive-fill-function' to let
22425 ;; `fill-context-prefix' handle
22426 ;; `adaptive-fill-regexp' variable.
22427 (let (adaptive-fill-function)
22428 (fill-context-prefix
22429 post-affiliated
22430 (org-element-property :end element)))))
22431 ((looking-at "[ \t]+") (match-string 0))
22432 (t "")))))
22433 (comment-block
22434 ;; Only fill contents if P is within block boundaries.
22435 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22436 (forward-line)
22437 (point)))
22438 (cend (save-excursion
22439 (goto-char (org-element-property :end element))
22440 (skip-chars-backward " \r\t\n")
22441 (line-beginning-position))))
22442 (when (and (>= p cbeg) (< p cend))
22443 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22444 (match-string 0)
22445 ""))))))))))
22447 (declare-function message-goto-body "message" ())
22448 (defvar message-cite-prefix-regexp) ; From message.el
22449 (defun org-fill-paragraph (&optional justify)
22450 "Fill element at point, when applicable.
22452 This function only applies to comment blocks, comments, example
22453 blocks and paragraphs. Also, as a special case, re-align table
22454 when point is at one.
22456 If JUSTIFY is non-nil (interactively, with prefix argument),
22457 justify as well. If `sentence-end-double-space' is non-nil, then
22458 period followed by one space does not end a sentence, so don't
22459 break a line there. The variable `fill-column' controls the
22460 width for filling.
22462 For convenience, when point is at a plain list, an item or
22463 a footnote definition, try to fill the first paragraph within."
22464 (interactive)
22465 (if (and (derived-mode-p 'message-mode)
22466 (or (not (message-in-body-p))
22467 (save-excursion (move-beginning-of-line 1)
22468 (looking-at message-cite-prefix-regexp))))
22469 ;; First ensure filling is correct in message-mode.
22470 (let ((fill-paragraph-function
22471 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22472 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22473 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22474 (paragraph-separate
22475 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22476 (fill-paragraph nil))
22477 (with-syntax-table org-mode-transpose-word-syntax-table
22478 ;; Move to end of line in order to get the first paragraph
22479 ;; within a plain list or a footnote definition.
22480 (let ((element (save-excursion
22481 (end-of-line)
22482 (or (ignore-errors (org-element-at-point))
22483 (user-error "An element cannot be parsed line %d"
22484 (line-number-at-pos (point)))))))
22485 ;; First check if point is in a blank line at the beginning of
22486 ;; the buffer. In that case, ignore filling.
22487 (case (org-element-type element)
22488 ;; Use major mode filling function is src blocks.
22489 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22490 ;; Align Org tables, leave table.el tables as-is.
22491 (table-row (org-table-align) t)
22492 (table
22493 (when (eq (org-element-property :type element) 'org)
22494 (save-excursion
22495 (goto-char (org-element-property :post-affiliated element))
22496 (org-table-align)))
22498 (paragraph
22499 ;; Paragraphs may contain `line-break' type objects.
22500 (let ((beg (max (point-min)
22501 (org-element-property :contents-begin element)))
22502 (end (min (point-max)
22503 (org-element-property :contents-end element))))
22504 ;; Do nothing if point is at an affiliated keyword.
22505 (if (< (line-end-position) beg) t
22506 (when (derived-mode-p 'message-mode)
22507 ;; In `message-mode', do not fill following citation
22508 ;; in current paragraph nor text before message body.
22509 (let ((body-start (save-excursion (message-goto-body))))
22510 (when body-start (setq beg (max body-start beg))))
22511 (when (save-excursion
22512 (re-search-forward
22513 (concat "^" message-cite-prefix-regexp) end t))
22514 (setq end (match-beginning 0))))
22515 ;; Fill paragraph, taking line breaks into account.
22516 ;; For that, slice the paragraph using line breaks as
22517 ;; separators, and fill the parts in reverse order to
22518 ;; avoid messing with markers.
22519 (save-excursion
22520 (goto-char end)
22521 (mapc
22522 (lambda (pos)
22523 (fill-region-as-paragraph pos (point) justify)
22524 (goto-char pos))
22525 ;; Find the list of ending positions for line breaks
22526 ;; in the current paragraph. Add paragraph
22527 ;; beginning to include first slice.
22528 (nreverse
22529 (cons beg
22530 (org-element-map
22531 (org-element--parse-objects
22532 beg end nil (org-element-restriction 'paragraph))
22533 'line-break
22534 (lambda (lb) (org-element-property :end lb)))))))
22535 t)))
22536 ;; Contents of `comment-block' type elements should be
22537 ;; filled as plain text, but only if point is within block
22538 ;; markers.
22539 (comment-block
22540 (let* ((case-fold-search t)
22541 (beg (save-excursion
22542 (goto-char (org-element-property :begin element))
22543 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22544 (forward-line)
22545 (point)))
22546 (end (save-excursion
22547 (goto-char (org-element-property :end element))
22548 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22549 (line-beginning-position))))
22550 (if (or (< (point) beg) (> (point) end)) t
22551 (fill-region-as-paragraph
22552 (save-excursion (end-of-line)
22553 (re-search-backward "^[ \t]*$" beg 'move)
22554 (line-beginning-position))
22555 (save-excursion (beginning-of-line)
22556 (re-search-forward "^[ \t]*$" end 'move)
22557 (line-beginning-position))
22558 justify))))
22559 ;; Fill comments.
22560 (comment
22561 (let ((begin (org-element-property :post-affiliated element))
22562 (end (org-element-property :end element)))
22563 (when (and (>= (point) begin) (<= (point) end))
22564 (let ((begin (save-excursion
22565 (end-of-line)
22566 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22567 (progn (forward-line) (point))
22568 begin)))
22569 (end (save-excursion
22570 (end-of-line)
22571 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22572 (1- (line-beginning-position))
22573 (skip-chars-backward " \r\t\n")
22574 (line-end-position)))))
22575 ;; Do not fill comments when at a blank line.
22576 (when (> end begin)
22577 (let ((fill-prefix
22578 (save-excursion
22579 (beginning-of-line)
22580 (looking-at "[ \t]*#")
22581 (let ((comment-prefix (match-string 0)))
22582 (goto-char (match-end 0))
22583 (if (looking-at adaptive-fill-regexp)
22584 (concat comment-prefix (match-string 0))
22585 (concat comment-prefix " "))))))
22586 (save-excursion
22587 (fill-region-as-paragraph begin end justify))))))
22589 ;; Ignore every other element.
22590 (otherwise t))))))
22592 (defun org-auto-fill-function ()
22593 "Auto-fill function."
22594 ;; Check if auto-filling is meaningful.
22595 (let ((fc (current-fill-column)))
22596 (when (and fc (> (current-column) fc))
22597 (let* ((fill-prefix (org-adaptive-fill-function))
22598 ;; Enforce empty fill prefix, if required. Otherwise, it
22599 ;; will be computed again.
22600 (adaptive-fill-mode (not (equal fill-prefix ""))))
22601 (when fill-prefix (do-auto-fill))))))
22603 (defun org-comment-line-break-function (&optional soft)
22604 "Break line at point and indent, continuing comment if within one.
22605 The inserted newline is marked hard if variable
22606 `use-hard-newlines' is true, unless optional argument SOFT is
22607 non-nil."
22608 (if soft (insert-and-inherit ?\n) (newline 1))
22609 (save-excursion (forward-char -1) (delete-horizontal-space))
22610 (delete-horizontal-space)
22611 (indent-to-left-margin)
22612 (insert-before-markers-and-inherit fill-prefix))
22615 ;;; Comments
22617 ;; Org comments syntax is quite complex. It requires the entire line
22618 ;; to be just a comment. Also, even with the right syntax at the
22619 ;; beginning of line, some some elements (i.e. verse-block or
22620 ;; example-block) don't accept comments. Usual Emacs comment commands
22621 ;; cannot cope with those requirements. Therefore, Org replaces them.
22623 ;; Org still relies on `comment-dwim', but cannot trust
22624 ;; `comment-only-p'. So, `comment-region-function' and
22625 ;; `uncomment-region-function' both point
22626 ;; to`org-comment-or-uncomment-region'. Eventually,
22627 ;; `org-insert-comment' takes care of insertion of comments at the
22628 ;; beginning of line.
22630 ;; `org-setup-comments-handling' install comments related variables
22631 ;; during `org-mode' initialization.
22633 (defun org-setup-comments-handling ()
22634 (interactive)
22635 (org-set-local 'comment-use-syntax nil)
22636 (org-set-local 'comment-start "# ")
22637 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22638 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22639 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22640 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22642 (defun org-insert-comment ()
22643 "Insert an empty comment above current line.
22644 If the line is empty, insert comment at its beginning. When
22645 point is within a source block, comment according to the related
22646 major mode."
22647 (if (let ((element (org-element-at-point)))
22648 (and (eq (org-element-type element) 'src-block)
22649 (< (save-excursion
22650 (goto-char (org-element-property :post-affiliated element))
22651 (line-end-position))
22652 (point))
22653 (> (save-excursion
22654 (goto-char (org-element-property :end element))
22655 (skip-chars-backward " \r\t\n")
22656 (line-beginning-position))
22657 (point))))
22658 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22659 (beginning-of-line)
22660 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22661 (open-line 1))
22662 (org-indent-line)
22663 (insert "# ")))
22665 (defvar comment-empty-lines) ; From newcomment.el.
22666 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22667 "Comment or uncomment each non-blank line in the region.
22668 Uncomment each non-blank line between BEG and END if it only
22669 contains commented lines. Otherwise, comment them. If region is
22670 strictly within a source block, use appropriate comment syntax."
22671 (if (let ((element (org-element-at-point)))
22672 (and (eq (org-element-type element) 'src-block)
22673 (< (save-excursion
22674 (goto-char (org-element-property :post-affiliated element))
22675 (line-end-position))
22676 beg)
22677 (>= (save-excursion
22678 (goto-char (org-element-property :end element))
22679 (skip-chars-backward " \r\t\n")
22680 (line-beginning-position))
22681 end)))
22682 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22683 (save-restriction
22684 ;; Restrict region
22685 (narrow-to-region (save-excursion (goto-char beg)
22686 (skip-chars-forward " \r\t\n" end)
22687 (line-beginning-position))
22688 (save-excursion (goto-char end)
22689 (skip-chars-backward " \r\t\n" beg)
22690 (line-end-position)))
22691 (let ((uncommentp
22692 ;; UNCOMMENTP is non-nil when every non blank line between
22693 ;; BEG and END is a comment.
22694 (save-excursion
22695 (goto-char (point-min))
22696 (while (and (not (eobp))
22697 (let ((element (org-element-at-point)))
22698 (and (eq (org-element-type element) 'comment)
22699 (goto-char (min (point-max)
22700 (org-element-property
22701 :end element)))))))
22702 (eobp))))
22703 (if uncommentp
22704 ;; Only blank lines and comments in region: uncomment it.
22705 (save-excursion
22706 (goto-char (point-min))
22707 (while (not (eobp))
22708 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22709 (replace-match "" nil nil nil 1))
22710 (forward-line)))
22711 ;; Comment each line in region.
22712 (let ((min-indent (point-max)))
22713 ;; First find the minimum indentation across all lines.
22714 (save-excursion
22715 (goto-char (point-min))
22716 (while (and (not (eobp)) (not (zerop min-indent)))
22717 (unless (looking-at "[ \t]*$")
22718 (setq min-indent (min min-indent (current-indentation))))
22719 (forward-line)))
22720 ;; Then loop over all lines.
22721 (save-excursion
22722 (goto-char (point-min))
22723 (while (not (eobp))
22724 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22725 ;; Don't get fooled by invisible text (e.g. link path)
22726 ;; when moving to column MIN-INDENT.
22727 (let ((buffer-invisibility-spec nil))
22728 (org-move-to-column min-indent t))
22729 (insert comment-start))
22730 (forward-line)))))))))
22732 (defun org-comment-dwim (arg)
22733 (interactive "*P")
22734 "Call `comment-dwim' within a source edit buffer if needed."
22735 (if (org-in-src-block-p)
22736 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22737 (call-interactively #'comment-dwim)))
22740 ;;; Planning
22742 ;; This section contains tools to operate on timestamp objects, as
22743 ;; returned by, e.g. `org-element-context'.
22745 (defun org-timestamp-has-time-p (timestamp)
22746 "Non-nil when TIMESTAMP has a time specified."
22747 (org-element-property :hour-start timestamp))
22749 (defun org-timestamp-format (timestamp format &optional end utc)
22750 "Format a TIMESTAMP element into a string.
22752 FORMAT is a format specifier to be passed to
22753 `format-time-string'.
22755 When optional argument END is non-nil, use end of date-range or
22756 time-range, if possible.
22758 When optional argument UTC is non-nil, time will be expressed as
22759 Universal Time."
22760 (format-time-string
22761 format
22762 (apply 'encode-time
22763 (cons 0
22764 (mapcar
22765 (lambda (prop) (or (org-element-property prop timestamp) 0))
22766 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22767 '(:minute-start :hour-start :day-start :month-start
22768 :year-start)))))
22769 utc))
22771 (defun org-timestamp-split-range (timestamp &optional end)
22772 "Extract a timestamp object from a date or time range.
22774 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22775 the end of the range. Otherwise, extract its start.
22777 Return a new timestamp object sharing the same parent as
22778 TIMESTAMP."
22779 (let ((type (org-element-property :type timestamp)))
22780 (if (memq type '(active inactive diary)) timestamp
22781 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22782 ;; Set new type.
22783 (org-element-put-property
22784 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22785 ;; Copy start properties over end properties if END is
22786 ;; non-nil. Otherwise, copy end properties over `start' ones.
22787 (let ((p-alist '((:minute-start . :minute-end)
22788 (:hour-start . :hour-end)
22789 (:day-start . :day-end)
22790 (:month-start . :month-end)
22791 (:year-start . :year-end))))
22792 (dolist (p-cell p-alist)
22793 (org-element-put-property
22794 split-ts
22795 (funcall (if end 'car 'cdr) p-cell)
22796 (org-element-property
22797 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22798 ;; Eventually refresh `:raw-value'.
22799 (org-element-put-property split-ts :raw-value nil)
22800 (org-element-put-property
22801 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22803 (defun org-timestamp-translate (timestamp &optional boundary)
22804 "Apply `org-translate-time' on a TIMESTAMP object.
22805 When optional argument BOUNDARY is non-nil, it is either the
22806 symbol `start' or `end'. In this case, only translate the
22807 starting or ending part of TIMESTAMP if it is a date or time
22808 range. Otherwise, translate both parts."
22809 (if (and (not boundary)
22810 (memq (org-element-property :type timestamp)
22811 '(active-range inactive-range)))
22812 (concat
22813 (org-translate-time
22814 (org-element-property :raw-value
22815 (org-timestamp-split-range timestamp)))
22816 "--"
22817 (org-translate-time
22818 (org-element-property :raw-value
22819 (org-timestamp-split-range timestamp t))))
22820 (org-translate-time
22821 (org-element-property
22822 :raw-value
22823 (if (not boundary) timestamp
22824 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22828 ;;; Other stuff.
22830 (defun org-toggle-fixed-width-section (arg)
22831 "Toggle the fixed-width export.
22832 If there is no active region, the QUOTE keyword at the current headline is
22833 inserted or removed. When present, it causes the text between this headline
22834 and the next to be exported as fixed-width text, and unmodified.
22835 If there is an active region, this command adds or removes a colon as the
22836 first character of this line. If the first character of a line is a colon,
22837 this line is also exported in fixed-width font."
22838 (interactive "P")
22839 (let* ((cc 0)
22840 (regionp (org-region-active-p))
22841 (beg (if regionp (region-beginning) (point)))
22842 (end (if regionp (region-end)))
22843 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22844 (case-fold-search nil)
22845 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22846 off)
22847 (if regionp
22848 (save-excursion
22849 (goto-char beg)
22850 (setq cc (current-column))
22851 (beginning-of-line 1)
22852 (setq off (looking-at re))
22853 (while (> nlines 0)
22854 (setq nlines (1- nlines))
22855 (beginning-of-line 1)
22856 (cond
22857 (arg
22858 (org-move-to-column cc t)
22859 (insert ": \n")
22860 (forward-line -1))
22861 ((and off (looking-at re))
22862 (replace-match "" t t nil 1))
22863 ((not off) (org-move-to-column cc t) (insert ": ")))
22864 (forward-line 1)))
22865 (save-excursion
22866 (org-back-to-heading)
22867 (cond
22868 ((looking-at (format org-heading-keyword-regexp-format
22869 org-quote-string))
22870 (goto-char (match-end 1))
22871 (looking-at (concat " +" org-quote-string))
22872 (replace-match "" t t)
22873 (when (eolp) (insert " ")))
22874 ((looking-at org-outline-regexp)
22875 (goto-char (match-end 0))
22876 (insert org-quote-string " ")))))))
22878 (defun org-reftex-citation ()
22879 "Use reftex-citation to insert a citation into the buffer.
22880 This looks for a line like
22882 #+BIBLIOGRAPHY: foo plain option:-d
22884 and derives from it that foo.bib is the bibliography file relevant
22885 for this document. It then installs the necessary environment for RefTeX
22886 to work in this buffer and calls `reftex-citation' to insert a citation
22887 into the buffer.
22889 Export of such citations to both LaTeX and HTML is handled by the contributed
22890 package ox-bibtex by Taru Karttunen."
22891 (interactive)
22892 (let ((reftex-docstruct-symbol 'rds)
22893 (reftex-cite-format "\\cite{%l}")
22894 rds bib)
22895 (save-excursion
22896 (save-restriction
22897 (widen)
22898 (let ((case-fold-search t)
22899 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22900 (if (not (save-excursion
22901 (or (re-search-forward re nil t)
22902 (re-search-backward re nil t))))
22903 (error "No bibliography defined in file")
22904 (setq bib (concat (match-string 1) ".bib")
22905 rds (list (list 'bib bib)))))))
22906 (call-interactively 'reftex-citation)))
22908 ;;;; Functions extending outline functionality
22910 (defun org-beginning-of-line (&optional arg)
22911 "Go to the beginning of the current line. If that is invisible, continue
22912 to a visible line beginning. This makes the function of C-a more intuitive.
22913 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22914 first attempt, and only move to after the tags when the cursor is already
22915 beyond the end of the headline."
22916 (interactive "P")
22917 (let ((pos (point))
22918 (special (if (consp org-special-ctrl-a/e)
22919 (car org-special-ctrl-a/e)
22920 org-special-ctrl-a/e))
22921 deactivate-mark refpos)
22922 (if (org-bound-and-true-p visual-line-mode)
22923 (beginning-of-visual-line 1)
22924 (beginning-of-line 1))
22925 (if (and arg (fboundp 'move-beginning-of-line))
22926 (call-interactively 'move-beginning-of-line)
22927 (if (bobp)
22929 (backward-char 1)
22930 (if (org-truely-invisible-p)
22931 (while (and (not (bobp)) (org-truely-invisible-p))
22932 (backward-char 1)
22933 (beginning-of-line 1))
22934 (forward-char 1))))
22935 (when special
22936 (cond
22937 ((and (looking-at org-complex-heading-regexp)
22938 (= (char-after (match-end 1)) ?\ ))
22939 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22940 (point-at-eol)))
22941 (goto-char
22942 (if (eq special t)
22943 (cond ((> pos refpos) refpos)
22944 ((= pos (point)) refpos)
22945 (t (point)))
22946 (cond ((> pos (point)) (point))
22947 ((not (eq last-command this-command)) (point))
22948 (t refpos)))))
22949 ((org-at-item-p)
22950 ;; Being at an item and not looking at an the item means point
22951 ;; was previously moved to beginning of a visual line, which
22952 ;; doesn't contain the item. Therefore, do nothing special,
22953 ;; just stay here.
22954 (when (looking-at org-list-full-item-re)
22955 ;; Set special position at first white space character after
22956 ;; bullet, and check-box, if any.
22957 (let ((after-bullet
22958 (let ((box (match-end 3)))
22959 (if (not box) (match-end 1)
22960 (let ((after (char-after box)))
22961 (if (and after (= after ? )) (1+ box) box))))))
22962 ;; Special case: Move point to special position when
22963 ;; currently after it or at beginning of line.
22964 (if (eq special t)
22965 (when (or (> pos after-bullet) (= (point) pos))
22966 (goto-char after-bullet))
22967 ;; Reversed case: Move point to special position when
22968 ;; point was already at beginning of line and command is
22969 ;; repeated.
22970 (when (and (= (point) pos) (eq last-command this-command))
22971 (goto-char after-bullet))))))))
22972 (org-no-warnings
22973 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22974 (setq disable-point-adjustment
22975 (or (not (invisible-p (point)))
22976 (not (invisible-p (max (point-min) (1- (point))))))))
22978 (defun org-end-of-line (&optional arg)
22979 "Go to the end of the line.
22980 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22981 tags on the first attempt, and only move to after the tags when
22982 the cursor is already beyond the end of the headline."
22983 (interactive "P")
22984 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22985 org-special-ctrl-a/e))
22986 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22987 'end-of-visual-line)
22988 ((fboundp 'move-end-of-line) 'move-end-of-line)
22989 (t 'end-of-line)))
22990 deactivate-mark)
22991 (if (or (not special) arg) (call-interactively move-fun)
22992 (let* ((element (save-excursion (beginning-of-line)
22993 (org-element-at-point)))
22994 (type (org-element-type element)))
22995 (cond
22996 ((memq type '(headline inlinetask))
22997 (let ((pos (point)))
22998 (beginning-of-line 1)
22999 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23000 (if (eq special t)
23001 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23002 (goto-char (match-beginning 1))
23003 (goto-char (match-end 0)))
23004 (if (or (< pos (match-end 0))
23005 (not (eq this-command last-command)))
23006 (goto-char (match-end 0))
23007 (goto-char (match-beginning 1))))
23008 (call-interactively move-fun))))
23009 ((outline-invisible-p (line-end-position))
23010 ;; If element is hidden, `move-end-of-line' would put point
23011 ;; after it. Use `end-of-line' to stay on current line.
23012 (call-interactively 'end-of-line))
23013 (t (call-interactively move-fun)))))
23014 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23015 (setq disable-point-adjustment
23016 (or (not (invisible-p (point)))
23017 (not (invisible-p (max (point-min) (1- (point))))))))
23019 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23020 (define-key org-mode-map "\C-e" 'org-end-of-line)
23022 (defun org-backward-sentence (&optional arg)
23023 "Go to beginning of sentence, or beginning of table field.
23024 This will call `backward-sentence' or `org-table-beginning-of-field',
23025 depending on context."
23026 (interactive "P")
23027 (cond
23028 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
23029 (t (call-interactively 'backward-sentence))))
23031 (defun org-forward-sentence (&optional arg)
23032 "Go to end of sentence, or end of table field.
23033 This will call `forward-sentence' or `org-table-end-of-field',
23034 depending on context."
23035 (interactive "P")
23036 (cond
23037 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
23038 (t (call-interactively 'forward-sentence))))
23040 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23041 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23043 (defun org-kill-line (&optional arg)
23044 "Kill line, to tags or end of line."
23045 (interactive "P")
23046 (cond
23047 ((or (not org-special-ctrl-k)
23048 (bolp)
23049 (not (org-at-heading-p)))
23050 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23051 org-ctrl-k-protect-subtree)
23052 (if (or (eq org-ctrl-k-protect-subtree 'error)
23053 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23054 (user-error "C-k aborted as it would kill a hidden subtree")))
23055 (call-interactively
23056 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23057 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23058 (kill-region (point) (match-beginning 1))
23059 (org-set-tags nil t))
23060 (t (kill-region (point) (point-at-eol)))))
23062 (define-key org-mode-map "\C-k" 'org-kill-line)
23064 (defun org-yank (&optional arg)
23065 "Yank. If the kill is a subtree, treat it specially.
23066 This command will look at the current kill and check if is a single
23067 subtree, or a series of subtrees[1]. If it passes the test, and if the
23068 cursor is at the beginning of a line or after the stars of a currently
23069 empty headline, then the yank is handled specially. How exactly depends
23070 on the value of the following variables, both set by default.
23072 org-yank-folded-subtrees
23073 When set, the subtree(s) will be folded after insertion, but only
23074 if doing so would now swallow text after the yanked text.
23076 org-yank-adjusted-subtrees
23077 When set, the subtree will be promoted or demoted in order to
23078 fit into the local outline tree structure, which means that the level
23079 will be adjusted so that it becomes the smaller one of the two
23080 *visible* surrounding headings.
23082 Any prefix to this command will cause `yank' to be called directly with
23083 no special treatment. In particular, a simple \\[universal-argument] prefix \
23084 will just
23085 plainly yank the text as it is.
23087 \[1] The test checks if the first non-white line is a heading
23088 and if there are no other headings with fewer stars."
23089 (interactive "P")
23090 (org-yank-generic 'yank arg))
23092 (defun org-yank-generic (command arg)
23093 "Perform some yank-like command.
23095 This function implements the behavior described in the `org-yank'
23096 documentation. However, it has been generalized to work for any
23097 interactive command with similar behavior."
23099 ;; pretend to be command COMMAND
23100 (setq this-command command)
23102 (if arg
23103 (call-interactively command)
23105 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23106 (and (org-kill-is-subtree-p)
23107 (or (bolp)
23108 (and (looking-at "[ \t]*$")
23109 (string-match
23110 "\\`\\*+\\'"
23111 (buffer-substring (point-at-bol) (point)))))))
23112 swallowp)
23113 (cond
23114 ((and subtreep org-yank-folded-subtrees)
23115 (let ((beg (point))
23116 end)
23117 (if (and subtreep org-yank-adjusted-subtrees)
23118 (org-paste-subtree nil nil 'for-yank)
23119 (call-interactively command))
23121 (setq end (point))
23122 (goto-char beg)
23123 (when (and (bolp) subtreep
23124 (not (setq swallowp
23125 (org-yank-folding-would-swallow-text beg end))))
23126 (org-with-limited-levels
23127 (or (looking-at org-outline-regexp)
23128 (re-search-forward org-outline-regexp-bol end t))
23129 (while (and (< (point) end) (looking-at org-outline-regexp))
23130 (hide-subtree)
23131 (org-cycle-show-empty-lines 'folded)
23132 (condition-case nil
23133 (outline-forward-same-level 1)
23134 (error (goto-char end))))))
23135 (when swallowp
23136 (message
23137 "Inserted text not folded because that would swallow text"))
23139 (goto-char end)
23140 (skip-chars-forward " \t\n\r")
23141 (beginning-of-line 1)
23142 (push-mark beg 'nomsg)))
23143 ((and subtreep org-yank-adjusted-subtrees)
23144 (let ((beg (point-at-bol)))
23145 (org-paste-subtree nil nil 'for-yank)
23146 (push-mark beg 'nomsg)))
23148 (call-interactively command))))))
23150 (defun org-yank-folding-would-swallow-text (beg end)
23151 "Would hide-subtree at BEG swallow any text after END?"
23152 (let (level)
23153 (org-with-limited-levels
23154 (save-excursion
23155 (goto-char beg)
23156 (when (or (looking-at org-outline-regexp)
23157 (re-search-forward org-outline-regexp-bol end t))
23158 (setq level (org-outline-level)))
23159 (goto-char end)
23160 (skip-chars-forward " \t\r\n\v\f")
23161 (if (or (eobp)
23162 (and (bolp) (looking-at org-outline-regexp)
23163 (<= (org-outline-level) level)))
23164 nil ; Nothing would be swallowed
23165 t))))) ; something would swallow
23167 (define-key org-mode-map "\C-y" 'org-yank)
23169 (defun org-truely-invisible-p ()
23170 "Check if point is at a character currently not visible.
23171 This version does not only check the character property, but also
23172 `visible-mode'."
23173 ;; Early versions of noutline don't have `outline-invisible-p'.
23174 (if (org-bound-and-true-p visible-mode)
23176 (outline-invisible-p)))
23178 (defun org-invisible-p2 ()
23179 "Check if point is at a character currently not visible."
23180 (save-excursion
23181 (if (and (eolp) (not (bobp))) (backward-char 1))
23182 ;; Early versions of noutline don't have `outline-invisible-p'.
23183 (outline-invisible-p)))
23185 (defun org-back-to-heading (&optional invisible-ok)
23186 "Call `outline-back-to-heading', but provide a better error message."
23187 (condition-case nil
23188 (outline-back-to-heading invisible-ok)
23189 (error (error "Before first headline at position %d in buffer %s"
23190 (point) (current-buffer)))))
23192 (defun org-before-first-heading-p ()
23193 "Before first heading?"
23194 (save-excursion
23195 (end-of-line)
23196 (null (re-search-backward org-outline-regexp-bol nil t))))
23198 (defun org-at-heading-p (&optional ignored)
23199 (outline-on-heading-p t))
23200 ;; Compatibility alias with Org versions < 7.8.03
23201 (defalias 'org-on-heading-p 'org-at-heading-p)
23203 (defun org-at-comment-p nil
23204 "Is cursor in a line starting with a # character?"
23205 (save-excursion
23206 (beginning-of-line)
23207 (looking-at "^#")))
23209 (defun org-at-drawer-p nil
23210 "Is cursor at a drawer keyword?"
23211 (save-excursion
23212 (move-beginning-of-line 1)
23213 (looking-at org-drawer-regexp)))
23215 (defun org-at-block-p nil
23216 "Is cursor at a block keyword?"
23217 (save-excursion
23218 (move-beginning-of-line 1)
23219 (looking-at org-block-regexp)))
23221 (defun org-point-at-end-of-empty-headline ()
23222 "If point is at the end of an empty headline, return t, else nil.
23223 If the heading only contains a TODO keyword, it is still still considered
23224 empty."
23225 (and (looking-at "[ \t]*$")
23226 (when org-todo-line-regexp
23227 (save-excursion
23228 (beginning-of-line 1)
23229 (let ((case-fold-search nil))
23230 (looking-at org-todo-line-regexp)
23231 (string= (match-string 3) ""))))))
23233 (defun org-at-heading-or-item-p ()
23234 (or (org-at-heading-p) (org-at-item-p)))
23236 (defun org-at-target-p ()
23237 (or (org-in-regexp org-radio-target-regexp)
23238 (org-in-regexp org-target-regexp)))
23239 ;; Compatibility alias with Org versions < 7.8.03
23240 (defalias 'org-on-target-p 'org-at-target-p)
23242 (defun org-up-heading-all (arg)
23243 "Move to the heading line of which the present line is a subheading.
23244 This function considers both visible and invisible heading lines.
23245 With argument, move up ARG levels."
23246 (if (fboundp 'outline-up-heading-all)
23247 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23248 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23250 (defun org-up-heading-safe ()
23251 "Move to the heading line of which the present line is a subheading.
23252 This version will not throw an error. It will return the level of the
23253 headline found, or nil if no higher level is found.
23255 Also, this function will be a lot faster than `outline-up-heading',
23256 because it relies on stars being the outline starters. This can really
23257 make a significant difference in outlines with very many siblings."
23258 (let (start-level re)
23259 (org-back-to-heading t)
23260 (setq start-level (funcall outline-level))
23261 (if (equal start-level 1)
23263 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23264 (if (re-search-backward re nil t)
23265 (funcall outline-level)))))
23267 (defun org-first-sibling-p ()
23268 "Is this heading the first child of its parents?"
23269 (interactive)
23270 (let ((re org-outline-regexp-bol)
23271 level l)
23272 (unless (org-at-heading-p t)
23273 (user-error "Not at a heading"))
23274 (setq level (funcall outline-level))
23275 (save-excursion
23276 (if (not (re-search-backward re nil t))
23278 (setq l (funcall outline-level))
23279 (< l level)))))
23281 (defun org-goto-sibling (&optional previous)
23282 "Goto the next sibling, even if it is invisible.
23283 When PREVIOUS is set, go to the previous sibling instead. Returns t
23284 when a sibling was found. When none is found, return nil and don't
23285 move point."
23286 (let ((fun (if previous 're-search-backward 're-search-forward))
23287 (pos (point))
23288 (re org-outline-regexp-bol)
23289 level l)
23290 (when (condition-case nil (org-back-to-heading t) (error nil))
23291 (setq level (funcall outline-level))
23292 (catch 'exit
23293 (or previous (forward-char 1))
23294 (while (funcall fun re nil t)
23295 (setq l (funcall outline-level))
23296 (when (< l level) (goto-char pos) (throw 'exit nil))
23297 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23298 (goto-char pos)
23299 nil))))
23301 (defun org-show-siblings ()
23302 "Show all siblings of the current headline."
23303 (save-excursion
23304 (while (org-goto-sibling) (org-flag-heading nil)))
23305 (save-excursion
23306 (while (org-goto-sibling 'previous)
23307 (org-flag-heading nil))))
23309 (defun org-goto-first-child ()
23310 "Goto the first child, even if it is invisible.
23311 Return t when a child was found. Otherwise don't move point and
23312 return nil."
23313 (let (level (pos (point)) (re org-outline-regexp-bol))
23314 (when (condition-case nil (org-back-to-heading t) (error nil))
23315 (setq level (outline-level))
23316 (forward-char 1)
23317 (if (and (re-search-forward re nil t) (> (outline-level) level))
23318 (progn (goto-char (match-beginning 0)) t)
23319 (goto-char pos) nil))))
23321 (defun org-show-hidden-entry ()
23322 "Show an entry where even the heading is hidden."
23323 (save-excursion
23324 (org-show-entry)))
23326 (defun org-flag-heading (flag &optional entry)
23327 "Flag the current heading. FLAG non-nil means make invisible.
23328 When ENTRY is non-nil, show the entire entry."
23329 (save-excursion
23330 (org-back-to-heading t)
23331 ;; Check if we should show the entire entry
23332 (if entry
23333 (progn
23334 (org-show-entry)
23335 (save-excursion
23336 (and (outline-next-heading)
23337 (org-flag-heading nil))))
23338 (outline-flag-region (max (point-min) (1- (point)))
23339 (save-excursion (outline-end-of-heading) (point))
23340 flag))))
23342 (defun org-get-next-sibling ()
23343 "Move to next heading of the same level, and return point.
23344 If there is no such heading, return nil.
23345 This is like outline-next-sibling, but invisible headings are ok."
23346 (let ((level (funcall outline-level)))
23347 (outline-next-heading)
23348 (while (and (not (eobp)) (> (funcall outline-level) level))
23349 (outline-next-heading))
23350 (if (or (eobp) (< (funcall outline-level) level))
23352 (point))))
23354 (defun org-get-last-sibling ()
23355 "Move to previous heading of the same level, and return point.
23356 If there is no such heading, return nil."
23357 (let ((opoint (point))
23358 (level (funcall outline-level)))
23359 (outline-previous-heading)
23360 (when (and (/= (point) opoint) (outline-on-heading-p t))
23361 (while (and (> (funcall outline-level) level)
23362 (not (bobp)))
23363 (outline-previous-heading))
23364 (if (< (funcall outline-level) level)
23366 (point)))))
23368 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23369 "Goto to the end of a subtree."
23370 ;; This contains an exact copy of the original function, but it uses
23371 ;; `org-back-to-heading', to make it work also in invisible
23372 ;; trees. And is uses an invisible-ok argument.
23373 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23374 ;; Furthermore, when used inside Org, finding the end of a large subtree
23375 ;; with many children and grandchildren etc, this can be much faster
23376 ;; than the outline version.
23377 (org-back-to-heading invisible-ok)
23378 (let ((first t)
23379 (level (funcall outline-level)))
23380 (if (and (derived-mode-p 'org-mode) (< level 1000))
23381 ;; A true heading (not a plain list item), in Org-mode
23382 ;; This means we can easily find the end by looking
23383 ;; only for the right number of stars. Using a regexp to do
23384 ;; this is so much faster than using a Lisp loop.
23385 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23386 (forward-char 1)
23387 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23388 ;; something else, do it the slow way
23389 (while (and (not (eobp))
23390 (or first (> (funcall outline-level) level)))
23391 (setq first nil)
23392 (outline-next-heading)))
23393 (unless to-heading
23394 (if (memq (preceding-char) '(?\n ?\^M))
23395 (progn
23396 ;; Go to end of line before heading
23397 (forward-char -1)
23398 (if (memq (preceding-char) '(?\n ?\^M))
23399 ;; leave blank line before heading
23400 (forward-char -1))))))
23401 (point))
23403 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23404 "Use Org version in org-mode, for dramatic speed-up."
23405 (if (derived-mode-p 'org-mode)
23406 (progn
23407 (org-end-of-subtree nil t)
23408 (unless (eobp) (backward-char 1)))
23409 ad-do-it))
23411 (defun org-end-of-meta-data-and-drawers ()
23412 "Jump to the first text after meta data and drawers in the current entry.
23413 This will move over empty lines, lines with planning time stamps,
23414 clocking lines, and drawers."
23415 (org-back-to-heading t)
23416 (let ((end (save-excursion (outline-next-heading) (point)))
23417 (re (concat "\\(" org-drawer-regexp "\\)"
23418 "\\|" "[ \t]*" org-keyword-time-regexp)))
23419 (forward-line 1)
23420 (while (re-search-forward re end t)
23421 (if (not (match-end 1))
23422 ;; empty or planning line
23423 (forward-line 1)
23424 ;; a drawer, find the end
23425 (re-search-forward "^[ \t]*:END:" end 'move)
23426 (forward-line 1)))
23427 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23428 (point)))
23430 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23431 "Move forward to the ARG'th subheading at same level as this one.
23432 Stop at the first and last subheadings of a superior heading.
23433 Normally this only looks at visible headings, but when INVISIBLE-OK is
23434 non-nil it will also look at invisible ones."
23435 (interactive "p")
23436 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23437 (if (and arg (< arg 0))
23438 (goto-char (point-min))
23439 (outline-next-heading))
23440 (org-at-heading-p)
23441 (let ((level (- (match-end 0) (match-beginning 0) 1))
23442 (f (if (and arg (< arg 0))
23443 're-search-backward
23444 're-search-forward))
23445 (count (if arg (abs arg) 1))
23446 (result (point)))
23447 (while (and (prog1 (> count 0)
23448 (forward-char (if (and arg (< arg 0)) -1 1)))
23449 (funcall f org-outline-regexp-bol nil 'move))
23450 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23451 (cond ((< l level) (setq count 0))
23452 ((and (= l level)
23453 (or invisible-ok
23454 (progn
23455 (goto-char (line-beginning-position))
23456 (not (outline-invisible-p)))))
23457 (setq count (1- count))
23458 (when (eq l level)
23459 (setq result (point)))))))
23460 (goto-char result))
23461 (beginning-of-line 1)))
23463 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23464 "Move backward to the ARG'th subheading at same level as this one.
23465 Stop at the first and last subheadings of a superior heading."
23466 (interactive "p")
23467 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23469 (defun org-next-block (arg &optional backward block-regexp)
23470 "Jump to the next block.
23471 With a prefix argument ARG, jump forward ARG many source blocks.
23472 When BACKWARD is non-nil, jump to the previous block.
23473 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23474 (interactive "p")
23475 (let ((re (or block-regexp org-block-regexp))
23476 (re-search-fn (or (and backward 're-search-backward)
23477 're-search-forward)))
23478 (if (looking-at re) (forward-char 1))
23479 (condition-case nil
23480 (funcall re-search-fn re nil nil arg)
23481 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23482 (goto-char (match-beginning 0)) (org-show-context)))
23484 (defun org-previous-block (arg &optional block-regexp)
23485 "Jump to the previous block.
23486 With a prefix argument ARG, jump backward ARG many source blocks.
23487 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23488 (interactive "p")
23489 (org-next-block arg t block-regexp))
23491 (defun org-forward-paragraph ()
23492 "Move forward to beginning of next paragraph or equivalent.
23494 The function moves point to the beginning of the next visible
23495 structural element, which can be a paragraph, a table, a list
23496 item, etc. It also provides some special moves for convenience:
23498 - On an affiliated keyword, jump to the beginning of the
23499 relative element.
23500 - On an item or a footnote definition, move to the second
23501 element inside, if any.
23502 - On a table or a property drawer, jump after it.
23503 - On a verse or source block, stop after blank lines."
23504 (interactive)
23505 (when (eobp) (user-error "Cannot move further down"))
23506 (let* ((deactivate-mark nil)
23507 (element (org-element-at-point))
23508 (type (org-element-type element))
23509 (post-affiliated (org-element-property :post-affiliated element))
23510 (contents-begin (org-element-property :contents-begin element))
23511 (contents-end (org-element-property :contents-end element))
23512 (end (let ((end (org-element-property :end element)) (parent element))
23513 (while (and (setq parent (org-element-property :parent parent))
23514 (= (org-element-property :contents-end parent) end))
23515 (setq end (org-element-property :end parent)))
23516 end)))
23517 (cond ((not element)
23518 (skip-chars-forward " \r\t\n")
23519 (or (eobp) (beginning-of-line)))
23520 ;; On affiliated keywords, move to element's beginning.
23521 ((and post-affiliated (< (point) post-affiliated))
23522 (goto-char post-affiliated))
23523 ;; At a table row, move to the end of the table. Similarly,
23524 ;; at a node property, move to the end of the property
23525 ;; drawer.
23526 ((memq type '(node-property table-row))
23527 (goto-char (org-element-property
23528 :end (org-element-property :parent element))))
23529 ((memq type '(property-drawer table)) (goto-char end))
23530 ;; Consider blank lines as separators in verse and source
23531 ;; blocks to ease editing.
23532 ((memq type '(src-block verse-block))
23533 (when (eq type 'src-block)
23534 (setq contents-end
23535 (save-excursion (goto-char end)
23536 (skip-chars-backward " \r\t\n")
23537 (line-beginning-position))))
23538 (beginning-of-line)
23539 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23540 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23541 (goto-char end)
23542 (skip-chars-forward " \r\t\n")
23543 (if (= (point) contents-end) (goto-char end)
23544 (beginning-of-line))))
23545 ;; With no contents, just skip element.
23546 ((not contents-begin) (goto-char end))
23547 ;; If contents are invisible, skip the element altogether.
23548 ((outline-invisible-p (line-end-position))
23549 (case type
23550 (headline
23551 (org-with-limited-levels (outline-next-visible-heading 1)))
23552 ;; At a plain list, make sure we move to the next item
23553 ;; instead of skipping the whole list.
23554 (plain-list (forward-char)
23555 (org-forward-paragraph))
23556 (otherwise (goto-char end))))
23557 ((>= (point) contents-end) (goto-char end))
23558 ((>= (point) contents-begin)
23559 ;; This can only happen on paragraphs and plain lists.
23560 (case type
23561 (paragraph (goto-char end))
23562 ;; At a plain list, try to move to second element in
23563 ;; first item, if possible.
23564 (plain-list (end-of-line)
23565 (org-forward-paragraph))))
23566 ;; When contents start on the middle of a line (e.g. in
23567 ;; items and footnote definitions), try to reach first
23568 ;; element starting after current line.
23569 ((> (line-end-position) contents-begin)
23570 (end-of-line)
23571 (org-forward-paragraph))
23572 (t (goto-char contents-begin)))))
23574 (defun org-backward-paragraph ()
23575 "Move backward to start of previous paragraph or equivalent.
23577 The function moves point to the beginning of the current
23578 structural element, which can be a paragraph, a table, a list
23579 item, etc., or to the beginning of the previous visible one if
23580 point is already there. It also provides some special moves for
23581 convenience:
23583 - On an affiliated keyword, jump to the first one.
23584 - On a table or a property drawer, move to its beginning.
23585 - On a verse or source block, stop before blank lines."
23586 (interactive)
23587 (when (bobp) (user-error "Cannot move further up"))
23588 (let* ((deactivate-mark nil)
23589 (element (org-element-at-point))
23590 (type (org-element-type element))
23591 (contents-begin (org-element-property :contents-begin element))
23592 (contents-end (org-element-property :contents-end element))
23593 (post-affiliated (org-element-property :post-affiliated element))
23594 (begin (org-element-property :begin element)))
23595 (cond
23596 ((not element) (goto-char (point-min)))
23597 ((= (point) begin)
23598 (backward-char)
23599 (org-backward-paragraph))
23600 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23601 ((memq type '(node-property table-row))
23602 (goto-char (org-element-property
23603 :post-affiliated (org-element-property :parent element))))
23604 ((memq type '(property-drawer table)) (goto-char begin))
23605 ((memq type '(src-block verse-block))
23606 (when (eq type 'src-block)
23607 (setq contents-begin
23608 (save-excursion (goto-char begin) (forward-line) (point))))
23609 (if (= (point) contents-begin) (goto-char post-affiliated)
23610 ;; Inside a verse block, see blank lines as paragraph
23611 ;; separators.
23612 (let ((origin (point)))
23613 (skip-chars-backward " \r\t\n" contents-begin)
23614 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23615 (skip-chars-forward " \r\t\n" origin)
23616 (if (= (point) origin) (goto-char contents-begin)
23617 (beginning-of-line))))))
23618 ((not contents-begin) (goto-char (or post-affiliated begin)))
23619 ((eq type 'paragraph)
23620 (goto-char contents-begin)
23621 ;; When at first paragraph in an item or a footnote definition,
23622 ;; move directly to beginning of line.
23623 (let ((parent-contents
23624 (org-element-property
23625 :contents-begin (org-element-property :parent element))))
23626 (when (and parent-contents (= parent-contents contents-begin))
23627 (beginning-of-line))))
23628 ;; At the end of a greater element, move to the beginning of the
23629 ;; last element within.
23630 ((>= (point) contents-end)
23631 (goto-char (1- contents-end))
23632 (org-backward-paragraph))
23633 (t (goto-char (or post-affiliated begin))))
23634 ;; Ensure we never leave point invisible.
23635 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23637 (defun org-forward-element ()
23638 "Move forward by one element.
23639 Move to the next element at the same level, when possible."
23640 (interactive)
23641 (cond ((eobp) (user-error "Cannot move further down"))
23642 ((org-with-limited-levels (org-at-heading-p))
23643 (let ((origin (point)))
23644 (goto-char (org-end-of-subtree nil t))
23645 (unless (org-with-limited-levels (org-at-heading-p))
23646 (goto-char origin)
23647 (user-error "Cannot move further down"))))
23649 (let* ((elem (org-element-at-point))
23650 (end (org-element-property :end elem))
23651 (parent (org-element-property :parent elem)))
23652 (cond ((and parent (= (org-element-property :contents-end parent) end))
23653 (goto-char (org-element-property :end parent)))
23654 ((integer-or-marker-p end) (goto-char end))
23655 (t (message "No element at point")))))))
23657 (defun org-backward-element ()
23658 "Move backward by one element.
23659 Move to the previous element at the same level, when possible."
23660 (interactive)
23661 (cond ((bobp) (user-error "Cannot move further up"))
23662 ((org-with-limited-levels (org-at-heading-p))
23663 ;; At a headline, move to the previous one, if any, or stay
23664 ;; here.
23665 (let ((origin (point)))
23666 (org-with-limited-levels (org-backward-heading-same-level 1))
23667 ;; When current headline has no sibling above, move to its
23668 ;; parent.
23669 (when (= (point) origin)
23670 (or (org-with-limited-levels (org-up-heading-safe))
23671 (progn (goto-char origin)
23672 (user-error "Cannot move further up"))))))
23674 (let* ((elem (org-element-at-point))
23675 (beg (org-element-property :begin elem)))
23676 (cond
23677 ;; Move to beginning of current element if point isn't
23678 ;; there already.
23679 ((null beg) (message "No element at point"))
23680 ((/= (point) beg) (goto-char beg))
23681 (t (goto-char beg)
23682 (skip-chars-backward " \r\t\n")
23683 (unless (bobp)
23684 (let ((prev (org-element-at-point)))
23685 (goto-char (org-element-property :begin prev))
23686 (while (and (setq prev (org-element-property :parent prev))
23687 (<= (org-element-property :end prev) beg))
23688 (goto-char (org-element-property :begin prev)))))))))))
23690 (defun org-up-element ()
23691 "Move to upper element."
23692 (interactive)
23693 (if (org-with-limited-levels (org-at-heading-p))
23694 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23695 (let* ((elem (org-element-at-point))
23696 (parent (org-element-property :parent elem)))
23697 (if parent (goto-char (org-element-property :begin parent))
23698 (if (org-with-limited-levels (org-before-first-heading-p))
23699 (user-error "No surrounding element")
23700 (org-with-limited-levels (org-back-to-heading)))))))
23702 (defvar org-element-greater-elements)
23703 (defun org-down-element ()
23704 "Move to inner element."
23705 (interactive)
23706 (let ((element (org-element-at-point)))
23707 (cond
23708 ((memq (org-element-type element) '(plain-list table))
23709 (goto-char (org-element-property :contents-begin element))
23710 (forward-char))
23711 ((memq (org-element-type element) org-element-greater-elements)
23712 ;; If contents are hidden, first disclose them.
23713 (when (outline-invisible-p (line-end-position)) (org-cycle))
23714 (goto-char (or (org-element-property :contents-begin element)
23715 (user-error "No content for this element"))))
23716 (t (user-error "No inner element")))))
23718 (defun org-drag-element-backward ()
23719 "Move backward element at point."
23720 (interactive)
23721 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23722 (let* ((elem (org-element-at-point))
23723 (prev-elem
23724 (save-excursion
23725 (goto-char (org-element-property :begin elem))
23726 (skip-chars-backward " \r\t\n")
23727 (unless (bobp)
23728 (let* ((beg (org-element-property :begin elem))
23729 (prev (org-element-at-point))
23730 (up prev))
23731 (while (and (setq up (org-element-property :parent up))
23732 (<= (org-element-property :end prev) beg))
23733 (setq prev up))
23734 prev)))))
23735 ;; Error out if no previous element or previous element is
23736 ;; a parent of the current one.
23737 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23738 (user-error "Cannot drag element backward")
23739 (let ((pos (point)))
23740 (org-element-swap-A-B prev-elem elem)
23741 (goto-char (+ (org-element-property :begin prev-elem)
23742 (- pos (org-element-property :begin elem)))))))))
23744 (defun org-drag-element-forward ()
23745 "Move forward element at point."
23746 (interactive)
23747 (let* ((pos (point))
23748 (elem (org-element-at-point)))
23749 (when (= (point-max) (org-element-property :end elem))
23750 (user-error "Cannot drag element forward"))
23751 (goto-char (org-element-property :end elem))
23752 (let ((next-elem (org-element-at-point)))
23753 (when (or (org-element-nested-p elem next-elem)
23754 (and (eq (org-element-type next-elem) 'headline)
23755 (not (eq (org-element-type elem) 'headline))))
23756 (goto-char pos)
23757 (user-error "Cannot drag element forward"))
23758 ;; Compute new position of point: it's shifted by NEXT-ELEM
23759 ;; body's length (without final blanks) and by the length of
23760 ;; blanks between ELEM and NEXT-ELEM.
23761 (let ((size-next (- (save-excursion
23762 (goto-char (org-element-property :end next-elem))
23763 (skip-chars-backward " \r\t\n")
23764 (forward-line)
23765 ;; Small correction if buffer doesn't end
23766 ;; with a newline character.
23767 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23768 (org-element-property :begin next-elem)))
23769 (size-blank (- (org-element-property :end elem)
23770 (save-excursion
23771 (goto-char (org-element-property :end elem))
23772 (skip-chars-backward " \r\t\n")
23773 (forward-line)
23774 (point)))))
23775 (org-element-swap-A-B elem next-elem)
23776 (goto-char (+ pos size-next size-blank))))))
23778 (defun org-drag-line-forward (arg)
23779 "Drag the line at point ARG lines forward."
23780 (interactive "p")
23781 (dotimes (n (abs arg))
23782 (let ((c (current-column)))
23783 (if (< 0 arg)
23784 (progn
23785 (beginning-of-line 2)
23786 (transpose-lines 1)
23787 (beginning-of-line 0))
23788 (transpose-lines 1)
23789 (beginning-of-line -1))
23790 (org-move-to-column c))))
23792 (defun org-drag-line-backward (arg)
23793 "Drag the line at point ARG lines backward."
23794 (interactive "p")
23795 (org-drag-line-forward (- arg)))
23797 (defun org-mark-element ()
23798 "Put point at beginning of this element, mark at end.
23800 Interactively, if this command is repeated or (in Transient Mark
23801 mode) if the mark is active, it marks the next element after the
23802 ones already marked."
23803 (interactive)
23804 (let (deactivate-mark)
23805 (if (and (org-called-interactively-p 'any)
23806 (or (and (eq last-command this-command) (mark t))
23807 (and transient-mark-mode mark-active)))
23808 (set-mark
23809 (save-excursion
23810 (goto-char (mark))
23811 (goto-char (org-element-property :end (org-element-at-point)))))
23812 (let ((element (org-element-at-point)))
23813 (end-of-line)
23814 (push-mark (org-element-property :end element) t t)
23815 (goto-char (org-element-property :begin element))))))
23817 (defun org-narrow-to-element ()
23818 "Narrow buffer to current element."
23819 (interactive)
23820 (let ((elem (org-element-at-point)))
23821 (cond
23822 ((eq (car elem) 'headline)
23823 (narrow-to-region
23824 (org-element-property :begin elem)
23825 (org-element-property :end elem)))
23826 ((memq (car elem) org-element-greater-elements)
23827 (narrow-to-region
23828 (org-element-property :contents-begin elem)
23829 (org-element-property :contents-end elem)))
23831 (narrow-to-region
23832 (org-element-property :begin elem)
23833 (org-element-property :end elem))))))
23835 (defun org-transpose-element ()
23836 "Transpose current and previous elements, keeping blank lines between.
23837 Point is moved after both elements."
23838 (interactive)
23839 (org-skip-whitespace)
23840 (let ((end (org-element-property :end (org-element-at-point))))
23841 (org-drag-element-backward)
23842 (goto-char end)))
23844 (defun org-unindent-buffer ()
23845 "Un-indent the visible part of the buffer.
23846 Relative indentation (between items, inside blocks, etc.) isn't
23847 modified."
23848 (interactive)
23849 (unless (eq major-mode 'org-mode)
23850 (user-error "Cannot un-indent a buffer not in Org mode"))
23851 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23852 unindent-tree ; For byte-compiler.
23853 (unindent-tree
23854 (function
23855 (lambda (contents)
23856 (mapc
23857 (lambda (element)
23858 (if (memq (org-element-type element) '(headline section))
23859 (funcall unindent-tree (org-element-contents element))
23860 (save-excursion
23861 (save-restriction
23862 (narrow-to-region
23863 (org-element-property :begin element)
23864 (org-element-property :end element))
23865 (org-do-remove-indentation)))))
23866 (reverse contents))))))
23867 (funcall unindent-tree (org-element-contents parse-tree))))
23869 (defun org-show-subtree ()
23870 "Show everything after this heading at deeper levels."
23871 (interactive)
23872 (outline-flag-region
23873 (point)
23874 (save-excursion
23875 (org-end-of-subtree t t))
23876 nil))
23878 (defun org-show-entry ()
23879 "Show the body directly following this heading.
23880 Show the heading too, if it is currently invisible."
23881 (interactive)
23882 (save-excursion
23883 (condition-case nil
23884 (progn
23885 (org-back-to-heading t)
23886 (outline-flag-region
23887 (max (point-min) (1- (point)))
23888 (save-excursion
23889 (if (re-search-forward
23890 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23891 (match-beginning 1)
23892 (point-max)))
23893 nil)
23894 (org-cycle-hide-drawers 'children))
23895 (error nil))))
23897 (defun org-make-options-regexp (kwds &optional extra)
23898 "Make a regular expression for keyword lines."
23899 (concat
23900 "^#\\+\\("
23901 (mapconcat 'regexp-quote kwds "\\|")
23902 (if extra (concat "\\|" extra))
23903 "\\):[ \t]*\\(.*\\)"))
23905 ;; Make isearch reveal the necessary context
23906 (defun org-isearch-end ()
23907 "Reveal context after isearch exits."
23908 (when isearch-success ; only if search was successful
23909 (if (featurep 'xemacs)
23910 ;; Under XEmacs, the hook is run in the correct place,
23911 ;; we directly show the context.
23912 (org-show-context 'isearch)
23913 ;; In Emacs the hook runs *before* restoring the overlays.
23914 ;; So we have to use a one-time post-command-hook to do this.
23915 ;; (Emacs 22 has a special variable, see function `org-mode')
23916 (unless (and (boundp 'isearch-mode-end-hook-quit)
23917 isearch-mode-end-hook-quit)
23918 ;; Only when the isearch was not quitted.
23919 (org-add-hook 'post-command-hook 'org-isearch-post-command
23920 'append 'local)))
23921 (org-fix-ellipsis-at-bol)))
23923 (defun org-isearch-post-command ()
23924 "Remove self from hook, and show context."
23925 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23926 (org-show-context 'isearch))
23929 ;;;; Integration with and fixes for other packages
23931 ;;; Imenu support
23933 (defvar org-imenu-markers nil
23934 "All markers currently used by Imenu.")
23935 (make-variable-buffer-local 'org-imenu-markers)
23937 (defun org-imenu-new-marker (&optional pos)
23938 "Return a new marker for use by Imenu, and remember the marker."
23939 (let ((m (make-marker)))
23940 (move-marker m (or pos (point)))
23941 (push m org-imenu-markers)
23944 (defun org-imenu-get-tree ()
23945 "Produce the index for Imenu."
23946 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23947 (setq org-imenu-markers nil)
23948 (let* ((n org-imenu-depth)
23949 (re (concat "^" (org-get-limited-outline-regexp)))
23950 (subs (make-vector (1+ n) nil))
23951 (last-level 0)
23952 m level head0 head)
23953 (save-excursion
23954 (save-restriction
23955 (widen)
23956 (goto-char (point-max))
23957 (while (re-search-backward re nil t)
23958 (setq level (org-reduced-level (funcall outline-level)))
23959 (when (and (<= level n)
23960 (looking-at org-complex-heading-regexp)
23961 (setq head0 (org-match-string-no-properties 4)))
23962 (setq head (org-link-display-format head0)
23963 m (org-imenu-new-marker))
23964 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23965 (if (>= level last-level)
23966 (push (cons head m) (aref subs level))
23967 (push (cons head (aref subs (1+ level))) (aref subs level))
23968 (loop for i from (1+ level) to n do (aset subs i nil)))
23969 (setq last-level level)))))
23970 (aref subs 1)))
23972 (eval-after-load "imenu"
23973 '(progn
23974 (add-hook 'imenu-after-jump-hook
23975 (lambda ()
23976 (if (derived-mode-p 'org-mode)
23977 (org-show-context 'org-goto))))))
23979 (defun org-link-display-format (link)
23980 "Replace a link with its the description.
23981 If there is no description, use the link target."
23982 (save-match-data
23983 (if (string-match org-bracket-link-analytic-regexp link)
23984 (replace-match (if (match-end 5)
23985 (match-string 5 link)
23986 (concat (match-string 1 link)
23987 (match-string 3 link)))
23988 nil t link)
23989 link)))
23991 (defun org-toggle-link-display ()
23992 "Toggle the literal or descriptive display of links."
23993 (interactive)
23994 (if org-descriptive-links
23995 (progn (org-remove-from-invisibility-spec '(org-link))
23996 (org-restart-font-lock)
23997 (setq org-descriptive-links nil))
23998 (progn (add-to-invisibility-spec '(org-link))
23999 (org-restart-font-lock)
24000 (setq org-descriptive-links t))))
24002 ;; Speedbar support
24004 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24005 "Overlay marking the agenda restriction line in speedbar.")
24006 (overlay-put org-speedbar-restriction-lock-overlay
24007 'face 'org-agenda-restriction-lock)
24008 (overlay-put org-speedbar-restriction-lock-overlay
24009 'help-echo "Agendas are currently limited to this item.")
24010 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24012 (defun org-speedbar-set-agenda-restriction ()
24013 "Restrict future agenda commands to the location at point in speedbar.
24014 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24015 (interactive)
24016 (require 'org-agenda)
24017 (let (p m tp np dir txt)
24018 (cond
24019 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24020 'org-imenu t))
24021 (setq m (get-text-property p 'org-imenu-marker))
24022 (with-current-buffer (marker-buffer m)
24023 (goto-char m)
24024 (org-agenda-set-restriction-lock 'subtree)))
24025 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24026 'speedbar-function 'speedbar-find-file))
24027 (setq tp (previous-single-property-change
24028 (1+ p) 'speedbar-function)
24029 np (next-single-property-change
24030 tp 'speedbar-function)
24031 dir (speedbar-line-directory)
24032 txt (buffer-substring-no-properties (or tp (point-min))
24033 (or np (point-max))))
24034 (with-current-buffer (find-file-noselect
24035 (let ((default-directory dir))
24036 (expand-file-name txt)))
24037 (unless (derived-mode-p 'org-mode)
24038 (user-error "Cannot restrict to non-Org-mode file"))
24039 (org-agenda-set-restriction-lock 'file)))
24040 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24041 (move-overlay org-speedbar-restriction-lock-overlay
24042 (point-at-bol) (point-at-eol))
24043 (setq current-prefix-arg nil)
24044 (org-agenda-maybe-redo)))
24046 (defvar speedbar-file-key-map)
24047 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24048 (eval-after-load "speedbar"
24049 '(progn
24050 (speedbar-add-supported-extension ".org")
24051 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24052 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24053 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24054 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24055 (add-hook 'speedbar-visiting-tag-hook
24056 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24058 ;;; Fixes and Hacks for problems with other packages
24060 (defun org-mode-flyspell-verify ()
24061 "Function used for `flyspell-generic-check-word-predicate'."
24062 (if (org-at-heading-p)
24063 ;; At a headline or an inlinetask, check title only. This is
24064 ;; faster than relying on `org-element-at-point'.
24065 (and (save-excursion (beginning-of-line)
24066 (and (let ((case-fold-search t))
24067 (not (looking-at "\\*+ END[ \t]*$")))
24068 (looking-at org-complex-heading-regexp)))
24069 (match-beginning 4)
24070 (>= (point) (match-beginning 4))
24071 (or (not (match-beginning 5))
24072 (< (point) (match-beginning 5))))
24073 (let* ((element (org-element-at-point))
24074 (post-affiliated (org-element-property :post-affiliated element))
24075 (object-check
24076 (function
24077 ;; Non-nil if checks can be done for object at point.
24078 (lambda ()
24079 (let ((object (save-excursion
24080 (when (org-looking-at-p "\\>") (backward-char))
24081 (org-element-context element))))
24082 (case (org-element-type object)
24083 ;; Prevent checks in links due to keybinding conflict
24084 ;; with Flyspell.
24085 ((code entity export-snippet inline-babel-call
24086 inline-src-block line-break latex-fragment link macro
24087 statistics-cookie target timestamp verbatim)
24088 nil)
24089 (footnote-reference
24090 ;; Only in inline footnotes, within the definition.
24091 (and (eq (org-element-property :type object) 'inline)
24092 (< (save-excursion
24093 (goto-char (org-element-property :begin object))
24094 (search-forward ":" nil t 2))
24095 (point))))
24096 (otherwise t)))))))
24097 (cond
24098 ;; Ignore checks in all affiliated keywords but captions.
24099 ((and post-affiliated (< (point) post-affiliated))
24100 (and (save-excursion
24101 (beginning-of-line)
24102 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24103 (> (point) (match-end 0))
24104 (funcall object-check)))
24105 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24106 ((and org-log-into-drawer
24107 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24108 (parent element))
24109 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24110 (setq parent (org-element-property :parent parent)))
24111 (and parent
24112 (eq (compare-strings
24113 log nil nil
24114 (org-element-property :drawer-name parent) nil nil t)
24115 t))))
24116 nil)
24118 (case (org-element-type element)
24119 ((comment quote-section) t)
24120 (comment-block
24121 ;; Allow checks between block markers, not on them.
24122 (and (> (line-beginning-position)
24123 (org-element-property :post-affiliated element))
24124 (save-excursion
24125 (end-of-line)
24126 (skip-chars-forward " \r\t\n")
24127 (< (point) (org-element-property :end element)))))
24128 ;; Arbitrary list of keywords where checks are meaningful.
24129 ;; Make sure point is on the value part of the element.
24130 (keyword
24131 (and (member (org-element-property :key element)
24132 '("DESCRIPTION" "TITLE"))
24133 (< (save-excursion
24134 (beginning-of-line) (search-forward ":") (point))
24135 (point))))
24136 ;; Check is globally allowed in paragraphs verse blocks and
24137 ;; table rows (after affiliated keywords) but some objects
24138 ;; must not be affected.
24139 ((paragraph table-row verse-block)
24140 (and (>= (point) (org-element-property :contents-begin element))
24141 (< (point) (org-element-property :contents-end element))
24142 (funcall object-check)))))))))
24143 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24145 (defun org-remove-flyspell-overlays-in (beg end)
24146 "Remove flyspell overlays in region."
24147 (and (org-bound-and-true-p flyspell-mode)
24148 (fboundp 'flyspell-delete-region-overlays)
24149 (flyspell-delete-region-overlays beg end)))
24151 (eval-after-load "flyspell"
24152 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24154 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24155 (eval-after-load "bookmark"
24156 '(if (boundp 'bookmark-after-jump-hook)
24157 ;; We can use the hook
24158 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24159 ;; Hook not available, use advice
24160 (defadvice bookmark-jump (after org-make-visible activate)
24161 "Make the position visible."
24162 (org-bookmark-jump-unhide))))
24164 ;; Make sure saveplace shows the location if it was hidden
24165 (eval-after-load "saveplace"
24166 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24167 "Make the position visible."
24168 (org-bookmark-jump-unhide)))
24170 ;; Make sure ecb shows the location if it was hidden
24171 (eval-after-load "ecb"
24172 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24173 "Make hierarchy visible when jumping into location from ECB tree buffer."
24174 (if (derived-mode-p 'org-mode)
24175 (org-show-context))))
24177 (defun org-bookmark-jump-unhide ()
24178 "Unhide the current position, to show the bookmark location."
24179 (and (derived-mode-p 'org-mode)
24180 (or (outline-invisible-p)
24181 (save-excursion (goto-char (max (point-min) (1- (point))))
24182 (outline-invisible-p)))
24183 (org-show-context 'bookmark-jump)))
24185 ;; Make session.el ignore our circular variable
24186 (defvar session-globals-exclude)
24187 (eval-after-load "session"
24188 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24190 ;;;; Finish up
24192 (provide 'org)
24194 (run-hooks 'org-load-hook)
24196 ;;; org.el ends here