org.el: Fix compiler warnings
[org-mode.git] / lisp / org.el
bloba6a8b2032062393edca1a108b848f1a439b2a70d
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].")
433 ;;;; LaTeX Environments and Fragments
435 (defconst org-latex-regexps
436 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
437 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
438 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
439 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
440 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
441 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
442 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
443 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
444 "Regular expressions for matching embedded LaTeX.")
446 ;;;; Node Property
448 (defconst org-effort-property "Effort"
449 "The property that is being used to keep track of effort estimates.
450 Effort estimates given in this property need to have the format H:MM.")
452 ;;;; Table
454 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
455 "Detect an org-type or table-type table.")
457 (defconst org-table-line-regexp "^[ \t]*|"
458 "Detect an org-type table line.")
460 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
461 "Detect an org-type table line.")
463 (defconst org-table-hline-regexp "^[ \t]*|-"
464 "Detect an org-type table hline.")
466 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
467 "Detect a table-type table hline.")
469 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
470 "Detect the first line outside a table when searching from within it.
471 This works for both table types.")
473 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
474 "Detect a #+TBLFM line.")
476 ;;;; Timestamp
478 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
479 "Regular expression for fast time stamp matching.")
481 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
482 "Regular expression for fast time stamp matching.")
484 (defconst org-ts-regexp0
485 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
486 "Regular expression matching time strings for analysis.
487 This one does not require the space after the date, so it can be used
488 on a string that terminates immediately after the date.")
490 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
491 "Regular expression matching time strings for analysis.")
493 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
494 "Regular expression matching time stamps, with groups.")
496 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
497 "Regular expression matching time stamps (also [..]), with groups.")
499 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
500 "Regular expression matching a time stamp range.")
502 (defconst org-tr-regexp-both
503 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
504 "Regular expression matching a time stamp range.")
506 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
507 org-ts-regexp "\\)?")
508 "Regular expression matching a time stamp or time stamp range.")
510 (defconst org-tsr-regexp-both
511 (concat org-ts-regexp-both "\\(--?-?"
512 org-ts-regexp-both "\\)?")
513 "Regular expression matching a time stamp or time stamp range.
514 The time stamps may be either active or inactive.")
516 (defconst org-repeat-re
517 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
518 "Regular expression for specifying repeated events.
519 After a match, group 1 contains the repeat expression.")
521 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
522 "Formats for `format-time-string' which are used for time stamps.")
525 ;;; The custom variables
527 (defgroup org nil
528 "Outline-based notes management and organizer."
529 :tag "Org"
530 :group 'outlines
531 :group 'calendar)
533 (defcustom org-mode-hook nil
534 "Mode hook for Org-mode, run after the mode was turned on."
535 :group 'org
536 :type 'hook)
538 (defcustom org-load-hook nil
539 "Hook that is run after org.el has been loaded."
540 :group 'org
541 :type 'hook)
543 (defcustom org-log-buffer-setup-hook nil
544 "Hook that is run after an Org log buffer is created."
545 :group 'org
546 :version "24.1"
547 :type 'hook)
549 (defvar org-modules) ; defined below
550 (defvar org-modules-loaded nil
551 "Have the modules been loaded already?")
553 (defun org-load-modules-maybe (&optional force)
554 "Load all extensions listed in `org-modules'."
555 (when (or force (not org-modules-loaded))
556 (mapc (lambda (ext)
557 (condition-case nil (require ext)
558 (error (message "Problems while trying to load feature `%s'" ext))))
559 org-modules)
560 (setq org-modules-loaded t)))
562 (defun org-set-modules (var value)
563 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
564 (set var value)
565 (when (featurep 'org)
566 (org-load-modules-maybe 'force)
567 (org-element-cache-reset 'all)))
569 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
570 "Modules that should always be loaded together with org.el.
572 If a description starts with <C>, the file is not part of Emacs
573 and loading it will require that you have downloaded and properly
574 installed the Org mode distribution.
576 You can also use this system to load external packages (i.e. neither Org
577 core modules, nor modules from the CONTRIB directory). Just add symbols
578 to the end of the list. If the package is called org-xyz.el, then you need
579 to add the symbol `xyz', and the package must have a call to:
581 \(provide 'org-xyz)
583 For export specific modules, see also `org-export-backends'."
584 :group 'org
585 :set 'org-set-modules
586 :version "24.4"
587 :package-version '(Org . "8.0")
588 :type
589 '(set :greedy t
590 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
591 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
592 (const :tag " crypt: Encryption of subtrees" org-crypt)
593 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
594 (const :tag " docview: Links to doc-view buffers" org-docview)
595 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
596 (const :tag " habit: Track your consistency with habits" org-habit)
597 (const :tag " id: Global IDs for identifying entries" org-id)
598 (const :tag " info: Links to Info nodes" org-info)
599 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
600 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
601 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
602 (const :tag " mouse: Additional mouse support" org-mouse)
603 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
604 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
605 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
607 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
608 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
609 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
610 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
611 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
612 (const :tag "C collector: Collect properties into tables" org-collector)
613 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
614 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
615 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
616 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
617 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
618 (const :tag "C eval: Include command output as text" org-eval)
619 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
620 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
621 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
622 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
623 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
624 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
625 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
626 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
627 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
628 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
629 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
630 (const :tag "C mew: Links to Mew folders/messages" org-mew)
631 (const :tag "C mtags: Support for muse-like tags" org-mtags)
632 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
633 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
634 (const :tag "C registry: A registry for Org-mode links" org-registry)
635 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
636 (const :tag "C secretary: Team management with org-mode" org-secretary)
637 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
638 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
639 (const :tag "C track: Keep up with Org-mode development" org-track)
640 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
641 (const :tag "C vm: Links to VM folders/messages" org-vm)
642 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
643 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
644 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
646 (defvar org-export--registered-backends) ; From ox.el.
647 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
648 (declare-function org-export-backend-name "ox" (backend))
649 (defcustom org-export-backends '(ascii html icalendar latex)
650 "List of export back-ends that should be always available.
652 If a description starts with <C>, the file is not part of Emacs
653 and loading it will require that you have downloaded and properly
654 installed the Org mode distribution.
656 Unlike to `org-modules', libraries in this list will not be
657 loaded along with Org, but only once the export framework is
658 needed.
660 This variable needs to be set before org.el is loaded. If you
661 need to make a change while Emacs is running, use the customize
662 interface or run the following code, where VAL stands for the new
663 value of the variable, after updating it:
665 \(progn
666 \(setq org-export--registered-backends
667 \(org-remove-if-not
668 \(lambda (backend)
669 \(let ((name (org-export-backend-name backend)))
670 \(or (memq name val)
671 \(catch 'parentp
672 \(dolist (b val)
673 \(and (org-export-derived-backend-p b name)
674 \(throw 'parentp t)))))))
675 org-export--registered-backends))
676 \(let ((new-list (mapcar 'org-export-backend-name
677 org-export--registered-backends)))
678 \(dolist (backend val)
679 \(cond
680 \((not (load (format \"ox-%s\" backend) t t))
681 \(message \"Problems while trying to load export back-end `%s'\"
682 backend))
683 \((not (memq backend new-list)) (push backend new-list))))
684 \(set-default 'org-export-backends new-list)))
686 Adding a back-end to this list will also pull the back-end it
687 depends on, if any."
688 :group 'org
689 :group 'org-export
690 :version "24.4"
691 :package-version '(Org . "8.0")
692 :initialize 'custom-initialize-set
693 :set (lambda (var val)
694 (if (not (featurep 'ox)) (set-default var val)
695 ;; Any back-end not required anymore (not present in VAL and not
696 ;; a parent of any back-end in the new value) is removed from the
697 ;; list of registered back-ends.
698 (setq org-export--registered-backends
699 (org-remove-if-not
700 (lambda (backend)
701 (let ((name (org-export-backend-name backend)))
702 (or (memq name val)
703 (catch 'parentp
704 (dolist (b val)
705 (and (org-export-derived-backend-p b name)
706 (throw 'parentp t)))))))
707 org-export--registered-backends))
708 ;; Now build NEW-LIST of both new back-ends and required
709 ;; parents.
710 (let ((new-list (mapcar 'org-export-backend-name
711 org-export--registered-backends)))
712 (dolist (backend val)
713 (cond
714 ((not (load (format "ox-%s" backend) t t))
715 (message "Problems while trying to load export back-end `%s'"
716 backend))
717 ((not (memq backend new-list)) (push backend new-list))))
718 ;; Set VAR to that list with fixed dependencies.
719 (set-default var new-list))))
720 :type '(set :greedy t
721 (const :tag " ascii Export buffer to ASCII format" ascii)
722 (const :tag " beamer Export buffer to Beamer presentation" beamer)
723 (const :tag " html Export buffer to HTML format" html)
724 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
725 (const :tag " latex Export buffer to LaTeX format" latex)
726 (const :tag " man Export buffer to MAN format" man)
727 (const :tag " md Export buffer to Markdown format" md)
728 (const :tag " odt Export buffer to ODT format" odt)
729 (const :tag " org Export buffer to Org format" org)
730 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
731 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
732 (const :tag "C deck Export buffer to deck.js presentations" deck)
733 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
734 (const :tag "C groff Export buffer to Groff format" groff)
735 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
736 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
737 (const :tag "C s5 Export buffer to s5 presentations" s5)
738 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
740 (eval-after-load 'ox
741 '(mapc
742 (lambda (backend)
743 (condition-case nil (require (intern (format "ox-%s" backend)))
744 (error (message "Problems while trying to load export back-end `%s'"
745 backend))))
746 org-export-backends))
748 (defcustom org-support-shift-select nil
749 "Non-nil means make shift-cursor commands select text when possible.
751 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
752 start selecting a region, or enlarge regions started in this way.
753 In Org-mode, in special contexts, these same keys are used for
754 other purposes, important enough to compete with shift selection.
755 Org tries to balance these needs by supporting `shift-select-mode'
756 outside these special contexts, under control of this variable.
758 The default of this variable is nil, to avoid confusing behavior. Shifted
759 cursor keys will then execute Org commands in the following contexts:
760 - on a headline, changing TODO state (left/right) and priority (up/down)
761 - on a time stamp, changing the time
762 - in a plain list item, changing the bullet type
763 - in a property definition line, switching between allowed values
764 - in the BEGIN line of a clock table (changing the time block).
765 Outside these contexts, the commands will throw an error.
767 When this variable is t and the cursor is not in a special
768 context, Org-mode will support shift-selection for making and
769 enlarging regions. To make this more effective, the bullet
770 cycling will no longer happen anywhere in an item line, but only
771 if the cursor is exactly on the bullet.
773 If you set this variable to the symbol `always', then the keys
774 will not be special in headlines, property lines, and item lines,
775 to make shift selection work there as well. If this is what you
776 want, you can use the following alternative commands: `C-c C-t'
777 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
778 can be used to switch TODO sets, `C-c -' to cycle item bullet
779 types, and properties can be edited by hand or in column view.
781 However, when the cursor is on a timestamp, shift-cursor commands
782 will still edit the time stamp - this is just too good to give up.
784 XEmacs user should have this variable set to nil, because
785 `shift-select-mode' is in Emacs 23 or later only."
786 :group 'org
787 :type '(choice
788 (const :tag "Never" nil)
789 (const :tag "When outside special context" t)
790 (const :tag "Everywhere except timestamps" always)))
792 (defcustom org-loop-over-headlines-in-active-region nil
793 "Shall some commands act upon headlines in the active region?
795 When set to `t', some commands will be performed in all headlines
796 within the active region.
798 When set to `start-level', some commands will be performed in all
799 headlines within the active region, provided that these headlines
800 are of the same level than the first one.
802 When set to a string, those commands will be performed on the
803 matching headlines within the active region. Such string must be
804 a tags/property/todo match as it is used in the agenda tags view.
806 The list of commands is: `org-schedule', `org-deadline',
807 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
808 `org-archive-to-archive-sibling'. The archiving commands skip
809 already archived entries."
810 :type '(choice (const :tag "Don't loop" nil)
811 (const :tag "All headlines in active region" t)
812 (const :tag "In active region, headlines at the same level than the first one" start-level)
813 (string :tag "Tags/Property/Todo matcher"))
814 :version "24.1"
815 :group 'org-todo
816 :group 'org-archive)
818 (defgroup org-startup nil
819 "Options concerning startup of Org-mode."
820 :tag "Org Startup"
821 :group 'org)
823 (defcustom org-startup-folded t
824 "Non-nil means entering Org-mode will switch to OVERVIEW.
825 This can also be configured on a per-file basis by adding one of
826 the following lines anywhere in the buffer:
828 #+STARTUP: fold (or `overview', this is equivalent)
829 #+STARTUP: nofold (or `showall', this is equivalent)
830 #+STARTUP: content
831 #+STARTUP: showeverything
833 By default, this option is ignored when Org opens agenda files
834 for the first time. If you want the agenda to honor the startup
835 option, set `org-agenda-inhibit-startup' to nil."
836 :group 'org-startup
837 :type '(choice
838 (const :tag "nofold: show all" nil)
839 (const :tag "fold: overview" t)
840 (const :tag "content: all headlines" content)
841 (const :tag "show everything, even drawers" showeverything)))
843 (defcustom org-startup-truncated t
844 "Non-nil means entering Org-mode will set `truncate-lines'.
845 This is useful since some lines containing links can be very long and
846 uninteresting. Also tables look terrible when wrapped."
847 :group 'org-startup
848 :type 'boolean)
850 (defcustom org-startup-indented nil
851 "Non-nil means turn on `org-indent-mode' on startup.
852 This can also be configured on a per-file basis by adding one of
853 the following lines anywhere in the buffer:
855 #+STARTUP: indent
856 #+STARTUP: noindent"
857 :group 'org-structure
858 :type '(choice
859 (const :tag "Not" nil)
860 (const :tag "Globally (slow on startup in large files)" t)))
862 (defcustom org-use-sub-superscripts t
863 "Non-nil means interpret \"_\" and \"^\" for display.
865 If you want to control how Org exports those characters, see
866 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
867 used to be an alias for `org-export-with-sub-superscripts' in
868 Org <8.0, it is not anymore.
870 When this option is turned on, you can use TeX-like syntax for
871 sub- and superscripts within the buffer. Several characters after
872 \"_\" or \"^\" will be considered as a single item - so grouping
873 with {} is normally not needed. For example, the following things
874 will be parsed as single sub- or superscripts:
876 10^24 or 10^tau several digits will be considered 1 item.
877 10^-12 or 10^-tau a leading sign with digits or a word
878 x^2-y^3 will be read as x^2 - y^3, because items are
879 terminated by almost any nonword/nondigit char.
880 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
882 Still, ambiguity is possible. So when in doubt, use {} to enclose
883 the sub/superscript. If you set this variable to the symbol `{}',
884 the braces are *required* in order to trigger interpretations as
885 sub/superscript. This can be helpful in documents that need \"_\"
886 frequently in plain text."
887 :group 'org-startup
888 :version "24.4"
889 :package-version '(Org . "8.0")
890 :type '(choice
891 (const :tag "Always interpret" t)
892 (const :tag "Only with braces" {})
893 (const :tag "Never interpret" nil)))
895 (defcustom org-startup-with-beamer-mode nil
896 "Non-nil means turn on `org-beamer-mode' on startup.
897 This can also be configured on a per-file basis by adding one of
898 the following lines anywhere in the buffer:
900 #+STARTUP: beamer"
901 :group 'org-startup
902 :version "24.1"
903 :type 'boolean)
905 (defcustom org-startup-align-all-tables nil
906 "Non-nil means align all tables when visiting a file.
907 This is useful when the column width in tables is forced with <N> cookies
908 in table fields. Such tables will look correct only after the first re-align.
909 This can also be configured on a per-file basis by adding one of
910 the following lines anywhere in the buffer:
911 #+STARTUP: align
912 #+STARTUP: noalign"
913 :group 'org-startup
914 :type 'boolean)
916 (defcustom org-startup-with-inline-images nil
917 "Non-nil means show inline images when loading a new Org file.
918 This can also be configured on a per-file basis by adding one of
919 the following lines anywhere in the buffer:
920 #+STARTUP: inlineimages
921 #+STARTUP: noinlineimages"
922 :group 'org-startup
923 :version "24.1"
924 :type 'boolean)
926 (defcustom org-startup-with-latex-preview nil
927 "Non-nil means preview LaTeX fragments when loading a new Org file.
929 This can also be configured on a per-file basis by adding one of
930 the following lines anywhere in the buffer:
931 #+STARTUP: latexpreview
932 #+STARTUP: nolatexpreview"
933 :group 'org-startup
934 :version "24.4"
935 :package-version '(Org . "8.0")
936 :type 'boolean)
938 (defcustom org-insert-mode-line-in-empty-file nil
939 "Non-nil means insert the first line setting Org-mode in empty files.
940 When the function `org-mode' is called interactively in an empty file, this
941 normally means that the file name does not automatically trigger Org-mode.
942 To ensure that the file will always be in Org-mode in the future, a
943 line enforcing Org-mode will be inserted into the buffer, if this option
944 has been set."
945 :group 'org-startup
946 :type 'boolean)
948 (defcustom org-replace-disputed-keys nil
949 "Non-nil means use alternative key bindings for some keys.
950 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
951 These keys are also used by other packages like shift-selection-mode'
952 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
953 If you want to use Org-mode together with one of these other modes,
954 or more generally if you would like to move some Org-mode commands to
955 other keys, set this variable and configure the keys with the variable
956 `org-disputed-keys'.
958 This option is only relevant at load-time of Org-mode, and must be set
959 *before* org.el is loaded. Changing it requires a restart of Emacs to
960 become effective."
961 :group 'org-startup
962 :type 'boolean)
964 (defcustom org-use-extra-keys nil
965 "Non-nil means use extra key sequence definitions for certain commands.
966 This happens automatically if you run XEmacs or if `window-system'
967 is nil. This variable lets you do the same manually. You must
968 set it before loading org.
970 Example: on Carbon Emacs 22 running graphically, with an external
971 keyboard on a Powerbook, the default way of setting M-left might
972 not work for either Alt or ESC. Setting this variable will make
973 it work for ESC."
974 :group 'org-startup
975 :type 'boolean)
977 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
979 (defcustom org-disputed-keys
980 '(([(shift up)] . [(meta p)])
981 ([(shift down)] . [(meta n)])
982 ([(shift left)] . [(meta -)])
983 ([(shift right)] . [(meta +)])
984 ([(control shift right)] . [(meta shift +)])
985 ([(control shift left)] . [(meta shift -)]))
986 "Keys for which Org-mode and other modes compete.
987 This is an alist, cars are the default keys, second element specifies
988 the alternative to use when `org-replace-disputed-keys' is t.
990 Keys can be specified in any syntax supported by `define-key'.
991 The value of this option takes effect only at Org-mode's startup,
992 therefore you'll have to restart Emacs to apply it after changing."
993 :group 'org-startup
994 :type 'alist)
996 (defun org-key (key)
997 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
998 Or return the original if not disputed.
999 Also apply the translations defined in `org-xemacs-key-equivalents'."
1000 (when org-replace-disputed-keys
1001 (let* ((nkey (key-description key))
1002 (x (org-find-if (lambda (x)
1003 (equal (key-description (car x)) nkey))
1004 org-disputed-keys)))
1005 (setq key (if x (cdr x) key))))
1006 (when (featurep 'xemacs)
1007 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1008 key)
1010 (defun org-find-if (predicate seq)
1011 (catch 'exit
1012 (while seq
1013 (if (funcall predicate (car seq))
1014 (throw 'exit (car seq))
1015 (pop seq)))))
1017 (defun org-defkey (keymap key def)
1018 "Define a key, possibly translated, as returned by `org-key'."
1019 (define-key keymap (org-key key) def))
1021 (defcustom org-ellipsis nil
1022 "The ellipsis to use in the Org-mode outline.
1023 When nil, just use the standard three dots.
1024 When a string, use that string instead.
1025 When a face, use the standard 3 dots, but with the specified face.
1026 The change affects only Org-mode (which will then use its own display table).
1027 Changing this requires executing `M-x org-mode RET' in a buffer to become
1028 effective."
1029 :group 'org-startup
1030 :type '(choice (const :tag "Default" nil)
1031 (face :tag "Face" :value org-warning)
1032 (string :tag "String" :value "...#")))
1034 (defvar org-display-table nil
1035 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1037 (defgroup org-keywords nil
1038 "Keywords in Org-mode."
1039 :tag "Org Keywords"
1040 :group 'org)
1042 (defcustom org-closed-keep-when-no-todo nil
1043 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1044 :group 'org-todo
1045 :group 'org-keywords
1046 :version "24.4"
1047 :package-version '(Org . "8.0")
1048 :type 'boolean)
1050 (defgroup org-structure nil
1051 "Options concerning the general structure of Org-mode files."
1052 :tag "Org Structure"
1053 :group 'org)
1055 (defgroup org-reveal-location nil
1056 "Options about how to make context of a location visible."
1057 :tag "Org Reveal Location"
1058 :group 'org-structure)
1060 (defconst org-context-choice
1061 '(choice
1062 (const :tag "Always" t)
1063 (const :tag "Never" nil)
1064 (repeat :greedy t :tag "Individual contexts"
1065 (cons
1066 (choice :tag "Context"
1067 (const agenda)
1068 (const org-goto)
1069 (const occur-tree)
1070 (const tags-tree)
1071 (const link-search)
1072 (const mark-goto)
1073 (const bookmark-jump)
1074 (const isearch)
1075 (const default))
1076 (boolean))))
1077 "Contexts for the reveal options.")
1079 (defcustom org-show-hierarchy-above '((default . t))
1080 "Non-nil means show full hierarchy when revealing a location.
1081 Org-mode often shows locations in an org-mode file which might have
1082 been invisible before. When this is set, the hierarchy of headings
1083 above the exposed location is shown.
1084 Turning this off for example for sparse trees makes them very compact.
1085 Instead of t, this can also be an alist specifying this option for different
1086 contexts. Valid contexts are
1087 agenda when exposing an entry from the agenda
1088 org-goto when using the command `org-goto' on key C-c C-j
1089 occur-tree when using the command `org-occur' on key C-c /
1090 tags-tree when constructing a sparse tree based on tags matches
1091 link-search when exposing search matches associated with a link
1092 mark-goto when exposing the jump goal of a mark
1093 bookmark-jump when exposing a bookmark location
1094 isearch when exiting from an incremental search
1095 default default for all contexts not set explicitly"
1096 :group 'org-reveal-location
1097 :type org-context-choice)
1099 (defcustom org-show-following-heading '((default . nil))
1100 "Non-nil means show following heading when revealing a location.
1101 Org-mode often shows locations in an org-mode file which might have
1102 been invisible before. When this is set, the heading following the
1103 match is shown.
1104 Turning this off for example for sparse trees makes them very compact,
1105 but makes it harder to edit the location of the match. In such a case,
1106 use the command \\[org-reveal] to show more context.
1107 Instead of t, this can also be an alist specifying this option for different
1108 contexts. See `org-show-hierarchy-above' for valid contexts."
1109 :group 'org-reveal-location
1110 :type org-context-choice)
1112 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
1113 "Non-nil means show all sibling heading when revealing a location.
1114 Org-mode often shows locations in an org-mode file which might have
1115 been invisible before. When this is set, the sibling of the current entry
1116 heading are all made visible. If `org-show-hierarchy-above' is t,
1117 the same happens on each level of the hierarchy above the current entry.
1119 By default this is on for the isearch context, off for all other contexts.
1120 Turning this off for example for sparse trees makes them very compact,
1121 but makes it harder to edit the location of the match. In such a case,
1122 use the command \\[org-reveal] to show more context.
1123 Instead of t, this can also be an alist specifying this option for different
1124 contexts. See `org-show-hierarchy-above' for valid contexts."
1125 :group 'org-reveal-location
1126 :type org-context-choice
1127 :version "24.4"
1128 :package-version '(Org . "8.0"))
1130 (defcustom org-show-entry-below '((default . nil))
1131 "Non-nil means show the entry below a headline when revealing a location.
1132 Org-mode often shows locations in an org-mode file which might have
1133 been invisible before. When this is set, the text below the headline that is
1134 exposed is also shown.
1136 By default this is off for all contexts.
1137 Instead of t, this can also be an alist specifying this option for different
1138 contexts. See `org-show-hierarchy-above' for valid contexts."
1139 :group 'org-reveal-location
1140 :type org-context-choice)
1142 (defcustom org-indirect-buffer-display 'other-window
1143 "How should indirect tree buffers be displayed?
1144 This applies to indirect buffers created with the commands
1145 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1146 Valid values are:
1147 current-window Display in the current window
1148 other-window Just display in another window.
1149 dedicated-frame Create one new frame, and re-use it each time.
1150 new-frame Make a new frame each time. Note that in this case
1151 previously-made indirect buffers are kept, and you need to
1152 kill these buffers yourself."
1153 :group 'org-structure
1154 :group 'org-agenda-windows
1155 :type '(choice
1156 (const :tag "In current window" current-window)
1157 (const :tag "In current frame, other window" other-window)
1158 (const :tag "Each time a new frame" new-frame)
1159 (const :tag "One dedicated frame" dedicated-frame)))
1161 (defcustom org-use-speed-commands nil
1162 "Non-nil means activate single letter commands at beginning of a headline.
1163 This may also be a function to test for appropriate locations where speed
1164 commands should be active.
1166 For example, to activate speed commands when the point is on any
1167 star at the beginning of the headline, you can do this:
1169 (setq org-use-speed-commands
1170 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1171 :group 'org-structure
1172 :type '(choice
1173 (const :tag "Never" nil)
1174 (const :tag "At beginning of headline stars" t)
1175 (function)))
1177 (defcustom org-speed-commands-user nil
1178 "Alist of additional speed commands.
1179 This list will be checked before `org-speed-commands-default'
1180 when the variable `org-use-speed-commands' is non-nil
1181 and when the cursor is at the beginning of a headline.
1182 The car if each entry is a string with a single letter, which must
1183 be assigned to `self-insert-command' in the global map.
1184 The cdr is either a command to be called interactively, a function
1185 to be called, or a form to be evaluated.
1186 An entry that is just a list with a single string will be interpreted
1187 as a descriptive headline that will be added when listing the speed
1188 commands in the Help buffer using the `?' speed command."
1189 :group 'org-structure
1190 :type '(repeat :value ("k" . ignore)
1191 (choice :value ("k" . ignore)
1192 (list :tag "Descriptive Headline" (string :tag "Headline"))
1193 (cons :tag "Letter and Command"
1194 (string :tag "Command letter")
1195 (choice
1196 (function)
1197 (sexp))))))
1199 (defcustom org-bookmark-names-plist
1200 '(:last-capture "org-capture-last-stored"
1201 :last-refile "org-refile-last-stored"
1202 :last-capture-marker "org-capture-last-stored-marker")
1203 "Names for bookmarks automatically set by some Org commands.
1204 This can provide strings as names for a number of bookmarks Org sets
1205 automatically. The following keys are currently implemented:
1206 :last-capture
1207 :last-capture-marker
1208 :last-refile
1209 When a key does not show up in the property list, the corresponding bookmark
1210 is not set."
1211 :group 'org-structure
1212 :type 'plist)
1214 (defgroup org-cycle nil
1215 "Options concerning visibility cycling in Org-mode."
1216 :tag "Org Cycle"
1217 :group 'org-structure)
1219 (defcustom org-cycle-skip-children-state-if-no-children t
1220 "Non-nil means skip CHILDREN state in entries that don't have any."
1221 :group 'org-cycle
1222 :type 'boolean)
1224 (defcustom org-cycle-max-level nil
1225 "Maximum level which should still be subject to visibility cycling.
1226 Levels higher than this will, for cycling, be treated as text, not a headline.
1227 When `org-odd-levels-only' is set, a value of N in this variable actually
1228 means 2N-1 stars as the limiting headline.
1229 When nil, cycle all levels.
1230 Note that the limiting level of cycling is also influenced by
1231 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1232 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1233 than its value."
1234 :group 'org-cycle
1235 :type '(choice
1236 (const :tag "No limit" nil)
1237 (integer :tag "Maximum level")))
1239 (defcustom org-hide-block-startup nil
1240 "Non-nil means entering Org-mode will fold all blocks.
1241 This can also be set in on a per-file basis with
1243 #+STARTUP: hideblocks
1244 #+STARTUP: showblocks"
1245 :group 'org-startup
1246 :group 'org-cycle
1247 :type 'boolean)
1249 (defcustom org-cycle-global-at-bob nil
1250 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1251 This makes it possible to do global cycling without having to use S-TAB or
1252 \\[universal-argument] TAB. For this special case to work, the first line
1253 of the buffer must not be a headline -- it may be empty or some other text.
1254 When used in this way, `org-cycle-hook' is disabled temporarily to make
1255 sure the cursor stays at the beginning of the buffer. When this option is
1256 nil, don't do anything special at the beginning of the buffer."
1257 :group 'org-cycle
1258 :type 'boolean)
1260 (defcustom org-cycle-level-after-item/entry-creation t
1261 "Non-nil means cycle entry level or item indentation in new empty entries.
1263 When the cursor is at the end of an empty headline, i.e., with only stars
1264 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1265 and then all possible ancestor states, before returning to the original state.
1266 This makes data entry extremely fast: M-RET to create a new headline,
1267 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1269 When the cursor is at the end of an empty plain list item, one TAB will
1270 make it a subitem, two or more tabs will back up to make this an item
1271 higher up in the item hierarchy."
1272 :group 'org-cycle
1273 :type 'boolean)
1275 (defcustom org-cycle-emulate-tab t
1276 "Where should `org-cycle' emulate TAB.
1277 nil Never
1278 white Only in completely white lines
1279 whitestart Only at the beginning of lines, before the first non-white char
1280 t Everywhere except in headlines
1281 exc-hl-bol Everywhere except at the start of a headline
1282 If TAB is used in a place where it does not emulate TAB, the current subtree
1283 visibility is cycled."
1284 :group 'org-cycle
1285 :type '(choice (const :tag "Never" nil)
1286 (const :tag "Only in completely white lines" white)
1287 (const :tag "Before first char in a line" whitestart)
1288 (const :tag "Everywhere except in headlines" t)
1289 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1291 (defcustom org-cycle-separator-lines 2
1292 "Number of empty lines needed to keep an empty line between collapsed trees.
1293 If you leave an empty line between the end of a subtree and the following
1294 headline, this empty line is hidden when the subtree is folded.
1295 Org-mode will leave (exactly) one empty line visible if the number of
1296 empty lines is equal or larger to the number given in this variable.
1297 So the default 2 means at least 2 empty lines after the end of a subtree
1298 are needed to produce free space between a collapsed subtree and the
1299 following headline.
1301 If the number is negative, and the number of empty lines is at least -N,
1302 all empty lines are shown.
1304 Special case: when 0, never leave empty lines in collapsed view."
1305 :group 'org-cycle
1306 :type 'integer)
1307 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1309 (defcustom org-pre-cycle-hook nil
1310 "Hook that is run before visibility cycling is happening.
1311 The function(s) in this hook must accept a single argument which indicates
1312 the new state that will be set right after running this hook. The
1313 argument is a symbol. Before a global state change, it can have the values
1314 `overview', `content', or `all'. Before a local state change, it can have
1315 the values `folded', `children', or `subtree'."
1316 :group 'org-cycle
1317 :type 'hook)
1319 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1320 org-cycle-hide-drawers
1321 org-cycle-hide-inline-tasks
1322 org-cycle-show-empty-lines
1323 org-optimize-window-after-visibility-change)
1324 "Hook that is run after `org-cycle' has changed the buffer visibility.
1325 The function(s) in this hook must accept a single argument which indicates
1326 the new state that was set by the most recent `org-cycle' command. The
1327 argument is a symbol. After a global state change, it can have the values
1328 `overview', `contents', or `all'. After a local state change, it can have
1329 the values `folded', `children', or `subtree'."
1330 :group 'org-cycle
1331 :type 'hook)
1333 (defgroup org-edit-structure nil
1334 "Options concerning structure editing in Org-mode."
1335 :tag "Org Edit Structure"
1336 :group 'org-structure)
1338 (defcustom org-odd-levels-only nil
1339 "Non-nil means skip even levels and only use odd levels for the outline.
1340 This has the effect that two stars are being added/taken away in
1341 promotion/demotion commands. It also influences how levels are
1342 handled by the exporters.
1343 Changing it requires restart of `font-lock-mode' to become effective
1344 for fontification also in regions already fontified.
1345 You may also set this on a per-file basis by adding one of the following
1346 lines to the buffer:
1348 #+STARTUP: odd
1349 #+STARTUP: oddeven"
1350 :group 'org-edit-structure
1351 :group 'org-appearance
1352 :type 'boolean)
1354 (defcustom org-adapt-indentation t
1355 "Non-nil means adapt indentation to outline node level.
1357 When this variable is set, Org assumes that you write outlines by
1358 indenting text in each node to align with the headline (after the stars).
1359 The following issues are influenced by this variable:
1361 - When this is set and the *entire* text in an entry is indented, the
1362 indentation is increased by one space in a demotion command, and
1363 decreased by one in a promotion command. If any line in the entry
1364 body starts with text at column 0, indentation is not changed at all.
1366 - Property drawers and planning information is inserted indented when
1367 this variable s set. When nil, they will not be indented.
1369 - TAB indents a line relative to context. The lines below a headline
1370 will be indented when this variable is set.
1372 Note that this is all about true indentation, by adding and removing
1373 space characters. See also `org-indent.el' which does level-dependent
1374 indentation in a virtual way, i.e. at display time in Emacs."
1375 :group 'org-edit-structure
1376 :type 'boolean)
1378 (defcustom org-special-ctrl-a/e nil
1379 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1381 When t, `C-a' will bring back the cursor to the beginning of the
1382 headline text, i.e. after the stars and after a possible TODO
1383 keyword. In an item, this will be the position after bullet and
1384 check-box, if any. When the cursor is already at that position,
1385 another `C-a' will bring it to the beginning of the line.
1387 `C-e' will jump to the end of the headline, ignoring the presence
1388 of tags in the headline. A second `C-e' will then jump to the
1389 true end of the line, after any tags. This also means that, when
1390 this variable is non-nil, `C-e' also will never jump beyond the
1391 end of the heading of a folded section, i.e. not after the
1392 ellipses.
1394 When set to the symbol `reversed', the first `C-a' or `C-e' works
1395 normally, going to the true line boundary first. Only a directly
1396 following, identical keypress will bring the cursor to the
1397 special positions.
1399 This may also be a cons cell where the behavior for `C-a' and
1400 `C-e' is set separately."
1401 :group 'org-edit-structure
1402 :type '(choice
1403 (const :tag "off" nil)
1404 (const :tag "on: after stars/bullet and before tags first" t)
1405 (const :tag "reversed: true line boundary first" reversed)
1406 (cons :tag "Set C-a and C-e separately"
1407 (choice :tag "Special C-a"
1408 (const :tag "off" nil)
1409 (const :tag "on: after stars/bullet first" t)
1410 (const :tag "reversed: before stars/bullet first" reversed))
1411 (choice :tag "Special C-e"
1412 (const :tag "off" nil)
1413 (const :tag "on: before tags first" t)
1414 (const :tag "reversed: after tags first" reversed)))))
1415 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1417 (defcustom org-special-ctrl-k nil
1418 "Non-nil means `C-k' will behave specially in headlines.
1419 When nil, `C-k' will call the default `kill-line' command.
1420 When t, the following will happen while the cursor is in the headline:
1422 - When the cursor is at the beginning of a headline, kill the entire
1423 line and possible the folded subtree below the line.
1424 - When in the middle of the headline text, kill the headline up to the tags.
1425 - When after the headline text, kill the tags."
1426 :group 'org-edit-structure
1427 :type 'boolean)
1429 (defcustom org-ctrl-k-protect-subtree nil
1430 "Non-nil means, do not delete a hidden subtree with C-k.
1431 When set to the symbol `error', simply throw an error when C-k is
1432 used to kill (part-of) a headline that has hidden text behind it.
1433 Any other non-nil value will result in a query to the user, if it is
1434 OK to kill that hidden subtree. When nil, kill without remorse."
1435 :group 'org-edit-structure
1436 :version "24.1"
1437 :type '(choice
1438 (const :tag "Do not protect hidden subtrees" nil)
1439 (const :tag "Protect hidden subtrees with a security query" t)
1440 (const :tag "Never kill a hidden subtree with C-k" error)))
1442 (defcustom org-special-ctrl-o t
1443 "Non-nil means, make `C-o' insert a row in tables."
1444 :group 'org-edit-structure
1445 :type 'boolean)
1447 (defcustom org-catch-invisible-edits nil
1448 "Check if in invisible region before inserting or deleting a character.
1449 Valid values are:
1451 nil Do not check, so just do invisible edits.
1452 error Throw an error and do nothing.
1453 show Make point visible, and do the requested edit.
1454 show-and-error Make point visible, then throw an error and abort the edit.
1455 smart Make point visible, and do insertion/deletion if it is
1456 adjacent to visible text and the change feels predictable.
1457 Never delete a previously invisible character or add in the
1458 middle or right after an invisible region. Basically, this
1459 allows insertion and backward-delete right before ellipses.
1460 FIXME: maybe in this case we should not even show?"
1461 :group 'org-edit-structure
1462 :version "24.1"
1463 :type '(choice
1464 (const :tag "Do not check" nil)
1465 (const :tag "Throw error when trying to edit" error)
1466 (const :tag "Unhide, but do not do the edit" show-and-error)
1467 (const :tag "Show invisible part and do the edit" show)
1468 (const :tag "Be smart and do the right thing" smart)))
1470 (defcustom org-yank-folded-subtrees t
1471 "Non-nil means when yanking subtrees, fold them.
1472 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1473 it starts with a heading and all other headings in it are either children
1474 or siblings, then fold all the subtrees. However, do this only if no
1475 text after the yank would be swallowed into a folded tree by this action."
1476 :group 'org-edit-structure
1477 :type 'boolean)
1479 (defcustom org-yank-adjusted-subtrees nil
1480 "Non-nil means when yanking subtrees, adjust the level.
1481 With this setting, `org-paste-subtree' is used to insert the subtree, see
1482 this function for details."
1483 :group 'org-edit-structure
1484 :type 'boolean)
1486 (defcustom org-M-RET-may-split-line '((default . t))
1487 "Non-nil means M-RET will split the line at the cursor position.
1488 When nil, it will go to the end of the line before making a
1489 new line.
1490 You may also set this option in a different way for different
1491 contexts. Valid contexts are:
1493 headline when creating a new headline
1494 item when creating a new item
1495 table in a table field
1496 default the value to be used for all contexts not explicitly
1497 customized"
1498 :group 'org-structure
1499 :group 'org-table
1500 :type '(choice
1501 (const :tag "Always" t)
1502 (const :tag "Never" nil)
1503 (repeat :greedy t :tag "Individual contexts"
1504 (cons
1505 (choice :tag "Context"
1506 (const headline)
1507 (const item)
1508 (const table)
1509 (const default))
1510 (boolean)))))
1513 (defcustom org-insert-heading-respect-content nil
1514 "Non-nil means insert new headings after the current subtree.
1515 When nil, the new heading is created directly after the current line.
1516 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1517 this variable on for the duration of the command."
1518 :group 'org-structure
1519 :type 'boolean)
1521 (defcustom org-blank-before-new-entry '((heading . auto)
1522 (plain-list-item . auto))
1523 "Should `org-insert-heading' leave a blank line before new heading/item?
1524 The value is an alist, with `heading' and `plain-list-item' as CAR,
1525 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1526 which case Org will look at the surrounding headings/items and try to
1527 make an intelligent decision whether to insert a blank line or not.
1529 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1530 the setting here is ignored and no empty line is inserted to avoid breaking
1531 the list structure."
1532 :group 'org-edit-structure
1533 :type '(list
1534 (cons (const heading)
1535 (choice (const :tag "Never" nil)
1536 (const :tag "Always" t)
1537 (const :tag "Auto" auto)))
1538 (cons (const plain-list-item)
1539 (choice (const :tag "Never" nil)
1540 (const :tag "Always" t)
1541 (const :tag "Auto" auto)))))
1543 (defcustom org-insert-heading-hook nil
1544 "Hook being run after inserting a new heading."
1545 :group 'org-edit-structure
1546 :type 'hook)
1548 (defcustom org-enable-fixed-width-editor t
1549 "Non-nil means lines starting with \":\" are treated as fixed-width.
1550 This currently only means they are never auto-wrapped.
1551 When nil, such lines will be treated like ordinary lines."
1552 :group 'org-edit-structure
1553 :type 'boolean)
1555 (defcustom org-goto-auto-isearch t
1556 "Non-nil means typing characters in `org-goto' starts incremental search.
1557 When nil, you can use these keybindings to navigate the buffer:
1559 q Quit the org-goto interface
1560 n Go to the next visible heading
1561 p Go to the previous visible heading
1562 f Go one heading forward on same level
1563 b Go one heading backward on same level
1564 u Go one heading up"
1565 :group 'org-edit-structure
1566 :type 'boolean)
1568 (defgroup org-sparse-trees nil
1569 "Options concerning sparse trees in Org-mode."
1570 :tag "Org Sparse Trees"
1571 :group 'org-structure)
1573 (defcustom org-highlight-sparse-tree-matches t
1574 "Non-nil means highlight all matches that define a sparse tree.
1575 The highlights will automatically disappear the next time the buffer is
1576 changed by an edit command."
1577 :group 'org-sparse-trees
1578 :type 'boolean)
1580 (defcustom org-remove-highlights-with-change t
1581 "Non-nil means any change to the buffer will remove temporary highlights.
1582 Such highlights are created by `org-occur' and `org-clock-display'.
1583 When nil, `C-c C-c needs to be used to get rid of the highlights.
1584 The highlights created by `org-preview-latex-fragment' always need
1585 `C-c C-c' to be removed."
1586 :group 'org-sparse-trees
1587 :group 'org-time
1588 :type 'boolean)
1591 (defcustom org-occur-hook '(org-first-headline-recenter)
1592 "Hook that is run after `org-occur' has constructed a sparse tree.
1593 This can be used to recenter the window to show as much of the structure
1594 as possible."
1595 :group 'org-sparse-trees
1596 :type 'hook)
1598 (defgroup org-imenu-and-speedbar nil
1599 "Options concerning imenu and speedbar in Org-mode."
1600 :tag "Org Imenu and Speedbar"
1601 :group 'org-structure)
1603 (defcustom org-imenu-depth 2
1604 "The maximum level for Imenu access to Org-mode headlines.
1605 This also applied for speedbar access."
1606 :group 'org-imenu-and-speedbar
1607 :type 'integer)
1609 (defgroup org-table nil
1610 "Options concerning tables in Org-mode."
1611 :tag "Org Table"
1612 :group 'org)
1614 (defcustom org-enable-table-editor 'optimized
1615 "Non-nil means lines starting with \"|\" are handled by the table editor.
1616 When nil, such lines will be treated like ordinary lines.
1618 When equal to the symbol `optimized', the table editor will be optimized to
1619 do the following:
1620 - Automatic overwrite mode in front of whitespace in table fields.
1621 This makes the structure of the table stay in tact as long as the edited
1622 field does not exceed the column width.
1623 - Minimize the number of realigns. Normally, the table is aligned each time
1624 TAB or RET are pressed to move to another field. With optimization this
1625 happens only if changes to a field might have changed the column width.
1626 Optimization requires replacing the functions `self-insert-command',
1627 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1628 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1629 very good at guessing when a re-align will be necessary, but you can always
1630 force one with \\[org-ctrl-c-ctrl-c].
1632 If you would like to use the optimized version in Org-mode, but the
1633 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1635 This variable can be used to turn on and off the table editor during a session,
1636 but in order to toggle optimization, a restart is required.
1638 See also the variable `org-table-auto-blank-field'."
1639 :group 'org-table
1640 :type '(choice
1641 (const :tag "off" nil)
1642 (const :tag "on" t)
1643 (const :tag "on, optimized" optimized)))
1645 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1646 (version<= emacs-version "24.1"))
1647 "Non-nil means cluster self-insert commands for undo when possible.
1648 If this is set, then, like in the Emacs command loop, 20 consecutive
1649 characters will be undone together.
1650 This is configurable, because there is some impact on typing performance."
1651 :group 'org-table
1652 :type 'boolean)
1654 (defcustom org-table-tab-recognizes-table.el t
1655 "Non-nil means TAB will automatically notice a table.el table.
1656 When it sees such a table, it moves point into it and - if necessary -
1657 calls `table-recognize-table'."
1658 :group 'org-table-editing
1659 :type 'boolean)
1661 (defgroup org-link nil
1662 "Options concerning links in Org-mode."
1663 :tag "Org Link"
1664 :group 'org)
1666 (defvar org-link-abbrev-alist-local nil
1667 "Buffer-local version of `org-link-abbrev-alist', which see.
1668 The value of this is taken from the #+LINK lines.")
1669 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1671 (defcustom org-link-abbrev-alist nil
1672 "Alist of link abbreviations.
1673 The car of each element is a string, to be replaced at the start of a link.
1674 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1675 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1677 [[linkkey:tag][description]]
1679 The 'linkkey' must be a word word, starting with a letter, followed
1680 by letters, numbers, '-' or '_'.
1682 If REPLACE is a string, the tag will simply be appended to create the link.
1683 If the string contains \"%s\", the tag will be inserted there. If the string
1684 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1685 at that point (see the function `url-hexify-string'). If the string contains
1686 the specifier \"%(my-function)\", then the custom function `my-function' will
1687 be invoked: this function takes the tag as its only argument and must return
1688 a string.
1690 REPLACE may also be a function that will be called with the tag as the
1691 only argument to create the link, which should be returned as a string.
1693 See the manual for examples."
1694 :group 'org-link
1695 :type '(repeat
1696 (cons
1697 (string :tag "Protocol")
1698 (choice
1699 (string :tag "Format")
1700 (function)))))
1702 (defcustom org-descriptive-links t
1703 "Non-nil means Org will display descriptive links.
1704 E.g. [[http://orgmode.org][Org website]] will be displayed as
1705 \"Org Website\", hiding the link itself and just displaying its
1706 description. When set to `nil', Org will display the full links
1707 literally.
1709 You can interactively set the value of this variable by calling
1710 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1711 :group 'org-link
1712 :type 'boolean)
1714 (defcustom org-link-file-path-type 'adaptive
1715 "How the path name in file links should be stored.
1716 Valid values are:
1718 relative Relative to the current directory, i.e. the directory of the file
1719 into which the link is being inserted.
1720 absolute Absolute path, if possible with ~ for home directory.
1721 noabbrev Absolute path, no abbreviation of home directory.
1722 adaptive Use relative path for files in the current directory and sub-
1723 directories of it. For other files, use an absolute path."
1724 :group 'org-link
1725 :type '(choice
1726 (const relative)
1727 (const absolute)
1728 (const noabbrev)
1729 (const adaptive)))
1731 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1732 "Types of links that should be activated in Org-mode files.
1733 This is a list of symbols, each leading to the activation of a certain link
1734 type. In principle, it does not hurt to turn on most link types - there may
1735 be a small gain when turning off unused link types. The types are:
1737 bracket The recommended [[link][description]] or [[link]] links with hiding.
1738 angle Links in angular brackets that may contain whitespace like
1739 <bbdb:Carsten Dominik>.
1740 plain Plain links in normal text, no whitespace, like http://google.com.
1741 radio Text that is matched by a radio target, see manual for details.
1742 tag Tag settings in a headline (link to tag search).
1743 date Time stamps (link to calendar).
1744 footnote Footnote labels.
1746 Changing this variable requires a restart of Emacs to become effective."
1747 :group 'org-link
1748 :type '(set :greedy t
1749 (const :tag "Double bracket links" bracket)
1750 (const :tag "Angular bracket links" angle)
1751 (const :tag "Plain text links" plain)
1752 (const :tag "Radio target matches" radio)
1753 (const :tag "Tags" tag)
1754 (const :tag "Timestamps" date)
1755 (const :tag "Footnotes" footnote)))
1757 (defcustom org-make-link-description-function nil
1758 "Function to use for generating link descriptions from links.
1759 When nil, the link location will be used. This function must take
1760 two parameters: the first one is the link, the second one is the
1761 description generated by `org-insert-link'. The function should
1762 return the description to use."
1763 :group 'org-link
1764 :type '(choice (const nil) (function)))
1766 (defgroup org-link-store nil
1767 "Options concerning storing links in Org-mode."
1768 :tag "Org Store Link"
1769 :group 'org-link)
1771 (defcustom org-url-hexify-p t
1772 "When non-nil, hexify URL when creating a link."
1773 :type 'boolean
1774 :version "24.3"
1775 :group 'org-link-store)
1777 (defcustom org-email-link-description-format "Email %c: %.30s"
1778 "Format of the description part of a link to an email or usenet message.
1779 The following %-escapes will be replaced by corresponding information:
1781 %F full \"From\" field
1782 %f name, taken from \"From\" field, address if no name
1783 %T full \"To\" field
1784 %t first name in \"To\" field, address if no name
1785 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1786 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1787 %s subject
1788 %d date
1789 %m message-id.
1791 You may use normal field width specification between the % and the letter.
1792 This is for example useful to limit the length of the subject.
1794 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1795 :group 'org-link-store
1796 :type 'string)
1798 (defcustom org-from-is-user-regexp
1799 (let (r1 r2)
1800 (when (and user-mail-address (not (string= user-mail-address "")))
1801 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1802 (when (and user-full-name (not (string= user-full-name "")))
1803 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1804 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1805 "Regexp matched against the \"From:\" header of an email or usenet message.
1806 It should match if the message is from the user him/herself."
1807 :group 'org-link-store
1808 :type 'regexp)
1810 (defcustom org-context-in-file-links t
1811 "Non-nil means file links from `org-store-link' contain context.
1812 A search string will be added to the file name with :: as separator and
1813 used to find the context when the link is activated by the command
1814 `org-open-at-point'. When this option is t, the entire active region
1815 will be placed in the search string of the file link. If set to a
1816 positive integer, only the first n lines of context will be stored.
1818 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1819 negates this setting for the duration of the command."
1820 :group 'org-link-store
1821 :type '(choice boolean integer))
1823 (defcustom org-keep-stored-link-after-insertion nil
1824 "Non-nil means keep link in list for entire session.
1826 The command `org-store-link' adds a link pointing to the current
1827 location to an internal list. These links accumulate during a session.
1828 The command `org-insert-link' can be used to insert links into any
1829 Org-mode file (offering completion for all stored links). When this
1830 option is nil, every link which has been inserted once using \\[org-insert-link]
1831 will be removed from the list, to make completing the unused links
1832 more efficient."
1833 :group 'org-link-store
1834 :type 'boolean)
1836 (defgroup org-link-follow nil
1837 "Options concerning following links in Org-mode."
1838 :tag "Org Follow Link"
1839 :group 'org-link)
1841 (defcustom org-link-translation-function nil
1842 "Function to translate links with different syntax to Org syntax.
1843 This can be used to translate links created for example by the Planner
1844 or emacs-wiki packages to Org syntax.
1845 The function must accept two parameters, a TYPE containing the link
1846 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1847 which is everything after the link protocol. It should return a cons
1848 with possibly modified values of type and path.
1849 Org contains a function for this, so if you set this variable to
1850 `org-translate-link-from-planner', you should be able follow many
1851 links created by planner."
1852 :group 'org-link-follow
1853 :type '(choice (const nil) (function)))
1855 (defcustom org-follow-link-hook nil
1856 "Hook that is run after a link has been followed."
1857 :group 'org-link-follow
1858 :type 'hook)
1860 (defcustom org-tab-follows-link nil
1861 "Non-nil means on links TAB will follow the link.
1862 Needs to be set before org.el is loaded.
1863 This really should not be used, it does not make sense, and the
1864 implementation is bad."
1865 :group 'org-link-follow
1866 :type 'boolean)
1868 (defcustom org-return-follows-link nil
1869 "Non-nil means on links RET will follow the link.
1870 In tables, the special behavior of RET has precedence."
1871 :group 'org-link-follow
1872 :type 'boolean)
1874 (defcustom org-mouse-1-follows-link
1875 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1876 "Non-nil means mouse-1 on a link will follow the link.
1877 A longer mouse click will still set point. Does not work on XEmacs.
1878 Needs to be set before org.el is loaded."
1879 :group 'org-link-follow
1880 :version "24.4"
1881 :package-version '(Org . "8.3")
1882 :type '(choice
1883 (const :tag "A double click follows the link" double)
1884 (const :tag "Unconditionally follow the link with mouse-1" t)
1885 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1887 (defcustom org-mark-ring-length 4
1888 "Number of different positions to be recorded in the ring.
1889 Changing this requires a restart of Emacs to work correctly."
1890 :group 'org-link-follow
1891 :type 'integer)
1893 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1894 "Non-nil means internal links in Org files must exactly match a headline.
1895 When nil, the link search tries to match a phrase with all words
1896 in the search text."
1897 :group 'org-link-follow
1898 :version "24.1"
1899 :type '(choice
1900 (const :tag "Use fuzzy text search" nil)
1901 (const :tag "Match only exact headline" t)
1902 (const :tag "Match exact headline or query to create it"
1903 query-to-create)))
1905 (defcustom org-link-frame-setup
1906 '((vm . vm-visit-folder-other-frame)
1907 (vm-imap . vm-visit-imap-folder-other-frame)
1908 (gnus . org-gnus-no-new-news)
1909 (file . find-file-other-window)
1910 (wl . wl-other-frame))
1911 "Setup the frame configuration for following links.
1912 When following a link with Emacs, it may often be useful to display
1913 this link in another window or frame. This variable can be used to
1914 set this up for the different types of links.
1915 For VM, use any of
1916 `vm-visit-folder'
1917 `vm-visit-folder-other-window'
1918 `vm-visit-folder-other-frame'
1919 For Gnus, use any of
1920 `gnus'
1921 `gnus-other-frame'
1922 `org-gnus-no-new-news'
1923 For FILE, use any of
1924 `find-file'
1925 `find-file-other-window'
1926 `find-file-other-frame'
1927 For Wanderlust use any of
1928 `wl'
1929 `wl-other-frame'
1930 For the calendar, use the variable `calendar-setup'.
1931 For BBDB, it is currently only possible to display the matches in
1932 another window."
1933 :group 'org-link-follow
1934 :type '(list
1935 (cons (const vm)
1936 (choice
1937 (const vm-visit-folder)
1938 (const vm-visit-folder-other-window)
1939 (const vm-visit-folder-other-frame)))
1940 (cons (const vm-imap)
1941 (choice
1942 (const vm-visit-imap-folder)
1943 (const vm-visit-imap-folder-other-window)
1944 (const vm-visit-imap-folder-other-frame)))
1945 (cons (const gnus)
1946 (choice
1947 (const gnus)
1948 (const gnus-other-frame)
1949 (const org-gnus-no-new-news)))
1950 (cons (const file)
1951 (choice
1952 (const find-file)
1953 (const find-file-other-window)
1954 (const find-file-other-frame)))
1955 (cons (const wl)
1956 (choice
1957 (const wl)
1958 (const wl-other-frame)))))
1960 (defcustom org-display-internal-link-with-indirect-buffer nil
1961 "Non-nil means use indirect buffer to display infile links.
1962 Activating internal links (from one location in a file to another location
1963 in the same file) normally just jumps to the location. When the link is
1964 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1965 is displayed in
1966 another window. When this option is set, the other window actually displays
1967 an indirect buffer clone of the current buffer, to avoid any visibility
1968 changes to the current buffer."
1969 :group 'org-link-follow
1970 :type 'boolean)
1972 (defcustom org-open-non-existing-files nil
1973 "Non-nil means `org-open-file' will open non-existing files.
1974 When nil, an error will be generated.
1975 This variable applies only to external applications because they
1976 might choke on non-existing files. If the link is to a file that
1977 will be opened in Emacs, the variable is ignored."
1978 :group 'org-link-follow
1979 :type 'boolean)
1981 (defcustom org-open-directory-means-index-dot-org nil
1982 "Non-nil means a link to a directory really means to index.org.
1983 When nil, following a directory link will run dired or open a finder/explorer
1984 window on that directory."
1985 :group 'org-link-follow
1986 :type 'boolean)
1988 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1989 "Function and arguments to call for following mailto links.
1990 This is a list with the first element being a Lisp function, and the
1991 remaining elements being arguments to the function. In string arguments,
1992 %a will be replaced by the address, and %s will be replaced by the subject
1993 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1994 :group 'org-link-follow
1995 :type '(choice
1996 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1997 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1998 (const :tag "message-mail" (message-mail "%a" "%s"))
1999 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
2001 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2002 "Non-nil means ask for confirmation before executing shell links.
2003 Shell links can be dangerous: just think about a link
2005 [[shell:rm -rf ~/*][Google Search]]
2007 This link would show up in your Org-mode document as \"Google Search\",
2008 but really it would remove your entire home directory.
2009 Therefore we advise against setting this variable to nil.
2010 Just change it to `y-or-n-p' if you want to confirm with a
2011 single keystroke rather than having to type \"yes\"."
2012 :group 'org-link-follow
2013 :type '(choice
2014 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2015 (const :tag "with y-or-n (faster)" y-or-n-p)
2016 (const :tag "no confirmation (dangerous)" nil)))
2017 (put 'org-confirm-shell-link-function
2018 'safe-local-variable
2019 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2021 (defcustom org-confirm-shell-link-not-regexp ""
2022 "A regexp to skip confirmation for shell links."
2023 :group 'org-link-follow
2024 :version "24.1"
2025 :type 'regexp)
2027 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2028 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2029 Elisp links can be dangerous: just think about a link
2031 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2033 This link would show up in your Org-mode document as \"Google Search\",
2034 but really it would remove your entire home directory.
2035 Therefore we advise against setting this variable to nil.
2036 Just change it to `y-or-n-p' if you want to confirm with a
2037 single keystroke rather than having to type \"yes\"."
2038 :group 'org-link-follow
2039 :type '(choice
2040 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2041 (const :tag "with y-or-n (faster)" y-or-n-p)
2042 (const :tag "no confirmation (dangerous)" nil)))
2043 (put 'org-confirm-shell-link-function
2044 'safe-local-variable
2045 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2047 (defcustom org-confirm-elisp-link-not-regexp ""
2048 "A regexp to skip confirmation for Elisp links."
2049 :group 'org-link-follow
2050 :version "24.1"
2051 :type 'regexp)
2053 (defconst org-file-apps-defaults-gnu
2054 '((remote . emacs)
2055 (system . mailcap)
2056 (t . mailcap))
2057 "Default file applications on a UNIX or GNU/Linux system.
2058 See `org-file-apps'.")
2060 (defconst org-file-apps-defaults-macosx
2061 '((remote . emacs)
2062 (t . "open %s")
2063 (system . "open %s")
2064 ("ps.gz" . "gv %s")
2065 ("eps.gz" . "gv %s")
2066 ("dvi" . "xdvi %s")
2067 ("fig" . "xfig %s"))
2068 "Default file applications on a MacOS X system.
2069 The system \"open\" is known as a default, but we use X11 applications
2070 for some files for which the OS does not have a good default.
2071 See `org-file-apps'.")
2073 (defconst org-file-apps-defaults-windowsnt
2074 (list
2075 '(remote . emacs)
2076 (cons t
2077 (list (if (featurep 'xemacs)
2078 'mswindows-shell-execute
2079 'w32-shell-execute)
2080 "open" 'file))
2081 (cons 'system
2082 (list (if (featurep 'xemacs)
2083 'mswindows-shell-execute
2084 'w32-shell-execute)
2085 "open" 'file)))
2086 "Default file applications on a Windows NT system.
2087 The system \"open\" is used for most files.
2088 See `org-file-apps'.")
2090 (defcustom org-file-apps
2091 '((auto-mode . emacs)
2092 ("\\.mm\\'" . default)
2093 ("\\.x?html?\\'" . default)
2094 ("\\.pdf\\'" . default))
2095 "External applications for opening `file:path' items in a document.
2096 Org-mode uses system defaults for different file types, but
2097 you can use this variable to set the application for a given file
2098 extension. The entries in this list are cons cells where the car identifies
2099 files and the cdr the corresponding command. Possible values for the
2100 file identifier are
2101 \"string\" A string as a file identifier can be interpreted in different
2102 ways, depending on its contents:
2104 - Alphanumeric characters only:
2105 Match links with this file extension.
2106 Example: (\"pdf\" . \"evince %s\")
2107 to open PDFs with evince.
2109 - Regular expression: Match links where the
2110 filename matches the regexp. If you want to
2111 use groups here, use shy groups.
2113 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2114 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2115 to open *.html and *.xhtml with firefox.
2117 - Regular expression which contains (non-shy) groups:
2118 Match links where the whole link, including \"::\", and
2119 anything after that, matches the regexp.
2120 In a custom command string, %1, %2, etc. are replaced with
2121 the parts of the link that were matched by the groups.
2122 For backwards compatibility, if a command string is given
2123 that does not use any of the group matches, this case is
2124 handled identically to the second one (i.e. match against
2125 file name only).
2126 In a custom lisp form, you can access the group matches with
2127 (match-string n link).
2129 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2130 to open [[file:document.pdf::5]] with evince at page 5.
2132 `directory' Matches a directory
2133 `remote' Matches a remote file, accessible through tramp or efs.
2134 Remote files most likely should be visited through Emacs
2135 because external applications cannot handle such paths.
2136 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2137 so all files Emacs knows how to handle. Using this with
2138 command `emacs' will open most files in Emacs. Beware that this
2139 will also open html files inside Emacs, unless you add
2140 (\"html\" . default) to the list as well.
2141 t Default for files not matched by any of the other options.
2142 `system' The system command to open files, like `open' on Windows
2143 and Mac OS X, and mailcap under GNU/Linux. This is the command
2144 that will be selected if you call `C-c C-o' with a double
2145 \\[universal-argument] \\[universal-argument] prefix.
2147 Possible values for the command are:
2148 `emacs' The file will be visited by the current Emacs process.
2149 `default' Use the default application for this file type, which is the
2150 association for t in the list, most likely in the system-specific
2151 part.
2152 This can be used to overrule an unwanted setting in the
2153 system-specific variable.
2154 `system' Use the system command for opening files, like \"open\".
2155 This command is specified by the entry whose car is `system'.
2156 Most likely, the system-specific version of this variable
2157 does define this command, but you can overrule/replace it
2158 here.
2159 string A command to be executed by a shell; %s will be replaced
2160 by the path to the file.
2161 sexp A Lisp form which will be evaluated. The file path will
2162 be available in the Lisp variable `file'.
2163 For more examples, see the system specific constants
2164 `org-file-apps-defaults-macosx'
2165 `org-file-apps-defaults-windowsnt'
2166 `org-file-apps-defaults-gnu'."
2167 :group 'org-link-follow
2168 :type '(repeat
2169 (cons (choice :value ""
2170 (string :tag "Extension")
2171 (const :tag "System command to open files" system)
2172 (const :tag "Default for unrecognized files" t)
2173 (const :tag "Remote file" remote)
2174 (const :tag "Links to a directory" directory)
2175 (const :tag "Any files that have Emacs modes"
2176 auto-mode))
2177 (choice :value ""
2178 (const :tag "Visit with Emacs" emacs)
2179 (const :tag "Use default" default)
2180 (const :tag "Use the system command" system)
2181 (string :tag "Command")
2182 (sexp :tag "Lisp form")))))
2184 (defcustom org-doi-server-url "http://dx.doi.org/"
2185 "The URL of the DOI server."
2186 :type 'string
2187 :version "24.3"
2188 :group 'org-link-follow)
2190 (defgroup org-refile nil
2191 "Options concerning refiling entries in Org-mode."
2192 :tag "Org Refile"
2193 :group 'org)
2195 (defcustom org-directory "~/org"
2196 "Directory with org files.
2197 This is just a default location to look for Org files. There is no need
2198 at all to put your files into this directory. It is only used in the
2199 following situations:
2201 1. When a capture template specifies a target file that is not an
2202 absolute path. The path will then be interpreted relative to
2203 `org-directory'
2204 2. When a capture note is filed away in an interactive way (when exiting the
2205 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2206 with `org-directory' as the default path."
2207 :group 'org-refile
2208 :group 'org-capture
2209 :type 'directory)
2211 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2212 "Default target for storing notes.
2213 Used as a fall back file for org-capture.el, for templates that
2214 do not specify a target file."
2215 :group 'org-refile
2216 :group 'org-capture
2217 :type '(choice
2218 (const :tag "Default from remember-data-file" nil)
2219 file))
2221 (defcustom org-goto-interface 'outline
2222 "The default interface to be used for `org-goto'.
2223 Allowed values are:
2224 outline The interface shows an outline of the relevant file
2225 and the correct heading is found by moving through
2226 the outline or by searching with incremental search.
2227 outline-path-completion Headlines in the current buffer are offered via
2228 completion. This is the interface also used by
2229 the refile command."
2230 :group 'org-refile
2231 :type '(choice
2232 (const :tag "Outline" outline)
2233 (const :tag "Outline-path-completion" outline-path-completion)))
2235 (defcustom org-goto-max-level 5
2236 "Maximum target level when running `org-goto' with refile interface."
2237 :group 'org-refile
2238 :type 'integer)
2240 (defcustom org-reverse-note-order nil
2241 "Non-nil means store new notes at the beginning of a file or entry.
2242 When nil, new notes will be filed to the end of a file or entry.
2243 This can also be a list with cons cells of regular expressions that
2244 are matched against file names, and values."
2245 :group 'org-capture
2246 :group 'org-refile
2247 :type '(choice
2248 (const :tag "Reverse always" t)
2249 (const :tag "Reverse never" nil)
2250 (repeat :tag "By file name regexp"
2251 (cons regexp boolean))))
2253 (defcustom org-log-refile nil
2254 "Information to record when a task is refiled.
2256 Possible values are:
2258 nil Don't add anything
2259 time Add a time stamp to the task
2260 note Prompt for a note and add it with template `org-log-note-headings'
2262 This option can also be set with on a per-file-basis with
2264 #+STARTUP: nologrefile
2265 #+STARTUP: logrefile
2266 #+STARTUP: lognoterefile
2268 You can have local logging settings for a subtree by setting the LOGGING
2269 property to one or more of these keywords.
2271 When bulk-refiling from the agenda, the value `note' is forbidden and
2272 will temporarily be changed to `time'."
2273 :group 'org-refile
2274 :group 'org-progress
2275 :version "24.1"
2276 :type '(choice
2277 (const :tag "No logging" nil)
2278 (const :tag "Record timestamp" time)
2279 (const :tag "Record timestamp with note." note)))
2281 (defcustom org-refile-targets nil
2282 "Targets for refiling entries with \\[org-refile].
2283 This is a list of cons cells. Each cell contains:
2284 - a specification of the files to be considered, either a list of files,
2285 or a symbol whose function or variable value will be used to retrieve
2286 a file name or a list of file names. If you use `org-agenda-files' for
2287 that, all agenda files will be scanned for targets. Nil means consider
2288 headings in the current buffer.
2289 - A specification of how to find candidate refile targets. This may be
2290 any of:
2291 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2292 This tag has to be present in all target headlines, inheritance will
2293 not be considered.
2294 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2295 todo keyword.
2296 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2297 headlines that are refiling targets.
2298 - a cons cell (:level . N). Any headline of level N is considered a target.
2299 Note that, when `org-odd-levels-only' is set, level corresponds to
2300 order in hierarchy, not to the number of stars.
2301 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2302 Note that, when `org-odd-levels-only' is set, level corresponds to
2303 order in hierarchy, not to the number of stars.
2305 Each element of this list generates a set of possible targets.
2306 The union of these sets is presented (with completion) to
2307 the user by `org-refile'.
2309 You can set the variable `org-refile-target-verify-function' to a function
2310 to verify each headline found by the simple criteria above.
2312 When this variable is nil, all top-level headlines in the current buffer
2313 are used, equivalent to the value `((nil . (:level . 1))'."
2314 :group 'org-refile
2315 :type '(repeat
2316 (cons
2317 (choice :value org-agenda-files
2318 (const :tag "All agenda files" org-agenda-files)
2319 (const :tag "Current buffer" nil)
2320 (function) (variable) (file))
2321 (choice :tag "Identify target headline by"
2322 (cons :tag "Specific tag" (const :value :tag) (string))
2323 (cons :tag "TODO keyword" (const :value :todo) (string))
2324 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2325 (cons :tag "Level number" (const :value :level) (integer))
2326 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2328 (defcustom org-refile-target-verify-function nil
2329 "Function to verify if the headline at point should be a refile target.
2330 The function will be called without arguments, with point at the
2331 beginning of the headline. It should return t and leave point
2332 where it is if the headline is a valid target for refiling.
2334 If the target should not be selected, the function must return nil.
2335 In addition to this, it may move point to a place from where the search
2336 should be continued. For example, the function may decide that the entire
2337 subtree of the current entry should be excluded and move point to the end
2338 of the subtree."
2339 :group 'org-refile
2340 :type '(choice
2341 (const nil)
2342 (function)))
2344 (defcustom org-refile-use-cache nil
2345 "Non-nil means cache refile targets to speed up the process.
2346 The cache for a particular file will be updated automatically when
2347 the buffer has been killed, or when any of the marker used for flagging
2348 refile targets no longer points at a live buffer.
2349 If you have added new entries to a buffer that might themselves be targets,
2350 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2351 find that easier, `C-u C-u C-u C-c C-w'."
2352 :group 'org-refile
2353 :version "24.1"
2354 :type 'boolean)
2356 (defcustom org-refile-use-outline-path nil
2357 "Non-nil means provide refile targets as paths.
2358 So a level 3 headline will be available as level1/level2/level3.
2360 When the value is `file', also include the file name (without directory)
2361 into the path. In this case, you can also stop the completion after
2362 the file name, to get entries inserted as top level in the file.
2364 When `full-file-path', include the full file path."
2365 :group 'org-refile
2366 :type '(choice
2367 (const :tag "Not" nil)
2368 (const :tag "Yes" t)
2369 (const :tag "Start with file name" file)
2370 (const :tag "Start with full file path" full-file-path)))
2372 (defcustom org-outline-path-complete-in-steps t
2373 "Non-nil means complete the outline path in hierarchical steps.
2374 When Org-mode uses the refile interface to select an outline path
2375 \(see variable `org-refile-use-outline-path'), the completion of
2376 the path can be done is a single go, or if can be done in steps down
2377 the headline hierarchy. Going in steps is probably the best if you
2378 do not use a special completion package like `ido' or `icicles'.
2379 However, when using these packages, going in one step can be very
2380 fast, while still showing the whole path to the entry."
2381 :group 'org-refile
2382 :type 'boolean)
2384 (defcustom org-refile-allow-creating-parent-nodes nil
2385 "Non-nil means allow to create new nodes as refile targets.
2386 New nodes are then created by adding \"/new node name\" to the completion
2387 of an existing node. When the value of this variable is `confirm',
2388 new node creation must be confirmed by the user (recommended).
2389 When nil, the completion must match an existing entry.
2391 Note that, if the new heading is not seen by the criteria
2392 listed in `org-refile-targets', multiple instances of the same
2393 heading would be created by trying again to file under the new
2394 heading."
2395 :group 'org-refile
2396 :type '(choice
2397 (const :tag "Never" nil)
2398 (const :tag "Always" t)
2399 (const :tag "Prompt for confirmation" confirm)))
2401 (defcustom org-refile-active-region-within-subtree nil
2402 "Non-nil means also refile active region within a subtree.
2404 By default `org-refile' doesn't allow refiling regions if they
2405 don't contain a set of subtrees, but it might be convenient to
2406 do so sometimes: in that case, the first line of the region is
2407 converted to a headline before refiling."
2408 :group 'org-refile
2409 :version "24.1"
2410 :type 'boolean)
2412 (defgroup org-todo nil
2413 "Options concerning TODO items in Org-mode."
2414 :tag "Org TODO"
2415 :group 'org)
2417 (defgroup org-progress nil
2418 "Options concerning Progress logging in Org-mode."
2419 :tag "Org Progress"
2420 :group 'org-time)
2422 (defvar org-todo-interpretation-widgets
2423 '((:tag "Sequence (cycling hits every state)" sequence)
2424 (:tag "Type (cycling directly to DONE)" type))
2425 "The available interpretation symbols for customizing `org-todo-keywords'.
2426 Interested libraries should add to this list.")
2428 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2429 "List of TODO entry keyword sequences and their interpretation.
2430 \\<org-mode-map>This is a list of sequences.
2432 Each sequence starts with a symbol, either `sequence' or `type',
2433 indicating if the keywords should be interpreted as a sequence of
2434 action steps, or as different types of TODO items. The first
2435 keywords are states requiring action - these states will select a headline
2436 for inclusion into the global TODO list Org-mode produces. If one of
2437 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2438 signify that no further action is necessary. If \"|\" is not found,
2439 the last keyword is treated as the only DONE state of the sequence.
2441 The command \\[org-todo] cycles an entry through these states, and one
2442 additional state where no keyword is present. For details about this
2443 cycling, see the manual.
2445 TODO keywords and interpretation can also be set on a per-file basis with
2446 the special #+SEQ_TODO and #+TYP_TODO lines.
2448 Each keyword can optionally specify a character for fast state selection
2449 \(in combination with the variable `org-use-fast-todo-selection')
2450 and specifiers for state change logging, using the same syntax that
2451 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2452 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2453 indicates to record a time stamp each time this state is selected.
2455 Each keyword may also specify if a timestamp or a note should be
2456 recorded when entering or leaving the state, by adding additional
2457 characters in the parenthesis after the keyword. This looks like this:
2458 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2459 record only the time of the state change. With X and Y being either
2460 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2461 Y when leaving the state if and only if the *target* state does not
2462 define X. You may omit any of the fast-selection key or X or /Y,
2463 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2465 For backward compatibility, this variable may also be just a list
2466 of keywords. In this case the interpretation (sequence or type) will be
2467 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2468 :group 'org-todo
2469 :group 'org-keywords
2470 :type '(choice
2471 (repeat :tag "Old syntax, just keywords"
2472 (string :tag "Keyword"))
2473 (repeat :tag "New syntax"
2474 (cons
2475 (choice
2476 :tag "Interpretation"
2477 ;;Quick and dirty way to see
2478 ;;`org-todo-interpretations'. This takes the
2479 ;;place of item arguments
2480 :convert-widget
2481 (lambda (widget)
2482 (widget-put widget
2483 :args (mapcar
2484 #'(lambda (x)
2485 (widget-convert
2486 (cons 'const x)))
2487 org-todo-interpretation-widgets))
2488 widget))
2489 (repeat
2490 (string :tag "Keyword"))))))
2492 (defvar org-todo-keywords-1 nil
2493 "All TODO and DONE keywords active in a buffer.")
2494 (make-variable-buffer-local 'org-todo-keywords-1)
2495 (defvar org-todo-keywords-for-agenda nil)
2496 (defvar org-done-keywords-for-agenda nil)
2497 (defvar org-todo-keyword-alist-for-agenda nil)
2498 (defvar org-tag-alist-for-agenda nil
2499 "Alist of all tags from all agenda files.")
2500 (defvar org-tag-groups-alist-for-agenda nil
2501 "Alist of all groups tags from all current agenda files.")
2502 (defvar org-tag-groups-alist nil)
2503 (make-variable-buffer-local 'org-tag-groups-alist)
2504 (defvar org-agenda-contributing-files nil)
2505 (defvar org-not-done-keywords nil)
2506 (make-variable-buffer-local 'org-not-done-keywords)
2507 (defvar org-done-keywords nil)
2508 (make-variable-buffer-local 'org-done-keywords)
2509 (defvar org-todo-heads nil)
2510 (make-variable-buffer-local 'org-todo-heads)
2511 (defvar org-todo-sets nil)
2512 (make-variable-buffer-local 'org-todo-sets)
2513 (defvar org-todo-log-states nil)
2514 (make-variable-buffer-local 'org-todo-log-states)
2515 (defvar org-todo-kwd-alist nil)
2516 (make-variable-buffer-local 'org-todo-kwd-alist)
2517 (defvar org-todo-key-alist nil)
2518 (make-variable-buffer-local 'org-todo-key-alist)
2519 (defvar org-todo-key-trigger nil)
2520 (make-variable-buffer-local 'org-todo-key-trigger)
2522 (defcustom org-todo-interpretation 'sequence
2523 "Controls how TODO keywords are interpreted.
2524 This variable is in principle obsolete and is only used for
2525 backward compatibility, if the interpretation of todo keywords is
2526 not given already in `org-todo-keywords'. See that variable for
2527 more information."
2528 :group 'org-todo
2529 :group 'org-keywords
2530 :type '(choice (const sequence)
2531 (const type)))
2533 (defcustom org-use-fast-todo-selection t
2534 "Non-nil means use the fast todo selection scheme with C-c C-t.
2535 This variable describes if and under what circumstances the cycling
2536 mechanism for TODO keywords will be replaced by a single-key, direct
2537 selection scheme.
2539 When nil, fast selection is never used.
2541 When the symbol `prefix', it will be used when `org-todo' is called
2542 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2543 `C-u t' in an agenda buffer.
2545 When t, fast selection is used by default. In this case, the prefix
2546 argument forces cycling instead.
2548 In all cases, the special interface is only used if access keys have
2549 actually been assigned by the user, i.e. if keywords in the configuration
2550 are followed by a letter in parenthesis, like TODO(t)."
2551 :group 'org-todo
2552 :type '(choice
2553 (const :tag "Never" nil)
2554 (const :tag "By default" t)
2555 (const :tag "Only with C-u C-c C-t" prefix)))
2557 (defcustom org-provide-todo-statistics t
2558 "Non-nil means update todo statistics after insert and toggle.
2559 ALL-HEADLINES means update todo statistics by including headlines
2560 with no TODO keyword as well, counting them as not done.
2561 A list of TODO keywords means the same, but skip keywords that are
2562 not in this list.
2563 When set to a list of two lists, the first list contains keywords
2564 to consider as TODO keywords, the second list contains keywords
2565 to consider as DONE keywords.
2567 When this is set, todo statistics is updated in the parent of the
2568 current entry each time a todo state is changed."
2569 :group 'org-todo
2570 :type '(choice
2571 (const :tag "Yes, only for TODO entries" t)
2572 (const :tag "Yes, including all entries" all-headlines)
2573 (repeat :tag "Yes, for TODOs in this list"
2574 (string :tag "TODO keyword"))
2575 (list :tag "Yes, for TODOs and DONEs in these lists"
2576 (repeat (string :tag "TODO keyword"))
2577 (repeat (string :tag "DONE keyword")))
2578 (other :tag "No TODO statistics" nil)))
2580 (defcustom org-hierarchical-todo-statistics t
2581 "Non-nil means TODO statistics covers just direct children.
2582 When nil, all entries in the subtree are considered.
2583 This has only an effect if `org-provide-todo-statistics' is set.
2584 To set this to nil for only a single subtree, use a COOKIE_DATA
2585 property and include the word \"recursive\" into the value."
2586 :group 'org-todo
2587 :type 'boolean)
2589 (defcustom org-after-todo-state-change-hook nil
2590 "Hook which is run after the state of a TODO item was changed.
2591 The new state (a string with a TODO keyword, or nil) is available in the
2592 Lisp variable `org-state'."
2593 :group 'org-todo
2594 :type 'hook)
2596 (defvar org-blocker-hook nil
2597 "Hook for functions that are allowed to block a state change.
2599 Functions in this hook should not modify the buffer.
2600 Each function gets as its single argument a property list,
2601 see `org-trigger-hook' for more information about this list.
2603 If any of the functions in this hook returns nil, the state change
2604 is blocked.")
2606 (defvar org-trigger-hook nil
2607 "Hook for functions that are triggered by a state change.
2609 Each function gets as its single argument a property list with at
2610 least the following elements:
2612 (:type type-of-change :position pos-at-entry-start
2613 :from old-state :to new-state)
2615 Depending on the type, more properties may be present.
2617 This mechanism is currently implemented for:
2619 TODO state changes
2620 ------------------
2621 :type todo-state-change
2622 :from previous state (keyword as a string), or nil, or a symbol
2623 'todo' or 'done', to indicate the general type of state.
2624 :to new state, like in :from")
2626 (defcustom org-enforce-todo-dependencies nil
2627 "Non-nil means undone TODO entries will block switching the parent to DONE.
2628 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2629 be blocked if any prior sibling is not yet done.
2630 Finally, if the parent is blocked because of ordered siblings of its own,
2631 the child will also be blocked."
2632 :set (lambda (var val)
2633 (set var val)
2634 (if val
2635 (add-hook 'org-blocker-hook
2636 'org-block-todo-from-children-or-siblings-or-parent)
2637 (remove-hook 'org-blocker-hook
2638 'org-block-todo-from-children-or-siblings-or-parent)))
2639 :group 'org-todo
2640 :type 'boolean)
2642 (defcustom org-enforce-todo-checkbox-dependencies nil
2643 "Non-nil means unchecked boxes will block switching the parent to DONE.
2644 When this is nil, checkboxes have no influence on switching TODO states.
2645 When non-nil, you first need to check off all check boxes before the TODO
2646 entry can be switched to DONE.
2647 This variable needs to be set before org.el is loaded, and you need to
2648 restart Emacs after a change to make the change effective. The only way
2649 to change is while Emacs is running is through the customize interface."
2650 :set (lambda (var val)
2651 (set var val)
2652 (if val
2653 (add-hook 'org-blocker-hook
2654 'org-block-todo-from-checkboxes)
2655 (remove-hook 'org-blocker-hook
2656 'org-block-todo-from-checkboxes)))
2657 :group 'org-todo
2658 :type 'boolean)
2660 (defcustom org-treat-insert-todo-heading-as-state-change nil
2661 "Non-nil means inserting a TODO heading is treated as state change.
2662 So when the command \\[org-insert-todo-heading] is used, state change
2663 logging will apply if appropriate. When nil, the new TODO item will
2664 be inserted directly, and no logging will take place."
2665 :group 'org-todo
2666 :type 'boolean)
2668 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2669 "Non-nil means switching TODO states with S-cursor counts as state change.
2670 This is the default behavior. However, setting this to nil allows a
2671 convenient way to select a TODO state and bypass any logging associated
2672 with that."
2673 :group 'org-todo
2674 :type 'boolean)
2676 (defcustom org-todo-state-tags-triggers nil
2677 "Tag changes that should be triggered by TODO state changes.
2678 This is a list. Each entry is
2680 (state-change (tag . flag) .......)
2682 State-change can be a string with a state, and empty string to indicate the
2683 state that has no TODO keyword, or it can be one of the symbols `todo'
2684 or `done', meaning any not-done or done state, respectively."
2685 :group 'org-todo
2686 :group 'org-tags
2687 :type '(repeat
2688 (cons (choice :tag "When changing to"
2689 (const :tag "Not-done state" todo)
2690 (const :tag "Done state" done)
2691 (string :tag "State"))
2692 (repeat
2693 (cons :tag "Tag action"
2694 (string :tag "Tag")
2695 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2697 (defcustom org-log-done nil
2698 "Information to record when a task moves to the DONE state.
2700 Possible values are:
2702 nil Don't add anything, just change the keyword
2703 time Add a time stamp to the task
2704 note Prompt for a note and add it with template `org-log-note-headings'
2706 This option can also be set with on a per-file-basis with
2708 #+STARTUP: nologdone
2709 #+STARTUP: logdone
2710 #+STARTUP: lognotedone
2712 You can have local logging settings for a subtree by setting the LOGGING
2713 property to one or more of these keywords."
2714 :group 'org-todo
2715 :group 'org-progress
2716 :type '(choice
2717 (const :tag "No logging" nil)
2718 (const :tag "Record CLOSED timestamp" time)
2719 (const :tag "Record CLOSED timestamp with note." note)))
2721 ;; Normalize old uses of org-log-done.
2722 (cond
2723 ((eq org-log-done t) (setq org-log-done 'time))
2724 ((and (listp org-log-done) (memq 'done org-log-done))
2725 (setq org-log-done 'note)))
2727 (defcustom org-log-reschedule nil
2728 "Information to record when the scheduling date of a tasks is modified.
2730 Possible values are:
2732 nil Don't add anything, just change the date
2733 time Add a time stamp to the task
2734 note Prompt for a note and add it with template `org-log-note-headings'
2736 This option can also be set with on a per-file-basis with
2738 #+STARTUP: nologreschedule
2739 #+STARTUP: logreschedule
2740 #+STARTUP: lognotereschedule"
2741 :group 'org-todo
2742 :group 'org-progress
2743 :type '(choice
2744 (const :tag "No logging" nil)
2745 (const :tag "Record timestamp" time)
2746 (const :tag "Record timestamp with note." note)))
2748 (defcustom org-log-redeadline nil
2749 "Information to record when the deadline date of a tasks is modified.
2751 Possible values are:
2753 nil Don't add anything, just change the date
2754 time Add a time stamp to the task
2755 note Prompt for a note and add it with template `org-log-note-headings'
2757 This option can also be set with on a per-file-basis with
2759 #+STARTUP: nologredeadline
2760 #+STARTUP: logredeadline
2761 #+STARTUP: lognoteredeadline
2763 You can have local logging settings for a subtree by setting the LOGGING
2764 property to one or more of these keywords."
2765 :group 'org-todo
2766 :group 'org-progress
2767 :type '(choice
2768 (const :tag "No logging" nil)
2769 (const :tag "Record timestamp" time)
2770 (const :tag "Record timestamp with note." note)))
2772 (defcustom org-log-note-clock-out nil
2773 "Non-nil means record a note when clocking out of an item.
2774 This can also be configured on a per-file basis by adding one of
2775 the following lines anywhere in the buffer:
2777 #+STARTUP: lognoteclock-out
2778 #+STARTUP: nolognoteclock-out"
2779 :group 'org-todo
2780 :group 'org-progress
2781 :type 'boolean)
2783 (defcustom org-log-done-with-time t
2784 "Non-nil means the CLOSED time stamp will contain date and time.
2785 When nil, only the date will be recorded."
2786 :group 'org-progress
2787 :type 'boolean)
2789 (defcustom org-log-note-headings
2790 '((done . "CLOSING NOTE %t")
2791 (state . "State %-12s from %-12S %t")
2792 (note . "Note taken on %t")
2793 (reschedule . "Rescheduled from %S on %t")
2794 (delschedule . "Not scheduled, was %S on %t")
2795 (redeadline . "New deadline from %S on %t")
2796 (deldeadline . "Removed deadline, was %S on %t")
2797 (refile . "Refiled on %t")
2798 (clock-out . ""))
2799 "Headings for notes added to entries.
2800 The value is an alist, with the car being a symbol indicating the note
2801 context, and the cdr is the heading to be used. The heading may also be the
2802 empty string.
2803 %t in the heading will be replaced by a time stamp.
2804 %T will be an active time stamp instead the default inactive one
2805 %d will be replaced by a short-format time stamp.
2806 %D will be replaced by an active short-format time stamp.
2807 %s will be replaced by the new TODO state, in double quotes.
2808 %S will be replaced by the old TODO state, in double quotes.
2809 %u will be replaced by the user name.
2810 %U will be replaced by the full user name.
2812 In fact, it is not a good idea to change the `state' entry, because
2813 agenda log mode depends on the format of these entries."
2814 :group 'org-todo
2815 :group 'org-progress
2816 :type '(list :greedy t
2817 (cons (const :tag "Heading when closing an item" done) string)
2818 (cons (const :tag
2819 "Heading when changing todo state (todo sequence only)"
2820 state) string)
2821 (cons (const :tag "Heading when just taking a note" note) string)
2822 (cons (const :tag "Heading when rescheduling" reschedule) string)
2823 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2824 (cons (const :tag "Heading when changing deadline" redeadline) string)
2825 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2826 (cons (const :tag "Heading when refiling" refile) string)
2827 (cons (const :tag "Heading when clocking out" clock-out) string)))
2829 (unless (assq 'note org-log-note-headings)
2830 (push '(note . "%t") org-log-note-headings))
2832 (defcustom org-log-into-drawer nil
2833 "Non-nil means insert state change notes and time stamps into a drawer.
2834 When nil, state changes notes will be inserted after the headline and
2835 any scheduling and clock lines, but not inside a drawer.
2837 The value of this variable should be the name of the drawer to use.
2838 LOGBOOK is proposed as the default drawer for this purpose, you can
2839 also set this to a string to define the drawer of your choice.
2841 A value of t is also allowed, representing \"LOGBOOK\".
2843 A value of t or nil can also be set with on a per-file-basis with
2845 #+STARTUP: logdrawer
2846 #+STARTUP: nologdrawer
2848 If this variable is set, `org-log-state-notes-insert-after-drawers'
2849 will be ignored.
2851 You can set the property LOG_INTO_DRAWER to overrule this setting for
2852 a subtree."
2853 :group 'org-todo
2854 :group 'org-progress
2855 :type '(choice
2856 (const :tag "Not into a drawer" nil)
2857 (const :tag "LOGBOOK" t)
2858 (string :tag "Other")))
2860 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2862 (defun org-log-into-drawer ()
2863 "Return the value of `org-log-into-drawer', but let properties overrule.
2864 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2865 used instead of the default value."
2866 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2867 (cond
2868 ((not p) org-log-into-drawer)
2869 ((equal p "nil") nil)
2870 ((equal p "t") "LOGBOOK")
2871 (t p))))
2873 (defcustom org-log-state-notes-insert-after-drawers nil
2874 "Non-nil means insert state change notes after any drawers in entry.
2875 Only the drawers that *immediately* follow the headline and the
2876 deadline/scheduled line are skipped.
2877 When nil, insert notes right after the heading and perhaps the line
2878 with deadline/scheduling if present.
2880 This variable will have no effect if `org-log-into-drawer' is
2881 set."
2882 :group 'org-todo
2883 :group 'org-progress
2884 :type 'boolean)
2886 (defcustom org-log-states-order-reversed t
2887 "Non-nil means the latest state note will be directly after heading.
2888 When nil, the state change notes will be ordered according to time.
2890 This option can also be set with on a per-file-basis with
2892 #+STARTUP: logstatesreversed
2893 #+STARTUP: nologstatesreversed"
2894 :group 'org-todo
2895 :group 'org-progress
2896 :type 'boolean)
2898 (defcustom org-todo-repeat-to-state nil
2899 "The TODO state to which a repeater should return the repeating task.
2900 By default this is the first task in a TODO sequence, or the previous state
2901 in a TODO_TYP set. But you can specify another task here.
2902 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2903 :group 'org-todo
2904 :version "24.1"
2905 :type '(choice (const :tag "Head of sequence" nil)
2906 (string :tag "Specific state")))
2908 (defcustom org-log-repeat 'time
2909 "Non-nil means record moving through the DONE state when triggering repeat.
2910 An auto-repeating task is immediately switched back to TODO when
2911 marked DONE. If you are not logging state changes (by adding \"@\"
2912 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2913 record a closing note, there will be no record of the task moving
2914 through DONE. This variable forces taking a note anyway.
2916 nil Don't force a record
2917 time Record a time stamp
2918 note Prompt for a note and add it with template `org-log-note-headings'
2920 This option can also be set with on a per-file-basis with
2922 #+STARTUP: nologrepeat
2923 #+STARTUP: logrepeat
2924 #+STARTUP: lognoterepeat
2926 You can have local logging settings for a subtree by setting the LOGGING
2927 property to one or more of these keywords."
2928 :group 'org-todo
2929 :group 'org-progress
2930 :type '(choice
2931 (const :tag "Don't force a record" nil)
2932 (const :tag "Force recording the DONE state" time)
2933 (const :tag "Force recording a note with the DONE state" note)))
2936 (defgroup org-priorities nil
2937 "Priorities in Org-mode."
2938 :tag "Org Priorities"
2939 :group 'org-todo)
2941 (defcustom org-enable-priority-commands t
2942 "Non-nil means priority commands are active.
2943 When nil, these commands will be disabled, so that you never accidentally
2944 set a priority."
2945 :group 'org-priorities
2946 :type 'boolean)
2948 (defcustom org-highest-priority ?A
2949 "The highest priority of TODO items. A character like ?A, ?B etc.
2950 Must have a smaller ASCII number than `org-lowest-priority'."
2951 :group 'org-priorities
2952 :type 'character)
2954 (defcustom org-lowest-priority ?C
2955 "The lowest priority of TODO items. A character like ?A, ?B etc.
2956 Must have a larger ASCII number than `org-highest-priority'."
2957 :group 'org-priorities
2958 :type 'character)
2960 (defcustom org-default-priority ?B
2961 "The default priority of TODO items.
2962 This is the priority an item gets if no explicit priority is given.
2963 When starting to cycle on an empty priority the first step in the cycle
2964 depends on `org-priority-start-cycle-with-default'. The resulting first
2965 step priority must not exceed the range from `org-highest-priority' to
2966 `org-lowest-priority' which means that `org-default-priority' has to be
2967 in this range exclusive or inclusive the range boundaries. Else the
2968 first step refuses to set the default and the second will fall back
2969 to (depending on the command used) the highest or lowest priority."
2970 :group 'org-priorities
2971 :type 'character)
2973 (defcustom org-priority-start-cycle-with-default t
2974 "Non-nil means start with default priority when starting to cycle.
2975 When this is nil, the first step in the cycle will be (depending on the
2976 command used) one higher or lower than the default priority.
2977 See also `org-default-priority'."
2978 :group 'org-priorities
2979 :type 'boolean)
2981 (defcustom org-get-priority-function nil
2982 "Function to extract the priority from a string.
2983 The string is normally the headline. If this is nil Org computes the
2984 priority from the priority cookie like [#A] in the headline. It returns
2985 an integer, increasing by 1000 for each priority level.
2986 The user can set a different function here, which should take a string
2987 as an argument and return the numeric priority."
2988 :group 'org-priorities
2989 :version "24.1"
2990 :type '(choice
2991 (const nil)
2992 (function)))
2994 (defgroup org-time nil
2995 "Options concerning time stamps and deadlines in Org-mode."
2996 :tag "Org Time"
2997 :group 'org)
2999 (defcustom org-insert-labeled-timestamps-at-point nil
3000 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
3001 When nil, these labeled time stamps are forces into the second line of an
3002 entry, just after the headline. When scheduling from the global TODO list,
3003 the time stamp will always be forced into the second line."
3004 :group 'org-time
3005 :type 'boolean)
3007 (defcustom org-time-stamp-rounding-minutes '(0 5)
3008 "Number of minutes to round time stamps to.
3009 These are two values, the first applies when first creating a time stamp.
3010 The second applies when changing it with the commands `S-up' and `S-down'.
3011 When changing the time stamp, this means that it will change in steps
3012 of N minutes, as given by the second value.
3014 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3015 numbers should be factors of 60, so for example 5, 10, 15.
3017 When this is larger than 1, you can still force an exact time stamp by using
3018 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3019 and by using a prefix arg to `S-up/down' to specify the exact number
3020 of minutes to shift."
3021 :group 'org-time
3022 :get #'(lambda (var) ; Make sure both elements are there
3023 (if (integerp (default-value var))
3024 (list (default-value var) 5)
3025 (default-value var)))
3026 :type '(list
3027 (integer :tag "when inserting times")
3028 (integer :tag "when modifying times")))
3030 ;; Normalize old customizations of this variable.
3031 (when (integerp org-time-stamp-rounding-minutes)
3032 (setq org-time-stamp-rounding-minutes
3033 (list org-time-stamp-rounding-minutes
3034 org-time-stamp-rounding-minutes)))
3036 (defcustom org-display-custom-times nil
3037 "Non-nil means overlay custom formats over all time stamps.
3038 The formats are defined through the variable `org-time-stamp-custom-formats'.
3039 To turn this on on a per-file basis, insert anywhere in the file:
3040 #+STARTUP: customtime"
3041 :group 'org-time
3042 :set 'set-default
3043 :type 'sexp)
3044 (make-variable-buffer-local 'org-display-custom-times)
3046 (defcustom org-time-stamp-custom-formats
3047 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3048 "Custom formats for time stamps. See `format-time-string' for the syntax.
3049 These are overlaid over the default ISO format if the variable
3050 `org-display-custom-times' is set. Time like %H:%M should be at the
3051 end of the second format. The custom formats are also honored by export
3052 commands, if custom time display is turned on at the time of export."
3053 :group 'org-time
3054 :type 'sexp)
3056 (defun org-time-stamp-format (&optional long inactive)
3057 "Get the right format for a time string."
3058 (let ((f (if long (cdr org-time-stamp-formats)
3059 (car org-time-stamp-formats))))
3060 (if inactive
3061 (concat "[" (substring f 1 -1) "]")
3062 f)))
3064 (defcustom org-time-clocksum-format
3065 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3066 "The format string used when creating CLOCKSUM lines.
3067 This is also used when Org mode generates a time duration.
3069 The value can be a single format string containing two
3070 %-sequences, which will be filled with the number of hours and
3071 minutes in that order.
3073 Alternatively, the value can be a plist associating any of the
3074 keys :years, :months, :weeks, :days, :hours or :minutes with
3075 format strings. The time duration is formatted using only the
3076 time components that are needed and concatenating the results.
3077 If a time unit in absent, it falls back to the next smallest
3078 unit.
3080 The keys :require-years, :require-months, :require-days,
3081 :require-weeks, :require-hours, :require-minutes are also
3082 meaningful. A non-nil value for these keys indicates that the
3083 corresponding time component should always be included, even if
3084 its value is 0.
3087 For example,
3089 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3090 :require-minutes t)
3092 means durations longer than a day will be expressed in days,
3093 hours and minutes, and durations less than a day will always be
3094 expressed in hours and minutes (even for durations less than an
3095 hour).
3097 The value
3099 \(:days \"%dd\" :minutes \"%dm\")
3101 means durations longer than a day will be expressed in days and
3102 minutes, and durations less than a day will be expressed entirely
3103 in minutes (even for durations longer than an hour)."
3104 :group 'org-time
3105 :group 'org-clock
3106 :version "24.4"
3107 :package-version '(Org . "8.0")
3108 :type '(choice (string :tag "Format string")
3109 (set :tag "Plist"
3110 (group :inline t (const :tag "Years" :years)
3111 (string :tag "Format string"))
3112 (group :inline t
3113 (const :tag "Always show years" :require-years)
3114 (const t))
3115 (group :inline t (const :tag "Months" :months)
3116 (string :tag "Format string"))
3117 (group :inline t
3118 (const :tag "Always show months" :require-months)
3119 (const t))
3120 (group :inline t (const :tag "Weeks" :weeks)
3121 (string :tag "Format string"))
3122 (group :inline t
3123 (const :tag "Always show weeks" :require-weeks)
3124 (const t))
3125 (group :inline t (const :tag "Days" :days)
3126 (string :tag "Format string"))
3127 (group :inline t
3128 (const :tag "Always show days" :require-days)
3129 (const t))
3130 (group :inline t (const :tag "Hours" :hours)
3131 (string :tag "Format string"))
3132 (group :inline t
3133 (const :tag "Always show hours" :require-hours)
3134 (const t))
3135 (group :inline t (const :tag "Minutes" :minutes)
3136 (string :tag "Format string"))
3137 (group :inline t
3138 (const :tag "Always show minutes" :require-minutes)
3139 (const t)))))
3141 (defcustom org-time-clocksum-use-fractional nil
3142 "When non-nil, \\[org-clock-display] uses fractional times.
3143 See `org-time-clocksum-format' for more on time clock formats."
3144 :group 'org-time
3145 :group 'org-clock
3146 :version "24.3"
3147 :type 'boolean)
3149 (defcustom org-time-clocksum-use-effort-durations nil
3150 "When non-nil, \\[org-clock-display] uses effort durations.
3151 E.g. by default, one day is considered to be a 8 hours effort,
3152 so a task that has been clocked for 16 hours will be displayed
3153 as during 2 days in the clock display or in the clocktable.
3155 See `org-effort-durations' on how to set effort durations
3156 and `org-time-clocksum-format' for more on time clock formats."
3157 :group 'org-time
3158 :group 'org-clock
3159 :version "24.4"
3160 :package-version '(Org . "8.0")
3161 :type 'boolean)
3163 (defcustom org-time-clocksum-fractional-format "%.2f"
3164 "The format string used when creating CLOCKSUM lines,
3165 or when Org mode generates a time duration, if
3166 `org-time-clocksum-use-fractional' is enabled.
3168 The value can be a single format string containing one
3169 %-sequence, which will be filled with the number of hours as
3170 a float.
3172 Alternatively, the value can be a plist associating any of the
3173 keys :years, :months, :weeks, :days, :hours or :minutes with
3174 a format string. The time duration is formatted using the
3175 largest time unit which gives a non-zero integer part. If all
3176 specified formats have zero integer part, the smallest time unit
3177 is used."
3178 :group 'org-time
3179 :type '(choice (string :tag "Format string")
3180 (set (group :inline t (const :tag "Years" :years)
3181 (string :tag "Format string"))
3182 (group :inline t (const :tag "Months" :months)
3183 (string :tag "Format string"))
3184 (group :inline t (const :tag "Weeks" :weeks)
3185 (string :tag "Format string"))
3186 (group :inline t (const :tag "Days" :days)
3187 (string :tag "Format string"))
3188 (group :inline t (const :tag "Hours" :hours)
3189 (string :tag "Format string"))
3190 (group :inline t (const :tag "Minutes" :minutes)
3191 (string :tag "Format string")))))
3193 (defcustom org-deadline-warning-days 14
3194 "Number of days before expiration during which a deadline becomes active.
3195 This variable governs the display in sparse trees and in the agenda.
3196 When 0 or negative, it means use this number (the absolute value of it)
3197 even if a deadline has a different individual lead time specified.
3199 Custom commands can set this variable in the options section."
3200 :group 'org-time
3201 :group 'org-agenda-daily/weekly
3202 :type 'integer)
3204 (defcustom org-scheduled-delay-days 0
3205 "Number of days before a scheduled item becomes active.
3206 This variable governs the display in sparse trees and in the agenda.
3207 The default value (i.e. 0) means: don't delay scheduled item.
3208 When negative, it means use this number (the absolute value of it)
3209 even if a scheduled item has a different individual delay time
3210 specified.
3212 Custom commands can set this variable in the options section."
3213 :group 'org-time
3214 :group 'org-agenda-daily/weekly
3215 :version "24.4"
3216 :package-version '(Org . "8.0")
3217 :type 'integer)
3219 (defcustom org-read-date-prefer-future t
3220 "Non-nil means assume future for incomplete date input from user.
3221 This affects the following situations:
3222 1. The user gives a month but not a year.
3223 For example, if it is April and you enter \"feb 2\", this will be read
3224 as Feb 2, *next* year. \"May 5\", however, will be this year.
3225 2. The user gives a day, but no month.
3226 For example, if today is the 15th, and you enter \"3\", Org-mode will
3227 read this as the third of *next* month. However, if you enter \"17\",
3228 it will be considered as *this* month.
3230 If you set this variable to the symbol `time', then also the following
3231 will work:
3233 3. If the user gives a time.
3234 If the time is before now, it will be interpreted as tomorrow.
3236 Currently none of this works for ISO week specifications.
3238 When this option is nil, the current day, month and year will always be
3239 used as defaults.
3241 See also `org-agenda-jump-prefer-future'."
3242 :group 'org-time
3243 :type '(choice
3244 (const :tag "Never" nil)
3245 (const :tag "Check month and day" t)
3246 (const :tag "Check month, day, and time" time)))
3248 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3249 "Should the agenda jump command prefer the future for incomplete dates?
3250 The default is to do the same as configured in `org-read-date-prefer-future'.
3251 But you can also set a deviating value here.
3252 This may t or nil, or the symbol `org-read-date-prefer-future'."
3253 :group 'org-agenda
3254 :group 'org-time
3255 :version "24.1"
3256 :type '(choice
3257 (const :tag "Use org-read-date-prefer-future"
3258 org-read-date-prefer-future)
3259 (const :tag "Never" nil)
3260 (const :tag "Always" t)))
3262 (defcustom org-read-date-force-compatible-dates t
3263 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3265 Depending on the system Emacs is running on, certain dates cannot
3266 be represented with the type used internally to represent time.
3267 Dates between 1970-1-1 and 2038-1-1 can always be represented
3268 correctly. Some systems allow for earlier dates, some for later,
3269 some for both. One way to find out it to insert any date into an
3270 Org buffer, putting the cursor on the year and hitting S-up and
3271 S-down to test the range.
3273 When this variable is set to t, the date/time prompt will not let
3274 you specify dates outside the 1970-2037 range, so it is certain that
3275 these dates will work in whatever version of Emacs you are
3276 running, and also that you can move a file from one Emacs implementation
3277 to another. WHenever Org is forcing the year for you, it will display
3278 a message and beep.
3280 When this variable is nil, Org will check if the date is
3281 representable in the specific Emacs implementation you are using.
3282 If not, it will force a year, usually the current year, and beep
3283 to remind you. Currently this setting is not recommended because
3284 the likelihood that you will open your Org files in an Emacs that
3285 has limited date range is not negligible.
3287 A workaround for this problem is to use diary sexp dates for time
3288 stamps outside of this range."
3289 :group 'org-time
3290 :version "24.1"
3291 :type 'boolean)
3293 (defcustom org-read-date-display-live t
3294 "Non-nil means display current interpretation of date prompt live.
3295 This display will be in an overlay, in the minibuffer."
3296 :group 'org-time
3297 :type 'boolean)
3299 (defcustom org-read-date-popup-calendar t
3300 "Non-nil means pop up a calendar when prompting for a date.
3301 In the calendar, the date can be selected with mouse-1. However, the
3302 minibuffer will also be active, and you can simply enter the date as well.
3303 When nil, only the minibuffer will be available."
3304 :group 'org-time
3305 :type 'boolean)
3306 (org-defvaralias 'org-popup-calendar-for-date-prompt
3307 'org-read-date-popup-calendar)
3309 (make-obsolete-variable
3310 'org-read-date-minibuffer-setup-hook
3311 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3312 (defcustom org-read-date-minibuffer-setup-hook nil
3313 "Hook to be used to set up keys for the date/time interface.
3314 Add key definitions to `minibuffer-local-map', which will be a
3315 temporary copy.
3317 WARNING: This option is obsolete, you should use
3318 `org-read-date-minibuffer-local-map' to set up keys."
3319 :group 'org-time
3320 :type 'hook)
3322 (defcustom org-extend-today-until 0
3323 "The hour when your day really ends. Must be an integer.
3324 This has influence for the following applications:
3325 - When switching the agenda to \"today\". It it is still earlier than
3326 the time given here, the day recognized as TODAY is actually yesterday.
3327 - When a date is read from the user and it is still before the time given
3328 here, the current date and time will be assumed to be yesterday, 23:59.
3329 Also, timestamps inserted in capture templates follow this rule.
3331 IMPORTANT: This is a feature whose implementation is and likely will
3332 remain incomplete. Really, it is only here because past midnight seems to
3333 be the favorite working time of John Wiegley :-)"
3334 :group 'org-time
3335 :type 'integer)
3337 (defcustom org-use-effective-time nil
3338 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3339 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3340 \"effective time\" of any timestamps between midnight and 8am will be
3341 23:59 of the previous day."
3342 :group 'org-time
3343 :version "24.1"
3344 :type 'boolean)
3346 (defcustom org-use-last-clock-out-time-as-effective-time nil
3347 "When non-nil, use the last clock out time for `org-todo'.
3348 Note that this option has precedence over the combined use of
3349 `org-use-effective-time' and `org-extend-today-until'."
3350 :group 'org-time
3351 :version "24.4"
3352 :package-version '(Org . "8.0")
3353 :type 'boolean)
3355 (defcustom org-edit-timestamp-down-means-later nil
3356 "Non-nil means S-down will increase the time in a time stamp.
3357 When nil, S-up will increase."
3358 :group 'org-time
3359 :type 'boolean)
3361 (defcustom org-calendar-follow-timestamp-change t
3362 "Non-nil means make the calendar window follow timestamp changes.
3363 When a timestamp is modified and the calendar window is visible, it will be
3364 moved to the new date."
3365 :group 'org-time
3366 :type 'boolean)
3368 (defgroup org-tags nil
3369 "Options concerning tags in Org-mode."
3370 :tag "Org Tags"
3371 :group 'org)
3373 (defcustom org-tag-alist nil
3374 "List of tags allowed in Org-mode files.
3375 When this list is nil, Org-mode will base TAG input on what is already in the
3376 buffer.
3377 The value of this variable is an alist, the car of each entry must be a
3378 keyword as a string, the cdr may be a character that is used to select
3379 that tag through the fast-tag-selection interface.
3380 See the manual for details."
3381 :group 'org-tags
3382 :type '(repeat
3383 (choice
3384 (cons (string :tag "Tag name")
3385 (character :tag "Access char"))
3386 (list :tag "Start radio group"
3387 (const :startgroup)
3388 (option (string :tag "Group description")))
3389 (list :tag "Group tags delimiter"
3390 (const :grouptags))
3391 (list :tag "End radio group"
3392 (const :endgroup)
3393 (option (string :tag "Group description")))
3394 (const :tag "New line" (:newline)))))
3396 (defcustom org-tag-persistent-alist nil
3397 "List of tags that will always appear in all Org-mode files.
3398 This is in addition to any in buffer settings or customizations
3399 of `org-tag-alist'.
3400 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3401 The value of this variable is an alist, the car of each entry must be a
3402 keyword as a string, the cdr may be a character that is used to select
3403 that tag through the fast-tag-selection interface.
3404 See the manual for details.
3405 To disable these tags on a per-file basis, insert anywhere in the file:
3406 #+STARTUP: noptag"
3407 :group 'org-tags
3408 :type '(repeat
3409 (choice
3410 (cons (string :tag "Tag name")
3411 (character :tag "Access char"))
3412 (const :tag "Start radio group" (:startgroup))
3413 (const :tag "Group tags delimiter" (:grouptags))
3414 (const :tag "End radio group" (:endgroup))
3415 (const :tag "New line" (:newline)))))
3417 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3418 "If non-nil, always offer completion for all tags of all agenda files.
3419 Instead of customizing this variable directly, you might want to
3420 set it locally for capture buffers, because there no list of
3421 tags in that file can be created dynamically (there are none).
3423 (add-hook 'org-capture-mode-hook
3424 (lambda ()
3425 (set (make-local-variable
3426 'org-complete-tags-always-offer-all-agenda-tags)
3427 t)))"
3428 :group 'org-tags
3429 :version "24.1"
3430 :type 'boolean)
3432 (defvar org-file-tags nil
3433 "List of tags that can be inherited by all entries in the file.
3434 The tags will be inherited if the variable `org-use-tag-inheritance'
3435 says they should be.
3436 This variable is populated from #+FILETAGS lines.")
3438 (defcustom org-use-fast-tag-selection 'auto
3439 "Non-nil means use fast tag selection scheme.
3440 This is a special interface to select and deselect tags with single keys.
3441 When nil, fast selection is never used.
3442 When the symbol `auto', fast selection is used if and only if selection
3443 characters for tags have been configured, either through the variable
3444 `org-tag-alist' or through a #+TAGS line in the buffer.
3445 When t, fast selection is always used and selection keys are assigned
3446 automatically if necessary."
3447 :group 'org-tags
3448 :type '(choice
3449 (const :tag "Always" t)
3450 (const :tag "Never" nil)
3451 (const :tag "When selection characters are configured" auto)))
3453 (defcustom org-fast-tag-selection-single-key nil
3454 "Non-nil means fast tag selection exits after first change.
3455 When nil, you have to press RET to exit it.
3456 During fast tag selection, you can toggle this flag with `C-c'.
3457 This variable can also have the value `expert'. In this case, the window
3458 displaying the tags menu is not even shown, until you press C-c again."
3459 :group 'org-tags
3460 :type '(choice
3461 (const :tag "No" nil)
3462 (const :tag "Yes" t)
3463 (const :tag "Expert" expert)))
3465 (defvar org-fast-tag-selection-include-todo nil
3466 "Non-nil means fast tags selection interface will also offer TODO states.
3467 This is an undocumented feature, you should not rely on it.")
3469 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3470 "The column to which tags should be indented in a headline.
3471 If this number is positive, it specifies the column. If it is negative,
3472 it means that the tags should be flushright to that column. For example,
3473 -80 works well for a normal 80 character screen.
3474 When 0, place tags directly after headline text, with only one space in
3475 between."
3476 :group 'org-tags
3477 :type 'integer)
3479 (defcustom org-auto-align-tags t
3480 "Non-nil keeps tags aligned when modifying headlines.
3481 Some operations (i.e. demoting) change the length of a headline and
3482 therefore shift the tags around. With this option turned on, after
3483 each such operation the tags are again aligned to `org-tags-column'."
3484 :group 'org-tags
3485 :type 'boolean)
3487 (defcustom org-use-tag-inheritance t
3488 "Non-nil means tags in levels apply also for sublevels.
3489 When nil, only the tags directly given in a specific line apply there.
3490 This may also be a list of tags that should be inherited, or a regexp that
3491 matches tags that should be inherited. Additional control is possible
3492 with the variable `org-tags-exclude-from-inheritance' which gives an
3493 explicit list of tags to be excluded from inheritance, even if the value of
3494 `org-use-tag-inheritance' would select it for inheritance.
3496 If this option is t, a match early-on in a tree can lead to a large
3497 number of matches in the subtree when constructing the agenda or creating
3498 a sparse tree. If you only want to see the first match in a tree during
3499 a search, check out the variable `org-tags-match-list-sublevels'."
3500 :group 'org-tags
3501 :type '(choice
3502 (const :tag "Not" nil)
3503 (const :tag "Always" t)
3504 (repeat :tag "Specific tags" (string :tag "Tag"))
3505 (regexp :tag "Tags matched by regexp")))
3507 (defcustom org-tags-exclude-from-inheritance nil
3508 "List of tags that should never be inherited.
3509 This is a way to exclude a few tags from inheritance. For way to do
3510 the opposite, to actively allow inheritance for selected tags,
3511 see the variable `org-use-tag-inheritance'."
3512 :group 'org-tags
3513 :type '(repeat (string :tag "Tag")))
3515 (defun org-tag-inherit-p (tag)
3516 "Check if TAG is one that should be inherited."
3517 (cond
3518 ((member tag org-tags-exclude-from-inheritance) nil)
3519 ((eq org-use-tag-inheritance t) t)
3520 ((not org-use-tag-inheritance) nil)
3521 ((stringp org-use-tag-inheritance)
3522 (string-match org-use-tag-inheritance tag))
3523 ((listp org-use-tag-inheritance)
3524 (member tag org-use-tag-inheritance))
3525 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3527 (defcustom org-tags-match-list-sublevels t
3528 "Non-nil means list also sublevels of headlines matching a search.
3529 This variable applies to tags/property searches, and also to stuck
3530 projects because this search is based on a tags match as well.
3532 When set to the symbol `indented', sublevels are indented with
3533 leading dots.
3535 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3536 the sublevels of a headline matching a tag search often also match
3537 the same search. Listing all of them can create very long lists.
3538 Setting this variable to nil causes subtrees of a match to be skipped.
3540 This variable is semi-obsolete and probably should always be true. It
3541 is better to limit inheritance to certain tags using the variables
3542 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3543 :group 'org-tags
3544 :type '(choice
3545 (const :tag "No, don't list them" nil)
3546 (const :tag "Yes, do list them" t)
3547 (const :tag "List them, indented with leading dots" indented)))
3549 (defcustom org-tags-sort-function nil
3550 "When set, tags are sorted using this function as a comparator."
3551 :group 'org-tags
3552 :type '(choice
3553 (const :tag "No sorting" nil)
3554 (const :tag "Alphabetical" string<)
3555 (const :tag "Reverse alphabetical" string>)
3556 (function :tag "Custom function" nil)))
3558 (defvar org-tags-history nil
3559 "History of minibuffer reads for tags.")
3560 (defvar org-last-tags-completion-table nil
3561 "The last used completion table for tags.")
3562 (defvar org-after-tags-change-hook nil
3563 "Hook that is run after the tags in a line have changed.")
3565 (defgroup org-properties nil
3566 "Options concerning properties in Org-mode."
3567 :tag "Org Properties"
3568 :group 'org)
3570 (defcustom org-property-format "%-10s %s"
3571 "How property key/value pairs should be formatted by `indent-line'.
3572 When `indent-line' hits a property definition, it will format the line
3573 according to this format, mainly to make sure that the values are
3574 lined-up with respect to each other."
3575 :group 'org-properties
3576 :type 'string)
3578 (defcustom org-properties-postprocess-alist nil
3579 "Alist of properties and functions to adjust inserted values.
3580 Elements of this alist must be of the form
3582 ([string] [function])
3584 where [string] must be a property name and [function] must be a
3585 lambda expression: this lambda expression must take one argument,
3586 the value to adjust, and return the new value as a string.
3588 For example, this element will allow the property \"Remaining\"
3589 to be updated wrt the relation between the \"Effort\" property
3590 and the clock summary:
3592 ((\"Remaining\" (lambda(value)
3593 (let ((clocksum (org-clock-sum-current-item))
3594 (effort (org-duration-string-to-minutes
3595 (org-entry-get (point) \"Effort\"))))
3596 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3597 :group 'org-properties
3598 :version "24.1"
3599 :type '(alist :key-type (string :tag "Property")
3600 :value-type (function :tag "Function")))
3602 (defcustom org-use-property-inheritance nil
3603 "Non-nil means properties apply also for sublevels.
3605 This setting is chiefly used during property searches. Turning it on can
3606 cause significant overhead when doing a search, which is why it is not
3607 on by default.
3609 When nil, only the properties directly given in the current entry count.
3610 When t, every property is inherited. The value may also be a list of
3611 properties that should have inheritance, or a regular expression matching
3612 properties that should be inherited.
3614 However, note that some special properties use inheritance under special
3615 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3616 and the properties ending in \"_ALL\" when they are used as descriptor
3617 for valid values of a property.
3619 Note for programmers:
3620 When querying an entry with `org-entry-get', you can control if inheritance
3621 should be used. By default, `org-entry-get' looks only at the local
3622 properties. You can request inheritance by setting the inherit argument
3623 to t (to force inheritance) or to `selective' (to respect the setting
3624 in this variable)."
3625 :group 'org-properties
3626 :type '(choice
3627 (const :tag "Not" nil)
3628 (const :tag "Always" t)
3629 (repeat :tag "Specific properties" (string :tag "Property"))
3630 (regexp :tag "Properties matched by regexp")))
3632 (defun org-property-inherit-p (property)
3633 "Check if PROPERTY is one that should be inherited."
3634 (cond
3635 ((eq org-use-property-inheritance t) t)
3636 ((not org-use-property-inheritance) nil)
3637 ((stringp org-use-property-inheritance)
3638 (string-match org-use-property-inheritance property))
3639 ((listp org-use-property-inheritance)
3640 (member property org-use-property-inheritance))
3641 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3643 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3644 "The default column format, if no other format has been defined.
3645 This variable can be set on the per-file basis by inserting a line
3647 #+COLUMNS: %25ITEM ....."
3648 :group 'org-properties
3649 :type 'string)
3651 (defcustom org-columns-ellipses ".."
3652 "The ellipses to be used when a field in column view is truncated.
3653 When this is the empty string, as many characters as possible are shown,
3654 but then there will be no visual indication that the field has been truncated.
3655 When this is a string of length N, the last N characters of a truncated
3656 field are replaced by this string. If the column is narrower than the
3657 ellipses string, only part of the ellipses string will be shown."
3658 :group 'org-properties
3659 :type 'string)
3661 (defcustom org-columns-modify-value-for-display-function nil
3662 "Function that modifies values for display in column view.
3663 For example, it can be used to cut out a certain part from a time stamp.
3664 The function must take 2 arguments:
3666 column-title The title of the column (*not* the property name)
3667 value The value that should be modified.
3669 The function should return the value that should be displayed,
3670 or nil if the normal value should be used."
3671 :group 'org-properties
3672 :type '(choice (const nil) (function)))
3674 (defconst org-global-properties-fixed
3675 '(("VISIBILITY_ALL" . "folded children content all")
3676 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3677 "List of property/value pairs that can be inherited by any entry.
3679 These are fixed values, for the preset properties. The user variable
3680 that can be used to add to this list is `org-global-properties'.
3682 The entries in this list are cons cells where the car is a property
3683 name and cdr is a string with the value. If the value represents
3684 multiple items like an \"_ALL\" property, separate the items by
3685 spaces.")
3687 (defcustom org-global-properties nil
3688 "List of property/value pairs that can be inherited by any entry.
3690 This list will be combined with the constant `org-global-properties-fixed'.
3692 The entries in this list are cons cells where the car is a property
3693 name and cdr is a string with the value.
3695 You can set buffer-local values for the same purpose in the variable
3696 `org-file-properties' this by adding lines like
3698 #+PROPERTY: NAME VALUE"
3699 :group 'org-properties
3700 :type '(repeat
3701 (cons (string :tag "Property")
3702 (string :tag "Value"))))
3704 (defvar org-file-properties nil
3705 "List of property/value pairs that can be inherited by any entry.
3706 Valid for the current buffer.
3707 This variable is populated from #+PROPERTY lines.")
3708 (make-variable-buffer-local 'org-file-properties)
3710 (defgroup org-agenda nil
3711 "Options concerning agenda views in Org-mode."
3712 :tag "Org Agenda"
3713 :group 'org)
3715 (defvar org-category nil
3716 "Variable used by org files to set a category for agenda display.
3717 Such files should use a file variable to set it, for example
3719 # -*- mode: org; org-category: \"ELisp\"
3721 or contain a special line
3723 #+CATEGORY: ELisp
3725 If the file does not specify a category, then file's base name
3726 is used instead.")
3727 (make-variable-buffer-local 'org-category)
3728 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3730 (defcustom org-agenda-files nil
3731 "The files to be used for agenda display.
3732 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3733 \\[org-remove-file]. You can also use customize to edit the list.
3735 If an entry is a directory, all files in that directory that are matched by
3736 `org-agenda-file-regexp' will be part of the file list.
3738 If the value of the variable is not a list but a single file name, then
3739 the list of agenda files is actually stored and maintained in that file, one
3740 agenda file per line. In this file paths can be given relative to
3741 `org-directory'. Tilde expansion and environment variable substitution
3742 are also made."
3743 :group 'org-agenda
3744 :type '(choice
3745 (repeat :tag "List of files and directories" file)
3746 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3748 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3749 "Regular expression to match files for `org-agenda-files'.
3750 If any element in the list in that variable contains a directory instead
3751 of a normal file, all files in that directory that are matched by this
3752 regular expression will be included."
3753 :group 'org-agenda
3754 :type 'regexp)
3756 (defcustom org-agenda-text-search-extra-files nil
3757 "List of extra files to be searched by text search commands.
3758 These files will be searched in addition to the agenda files by the
3759 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3760 Note that these files will only be searched for text search commands,
3761 not for the other agenda views like todo lists, tag searches or the weekly
3762 agenda. This variable is intended to list notes and possibly archive files
3763 that should also be searched by these two commands.
3764 In fact, if the first element in the list is the symbol `agenda-archives',
3765 then all archive files of all agenda files will be added to the search
3766 scope."
3767 :group 'org-agenda
3768 :type '(set :greedy t
3769 (const :tag "Agenda Archives" agenda-archives)
3770 (repeat :inline t (file))))
3772 (org-defvaralias 'org-agenda-multi-occur-extra-files
3773 'org-agenda-text-search-extra-files)
3775 (defcustom org-agenda-skip-unavailable-files nil
3776 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3777 A nil value means to remove them, after a query, from the list."
3778 :group 'org-agenda
3779 :type 'boolean)
3781 (defcustom org-calendar-to-agenda-key [?c]
3782 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3783 The command `org-calendar-goto-agenda' will be bound to this key. The
3784 default is the character `c' because then `c' can be used to switch back and
3785 forth between agenda and calendar."
3786 :group 'org-agenda
3787 :type 'sexp)
3789 (defcustom org-calendar-insert-diary-entry-key [?i]
3790 "The key to be installed in `calendar-mode-map' for adding diary entries.
3791 This option is irrelevant until `org-agenda-diary-file' has been configured
3792 to point to an Org-mode file. When that is the case, the command
3793 `org-agenda-diary-entry' will be bound to the key given here, by default
3794 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3795 if you want to continue doing this, you need to change this to a different
3796 key."
3797 :group 'org-agenda
3798 :type 'sexp)
3800 (defcustom org-agenda-diary-file 'diary-file
3801 "File to which to add new entries with the `i' key in agenda and calendar.
3802 When this is the symbol `diary-file', the functionality in the Emacs
3803 calendar will be used to add entries to the `diary-file'. But when this
3804 points to a file, `org-agenda-diary-entry' will be used instead."
3805 :group 'org-agenda
3806 :type '(choice
3807 (const :tag "The standard Emacs diary file" diary-file)
3808 (file :tag "Special Org file diary entries")))
3810 (eval-after-load "calendar"
3811 '(progn
3812 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3813 'org-calendar-goto-agenda)
3814 (add-hook 'calendar-mode-hook
3815 (lambda ()
3816 (unless (eq org-agenda-diary-file 'diary-file)
3817 (define-key calendar-mode-map
3818 org-calendar-insert-diary-entry-key
3819 'org-agenda-diary-entry))))))
3821 (defgroup org-latex nil
3822 "Options for embedding LaTeX code into Org-mode."
3823 :tag "Org LaTeX"
3824 :group 'org)
3826 (defcustom org-format-latex-options
3827 '(:foreground default :background default :scale 1.0
3828 :html-foreground "Black" :html-background "Transparent"
3829 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3830 "Options for creating images from LaTeX fragments.
3831 This is a property list with the following properties:
3832 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3833 `default' means use the foreground of the default face.
3834 `auto' means use the foreground from the text face.
3835 :background the background color, or \"Transparent\".
3836 `default' means use the background of the default face.
3837 `auto' means use the background from the text face.
3838 :scale a scaling factor for the size of the images, to get more pixels
3839 :html-foreground, :html-background, :html-scale
3840 the same numbers for HTML export.
3841 :matchers a list indicating which matchers should be used to
3842 find LaTeX fragments. Valid members of this list are:
3843 \"begin\" find environments
3844 \"$1\" find single characters surrounded by $.$
3845 \"$\" find math expressions surrounded by $...$
3846 \"$$\" find math expressions surrounded by $$....$$
3847 \"\\(\" find math expressions surrounded by \\(...\\)
3848 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3849 :group 'org-latex
3850 :type 'plist)
3852 (defcustom org-format-latex-signal-error t
3853 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3854 When nil, just push out a message."
3855 :group 'org-latex
3856 :version "24.1"
3857 :type 'boolean)
3859 (defcustom org-latex-to-mathml-jar-file nil
3860 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3861 Use this to specify additional executable file say a jar file.
3863 When using MathToWeb as the converter, specify the full-path to
3864 your mathtoweb.jar file."
3865 :group 'org-latex
3866 :version "24.1"
3867 :type '(choice
3868 (const :tag "None" nil)
3869 (file :tag "JAR file" :must-match t)))
3871 (defcustom org-latex-to-mathml-convert-command nil
3872 "Command to convert LaTeX fragments to MathML.
3873 Replace format-specifiers in the command as noted below and use
3874 `shell-command' to convert LaTeX to MathML.
3875 %j: Executable file in fully expanded form as specified by
3876 `org-latex-to-mathml-jar-file'.
3877 %I: Input LaTeX file in fully expanded form
3878 %o: Output MathML file
3879 This command is used by `org-create-math-formula'.
3881 When using MathToWeb as the converter, set this to
3882 \"java -jar %j -unicode -force -df %o %I\"."
3883 :group 'org-latex
3884 :version "24.1"
3885 :type '(choice
3886 (const :tag "None" nil)
3887 (string :tag "\nShell command")))
3889 (defcustom org-latex-create-formula-image-program 'dvipng
3890 "Program to convert LaTeX fragments with.
3892 dvipng Process the LaTeX fragments to dvi file, then convert
3893 dvi files to png files using dvipng.
3894 This will also include processing of non-math environments.
3895 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3896 to convert pdf files to png files"
3897 :group 'org-latex
3898 :version "24.1"
3899 :type '(choice
3900 (const :tag "dvipng" dvipng)
3901 (const :tag "imagemagick" imagemagick)))
3903 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3904 "Path to store latex preview images.
3905 A relative path here creates many directories relative to the
3906 processed org files paths. An absolute path puts all preview
3907 images at the same place."
3908 :group 'org-latex
3909 :version "24.3"
3910 :type 'string)
3912 (defun org-format-latex-mathml-available-p ()
3913 "Return t if `org-latex-to-mathml-convert-command' is usable."
3914 (save-match-data
3915 (when (and (boundp 'org-latex-to-mathml-convert-command)
3916 org-latex-to-mathml-convert-command)
3917 (let ((executable (car (split-string
3918 org-latex-to-mathml-convert-command))))
3919 (when (executable-find executable)
3920 (if (string-match
3921 "%j" org-latex-to-mathml-convert-command)
3922 (file-readable-p org-latex-to-mathml-jar-file)
3923 t))))))
3925 (defcustom org-format-latex-header "\\documentclass{article}
3926 \\usepackage[usenames]{color}
3927 \[PACKAGES]
3928 \[DEFAULT-PACKAGES]
3929 \\pagestyle{empty} % do not remove
3930 % The settings below are copied from fullpage.sty
3931 \\setlength{\\textwidth}{\\paperwidth}
3932 \\addtolength{\\textwidth}{-3cm}
3933 \\setlength{\\oddsidemargin}{1.5cm}
3934 \\addtolength{\\oddsidemargin}{-2.54cm}
3935 \\setlength{\\evensidemargin}{\\oddsidemargin}
3936 \\setlength{\\textheight}{\\paperheight}
3937 \\addtolength{\\textheight}{-\\headheight}
3938 \\addtolength{\\textheight}{-\\headsep}
3939 \\addtolength{\\textheight}{-\\footskip}
3940 \\addtolength{\\textheight}{-3cm}
3941 \\setlength{\\topmargin}{1.5cm}
3942 \\addtolength{\\topmargin}{-2.54cm}"
3943 "The document header used for processing LaTeX fragments.
3944 It is imperative that this header make sure that no page number
3945 appears on the page. The package defined in the variables
3946 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3947 will either replace the placeholder \"[PACKAGES]\" in this
3948 header, or they will be appended."
3949 :group 'org-latex
3950 :type 'string)
3952 (defun org-set-packages-alist (var val)
3953 "Set the packages alist and make sure it has 3 elements per entry."
3954 (set var (mapcar (lambda (x)
3955 (if (and (consp x) (= (length x) 2))
3956 (list (car x) (nth 1 x) t)
3958 val)))
3960 (defun org-get-packages-alist (var)
3961 "Get the packages alist and make sure it has 3 elements per entry."
3962 (mapcar (lambda (x)
3963 (if (and (consp x) (= (length x) 2))
3964 (list (car x) (nth 1 x) t)
3966 (default-value var)))
3968 (defcustom org-latex-default-packages-alist
3969 '(("AUTO" "inputenc" t)
3970 ("T1" "fontenc" t)
3971 ("" "fixltx2e" nil)
3972 ("" "graphicx" t)
3973 ("" "longtable" nil)
3974 ("" "float" nil)
3975 ("" "wrapfig" nil)
3976 ("" "rotating" nil)
3977 ("normalem" "ulem" t)
3978 ("" "amsmath" t)
3979 ("" "textcomp" t)
3980 ("" "marvosym" t)
3981 ("" "wasysym" t)
3982 ("" "amssymb" t)
3983 ("" "hyperref" nil)
3984 "\\tolerance=1000")
3985 "Alist of default packages to be inserted in the header.
3987 Change this only if one of the packages here causes an
3988 incompatibility with another package you are using.
3990 The packages in this list are needed by one part or another of
3991 Org mode to function properly:
3993 - inputenc, fontenc: for basic font and character selection
3994 - fixltx2e: Important patches of LaTeX itself
3995 - graphicx: for including images
3996 - longtable: For multipage tables
3997 - float, wrapfig: for figure placement
3998 - rotating: for sideways figures and tables
3999 - ulem: for underline and strike-through
4000 - amsmath: for subscript and superscript and math environments
4001 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4002 for interpreting the entities in `org-entities'. You can skip
4003 some of these packages if you don't use any of their symbols.
4004 - hyperref: for cross references
4006 Therefore you should not modify this variable unless you know
4007 what you are doing. The one reason to change it anyway is that
4008 you might be loading some other package that conflicts with one
4009 of the default packages. Each cell is of the format
4010 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
4011 the package also needs to be included when compiling LaTeX
4012 snippets into images for inclusion into non-LaTeX output."
4013 :group 'org-latex
4014 :group 'org-export-latex
4015 :set 'org-set-packages-alist
4016 :get 'org-get-packages-alist
4017 :version "24.1"
4018 :type '(repeat
4019 (choice
4020 (list :tag "options/package pair"
4021 (string :tag "options")
4022 (string :tag "package")
4023 (boolean :tag "Snippet"))
4024 (string :tag "A line of LaTeX"))))
4026 (defcustom org-latex-packages-alist nil
4027 "Alist of packages to be inserted in every LaTeX header.
4029 These will be inserted after `org-latex-default-packages-alist'.
4030 Each cell is of the format:
4032 \(\"options\" \"package\" snippet-flag)
4034 SNIPPET-FLAG, when t, indicates that this package is also needed
4035 when turning LaTeX snippets into images for inclusion into
4036 non-LaTeX output.
4038 Make sure that you only list packages here which:
4040 - you want in every file
4041 - do not conflict with the setup in `org-format-latex-header'.
4042 - do not conflict with the default packages in
4043 `org-latex-default-packages-alist'."
4044 :group 'org-latex
4045 :group 'org-export-latex
4046 :set 'org-set-packages-alist
4047 :get 'org-get-packages-alist
4048 :type '(repeat
4049 (choice
4050 (list :tag "options/package pair"
4051 (string :tag "options")
4052 (string :tag "package")
4053 (boolean :tag "Snippet"))
4054 (string :tag "A line of LaTeX"))))
4056 (defgroup org-appearance nil
4057 "Settings for Org-mode appearance."
4058 :tag "Org Appearance"
4059 :group 'org)
4061 (defcustom org-level-color-stars-only nil
4062 "Non-nil means fontify only the stars in each headline.
4063 When nil, the entire headline is fontified.
4064 Changing it requires restart of `font-lock-mode' to become effective
4065 also in regions already fontified."
4066 :group 'org-appearance
4067 :type 'boolean)
4069 (defcustom org-hide-leading-stars nil
4070 "Non-nil means hide the first N-1 stars in a headline.
4071 This works by using the face `org-hide' for these stars. This
4072 face is white for a light background, and black for a dark
4073 background. You may have to customize the face `org-hide' to
4074 make this work.
4075 Changing it requires restart of `font-lock-mode' to become effective
4076 also in regions already fontified.
4077 You may also set this on a per-file basis by adding one of the following
4078 lines to the buffer:
4080 #+STARTUP: hidestars
4081 #+STARTUP: showstars"
4082 :group 'org-appearance
4083 :type 'boolean)
4085 (defcustom org-hidden-keywords nil
4086 "List of symbols corresponding to keywords to be hidden the org buffer.
4087 For example, a value '(title) for this list will make the document's title
4088 appear in the buffer without the initial #+TITLE: keyword."
4089 :group 'org-appearance
4090 :version "24.1"
4091 :type '(set (const :tag "#+AUTHOR" author)
4092 (const :tag "#+DATE" date)
4093 (const :tag "#+EMAIL" email)
4094 (const :tag "#+TITLE" title)))
4096 (defcustom org-custom-properties nil
4097 "List of properties (as strings) with a special meaning.
4098 The default use of these custom properties is to let the user
4099 hide them with `org-toggle-custom-properties-visibility'."
4100 :group 'org-properties
4101 :group 'org-appearance
4102 :version "24.3"
4103 :type '(repeat (string :tag "Property Name")))
4105 (defcustom org-fontify-done-headline nil
4106 "Non-nil means change the face of a headline if it is marked DONE.
4107 Normally, only the TODO/DONE keyword indicates the state of a headline.
4108 When this is non-nil, the headline after the keyword is set to the
4109 `org-headline-done' as an additional indication."
4110 :group 'org-appearance
4111 :type 'boolean)
4113 (defcustom org-fontify-emphasized-text t
4114 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4115 Changing this variable requires a restart of Emacs to take effect."
4116 :group 'org-appearance
4117 :type 'boolean)
4119 (defcustom org-fontify-whole-heading-line nil
4120 "Non-nil means fontify the whole line for headings.
4121 This is useful when setting a background color for the
4122 org-level-* faces."
4123 :group 'org-appearance
4124 :type 'boolean)
4126 (defcustom org-highlight-latex-and-related nil
4127 "Non-nil means highlight LaTeX related syntax in the buffer.
4128 When non nil, the value should be a list containing any of the
4129 following symbols:
4130 `latex' Highlight LaTeX snippets and environments.
4131 `script' Highlight subscript and superscript.
4132 `entities' Highlight entities."
4133 :group 'org-appearance
4134 :version "24.4"
4135 :package-version '(Org . "8.0")
4136 :type '(choice
4137 (const :tag "No highlighting" nil)
4138 (set :greedy t :tag "Highlight"
4139 (const :tag "LaTeX snippets and environments" latex)
4140 (const :tag "Subscript and superscript" script)
4141 (const :tag "Entities" entities))))
4143 (defcustom org-hide-emphasis-markers nil
4144 "Non-nil mean font-lock should hide the emphasis marker characters."
4145 :group 'org-appearance
4146 :type 'boolean)
4148 (defcustom org-pretty-entities nil
4149 "Non-nil means show entities as UTF8 characters.
4150 When nil, the \\name form remains in the buffer."
4151 :group 'org-appearance
4152 :version "24.1"
4153 :type 'boolean)
4155 (defcustom org-pretty-entities-include-sub-superscripts t
4156 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4157 :group 'org-appearance
4158 :version "24.1"
4159 :type 'boolean)
4161 (defvar org-emph-re nil
4162 "Regular expression for matching emphasis.
4163 After a match, the match groups contain these elements:
4164 0 The match of the full regular expression, including the characters
4165 before and after the proper match
4166 1 The character before the proper match, or empty at beginning of line
4167 2 The proper match, including the leading and trailing markers
4168 3 The leading marker like * or /, indicating the type of highlighting
4169 4 The text between the emphasis markers, not including the markers
4170 5 The character after the match, empty at the end of a line")
4171 (defvar org-verbatim-re nil
4172 "Regular expression for matching verbatim text.")
4173 (defvar org-emphasis-regexp-components) ; defined just below
4174 (defvar org-emphasis-alist) ; defined just below
4175 (defun org-set-emph-re (var val)
4176 "Set variable and compute the emphasis regular expression."
4177 (set var val)
4178 (when (and (boundp 'org-emphasis-alist)
4179 (boundp 'org-emphasis-regexp-components)
4180 org-emphasis-alist org-emphasis-regexp-components)
4181 (let* ((e org-emphasis-regexp-components)
4182 (pre (car e))
4183 (post (nth 1 e))
4184 (border (nth 2 e))
4185 (body (nth 3 e))
4186 (nl (nth 4 e))
4187 (body1 (concat body "*?"))
4188 (markers (mapconcat 'car org-emphasis-alist ""))
4189 (vmarkers (mapconcat
4190 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4191 org-emphasis-alist "")))
4192 ;; make sure special characters appear at the right position in the class
4193 (if (string-match "\\^" markers)
4194 (setq markers (concat (replace-match "" t t markers) "^")))
4195 (if (string-match "-" markers)
4196 (setq markers (concat (replace-match "" t t markers) "-")))
4197 (if (string-match "\\^" vmarkers)
4198 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4199 (if (string-match "-" vmarkers)
4200 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4201 (if (> nl 0)
4202 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4203 (int-to-string nl) "\\}")))
4204 ;; Make the regexp
4205 (setq org-emph-re
4206 (concat "\\([" pre "]\\|^\\)"
4207 "\\("
4208 "\\([" markers "]\\)"
4209 "\\("
4210 "[^" border "]\\|"
4211 "[^" border "]"
4212 body1
4213 "[^" border "]"
4214 "\\)"
4215 "\\3\\)"
4216 "\\([" post "]\\|$\\)"))
4217 (setq org-verbatim-re
4218 (concat "\\([" pre "]\\|^\\)"
4219 "\\("
4220 "\\([" vmarkers "]\\)"
4221 "\\("
4222 "[^" border "]\\|"
4223 "[^" border "]"
4224 body1
4225 "[^" border "]"
4226 "\\)"
4227 "\\3\\)"
4228 "\\([" post "]\\|$\\)")))))
4230 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4231 ;; set this option proved cumbersome. See this message/thread:
4232 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4233 (defvar org-emphasis-regexp-components
4234 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4235 "Components used to build the regular expression for emphasis.
4236 This is a list with five entries. Terminology: In an emphasis string
4237 like \" *strong word* \", we call the initial space PREMATCH, the final
4238 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4239 and \"trong wor\" is the body. The different components in this variable
4240 specify what is allowed/forbidden in each part:
4242 pre Chars allowed as prematch. Beginning of line will be allowed too.
4243 post Chars allowed as postmatch. End of line will be allowed too.
4244 border The chars *forbidden* as border characters.
4245 body-regexp A regexp like \".\" to match a body character. Don't use
4246 non-shy groups here, and don't allow newline here.
4247 newline The maximum number of newlines allowed in an emphasis exp.
4249 You need to reload Org or to restart Emacs after customizing this.")
4251 (defcustom org-emphasis-alist
4252 `(("*" bold)
4253 ("/" italic)
4254 ("_" underline)
4255 ("=" org-code verbatim)
4256 ("~" org-verbatim verbatim)
4257 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4258 "Alist of characters and faces to emphasize text.
4259 Text starting and ending with a special character will be emphasized,
4260 for example *bold*, _underlined_ and /italic/. This variable sets the
4261 marker characters and the face to be used by font-lock for highlighting
4262 in Org-mode Emacs buffers.
4264 You need to reload Org or to restart Emacs after customizing this."
4265 :group 'org-appearance
4266 :set 'org-set-emph-re
4267 :version "24.4"
4268 :package-version '(Org . "8.0")
4269 :type '(repeat
4270 (list
4271 (string :tag "Marker character")
4272 (choice
4273 (face :tag "Font-lock-face")
4274 (plist :tag "Face property list"))
4275 (option (const verbatim)))))
4277 (defvar org-protecting-blocks
4278 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4279 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4280 This is needed for font-lock setup.")
4282 ;;; Miscellaneous options
4284 (defgroup org-completion nil
4285 "Completion in Org-mode."
4286 :tag "Org Completion"
4287 :group 'org)
4289 (defcustom org-completion-use-ido nil
4290 "Non-nil means use ido completion wherever possible.
4291 Note that `ido-mode' must be active for this variable to be relevant.
4292 If you decide to turn this variable on, you might well want to turn off
4293 `org-outline-path-complete-in-steps'.
4294 See also `org-completion-use-iswitchb'."
4295 :group 'org-completion
4296 :type 'boolean)
4298 (defcustom org-completion-use-iswitchb nil
4299 "Non-nil means use iswitchb completion wherever possible.
4300 Note that `iswitchb-mode' must be active for this variable to be relevant.
4301 If you decide to turn this variable on, you might well want to turn off
4302 `org-outline-path-complete-in-steps'.
4303 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4304 :group 'org-completion
4305 :type 'boolean)
4307 (defcustom org-completion-fallback-command 'hippie-expand
4308 "The expansion command called by \\[pcomplete] in normal context.
4309 Normal means, no org-mode-specific context."
4310 :group 'org-completion
4311 :type 'function)
4313 ;;; Functions and variables from their packages
4314 ;; Declared here to avoid compiler warnings
4316 ;; XEmacs only
4317 (defvar outline-mode-menu-heading)
4318 (defvar outline-mode-menu-show)
4319 (defvar outline-mode-menu-hide)
4320 (defvar zmacs-regions) ; XEmacs regions
4322 ;; Emacs only
4323 (defvar mark-active)
4325 ;; Various packages
4326 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4327 (declare-function calendar-forward-day "cal-move" (arg))
4328 (declare-function calendar-goto-date "cal-move" (date))
4329 (declare-function calendar-goto-today "cal-move" ())
4330 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4331 (defvar calc-embedded-close-formula)
4332 (defvar calc-embedded-open-formula)
4333 (declare-function cdlatex-tab "ext:cdlatex" ())
4334 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4335 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4336 (defvar font-lock-unfontify-region-function)
4337 (declare-function iswitchb-read-buffer "iswitchb"
4338 (prompt &optional default require-match start matches-set))
4339 (defvar iswitchb-temp-buflist)
4340 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4341 (defvar org-agenda-tags-todo-honor-ignore-options)
4342 (declare-function org-agenda-skip "org-agenda" ())
4343 (declare-function
4344 org-agenda-format-item "org-agenda"
4345 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4346 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4347 (declare-function org-agenda-change-all-lines "org-agenda"
4348 (newhead hdmarker &optional fixface just-this))
4349 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4350 (declare-function org-agenda-maybe-redo "org-agenda" ())
4351 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4352 (beg end))
4353 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4354 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4355 "org-agenda" (&optional end))
4356 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4357 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4358 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4359 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4360 (declare-function org-indent-mode "org-indent" (&optional arg))
4361 (declare-function parse-time-string "parse-time" (string))
4362 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4363 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4364 (defvar remember-data-file)
4365 (defvar texmathp-why)
4366 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4367 (declare-function table--at-cell-p "table" (position &optional object at-column))
4369 ;;;###autoload
4370 (defun turn-on-orgtbl ()
4371 "Unconditionally turn on `orgtbl-mode'."
4372 (require 'org-table)
4373 (orgtbl-mode 1))
4375 (defun org-at-table-p (&optional table-type)
4376 "Return t if the cursor is inside an org-type table.
4377 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4378 (if org-enable-table-editor
4379 (save-excursion
4380 (beginning-of-line 1)
4381 (looking-at (if table-type org-table-any-line-regexp
4382 org-table-line-regexp)))
4383 nil))
4384 (defsubst org-table-p () (org-at-table-p))
4386 (defun org-at-table.el-p ()
4387 "Return t if and only if we are at a table.el table."
4388 (and (org-at-table-p 'any)
4389 (save-excursion
4390 (goto-char (org-table-begin 'any))
4391 (looking-at org-table1-hline-regexp))))
4393 (defun org-table-recognize-table.el ()
4394 "If there is a table.el table nearby, recognize it and move into it."
4395 (if org-table-tab-recognizes-table.el
4396 (if (org-at-table.el-p)
4397 (progn
4398 (beginning-of-line 1)
4399 (if (looking-at org-table-dataline-regexp)
4401 (if (looking-at org-table1-hline-regexp)
4402 (progn
4403 (beginning-of-line 2)
4404 (if (looking-at org-table-any-border-regexp)
4405 (beginning-of-line -1)))))
4406 (if (re-search-forward "|" (org-table-end t) t)
4407 (progn
4408 (require 'table)
4409 (if (table--at-cell-p (point))
4411 (message "recognizing table.el table...")
4412 (table-recognize-table)
4413 (message "recognizing table.el table...done")))
4414 (error "This should not happen"))
4416 nil)
4417 nil))
4419 (defun org-at-table-hline-p ()
4420 "Return t if the cursor is inside a hline in a table."
4421 (if org-enable-table-editor
4422 (save-excursion
4423 (beginning-of-line 1)
4424 (looking-at org-table-hline-regexp))
4425 nil))
4427 (defun org-table-map-tables (function &optional quietly)
4428 "Apply FUNCTION to the start of all tables in the buffer."
4429 (save-excursion
4430 (save-restriction
4431 (widen)
4432 (goto-char (point-min))
4433 (while (re-search-forward org-table-any-line-regexp nil t)
4434 (unless quietly
4435 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4436 (beginning-of-line 1)
4437 (when (and (looking-at org-table-line-regexp)
4438 ;; Exclude tables in src/example/verbatim/clocktable blocks
4439 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4440 (save-excursion (funcall function))
4441 (or (looking-at org-table-line-regexp)
4442 (forward-char 1)))
4443 (re-search-forward org-table-any-border-regexp nil 1))))
4444 (unless quietly (message "Mapping tables: done")))
4446 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4447 (declare-function org-clock-update-mode-line "org-clock" ())
4448 (declare-function org-resolve-clocks "org-clock"
4449 (&optional also-non-dangling-p prompt last-valid))
4451 (defun org-at-TBLFM-p (&optional pos)
4452 "Return t when point (or POS) is in #+TBLFM line."
4453 (save-excursion
4454 (let ((pos pos)))
4455 (goto-char (or pos (point)))
4456 (beginning-of-line 1)
4457 (looking-at org-TBLFM-regexp)))
4459 (defvar org-clock-start-time)
4460 (defvar org-clock-marker (make-marker)
4461 "Marker recording the last clock-in.")
4462 (defvar org-clock-hd-marker (make-marker)
4463 "Marker recording the last clock-in, but the headline position.")
4464 (defvar org-clock-heading ""
4465 "The heading of the current clock entry.")
4466 (defun org-clock-is-active ()
4467 "Return the buffer where the clock is currently running.
4468 Return nil if no clock is running."
4469 (marker-buffer org-clock-marker))
4471 (defun org-check-running-clock ()
4472 "Check if the current buffer contains the running clock.
4473 If yes, offer to stop it and to save the buffer with the changes."
4474 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4475 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4476 (buffer-name))))
4477 (org-clock-out)
4478 (when (y-or-n-p "Save changed buffer?")
4479 (save-buffer))))
4481 (defun org-clocktable-try-shift (dir n)
4482 "Check if this line starts a clock table, if yes, shift the time block."
4483 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4484 (org-clocktable-shift dir n)))
4486 ;;;###autoload
4487 (defun org-clock-persistence-insinuate ()
4488 "Set up hooks for clock persistence."
4489 (require 'org-clock)
4490 (add-hook 'org-mode-hook 'org-clock-load)
4491 (add-hook 'kill-emacs-hook 'org-clock-save))
4493 (defgroup org-archive nil
4494 "Options concerning archiving in Org-mode."
4495 :tag "Org Archive"
4496 :group 'org-structure)
4498 (defcustom org-archive-location "%s_archive::"
4499 "The location where subtrees should be archived.
4501 The value of this variable is a string, consisting of two parts,
4502 separated by a double-colon. The first part is a filename and
4503 the second part is a headline.
4505 When the filename is omitted, archiving happens in the same file.
4506 %s in the filename will be replaced by the current file
4507 name (without the directory part). Archiving to a different file
4508 is useful to keep archived entries from contributing to the
4509 Org-mode Agenda.
4511 The archived entries will be filed as subtrees of the specified
4512 headline. When the headline is omitted, the subtrees are simply
4513 filed away at the end of the file, as top-level entries. Also in
4514 the heading you can use %s to represent the file name, this can be
4515 useful when using the same archive for a number of different files.
4517 Here are a few examples:
4518 \"%s_archive::\"
4519 If the current file is Projects.org, archive in file
4520 Projects.org_archive, as top-level trees. This is the default.
4522 \"::* Archived Tasks\"
4523 Archive in the current file, under the top-level headline
4524 \"* Archived Tasks\".
4526 \"~/org/archive.org::\"
4527 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4529 \"~/org/archive.org::* From %s\"
4530 Archive in file ~/org/archive.org (absolute path), under headlines
4531 \"From FILENAME\" where file name is the current file name.
4533 \"~/org/datetree.org::datetree/* Finished Tasks\"
4534 The \"datetree/\" string is special, signifying to archive
4535 items to the datetree. Items are placed in either the CLOSED
4536 date of the item, or the current date if there is no CLOSED date.
4537 The heading will be a subentry to the current date. There doesn't
4538 need to be a heading, but there always needs to be a slash after
4539 datetree. For example, to store archived items directly in the
4540 datetree, use \"~/org/datetree.org::datetree/\".
4542 \"basement::** Finished Tasks\"
4543 Archive in file ./basement (relative path), as level 3 trees
4544 below the level 2 heading \"** Finished Tasks\".
4546 You may set this option on a per-file basis by adding to the buffer a
4547 line like
4549 #+ARCHIVE: basement::** Finished Tasks
4551 You may also define it locally for a subtree by setting an ARCHIVE property
4552 in the entry. If such a property is found in an entry, or anywhere up
4553 the hierarchy, it will be used."
4554 :group 'org-archive
4555 :type 'string)
4557 (defcustom org-agenda-skip-archived-trees t
4558 "Non-nil means the agenda will skip any items located in archived trees.
4559 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4560 variable is no longer recommended, you should leave it at the value t.
4561 Instead, use the key `v' to cycle the archives-mode in the agenda."
4562 :group 'org-archive
4563 :group 'org-agenda-skip
4564 :type 'boolean)
4566 (defcustom org-columns-skip-archived-trees t
4567 "Non-nil means ignore archived trees when creating column view."
4568 :group 'org-archive
4569 :group 'org-properties
4570 :type 'boolean)
4572 (defcustom org-cycle-open-archived-trees nil
4573 "Non-nil means `org-cycle' will open archived trees.
4574 An archived tree is a tree marked with the tag ARCHIVE.
4575 When nil, archived trees will stay folded. You can still open them with
4576 normal outline commands like `show-all', but not with the cycling commands."
4577 :group 'org-archive
4578 :group 'org-cycle
4579 :type 'boolean)
4581 (defcustom org-sparse-tree-open-archived-trees nil
4582 "Non-nil means sparse tree construction shows matches in archived trees.
4583 When nil, matches in these trees are highlighted, but the trees are kept in
4584 collapsed state."
4585 :group 'org-archive
4586 :group 'org-sparse-trees
4587 :type 'boolean)
4589 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4590 "The default date type when building a sparse tree.
4591 When this is nil, a date is a scheduled or a deadline timestamp.
4592 Otherwise, these types are allowed:
4594 all: all timestamps
4595 active: only active timestamps (<...>)
4596 inactive: only inactive timestamps (<...)
4597 scheduled: only scheduled timestamps
4598 deadline: only deadline timestamps"
4599 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4600 (const :tag "All timestamps" all)
4601 (const :tag "Only active timestamps" active)
4602 (const :tag "Only inactive timestamps" inactive)
4603 (const :tag "Only scheduled timestamps" scheduled)
4604 (const :tag "Only deadline timestamps" deadline)
4605 (const :tag "Only closed timestamps" closed))
4606 :version "24.3"
4607 :group 'org-sparse-trees)
4609 (defun org-cycle-hide-archived-subtrees (state)
4610 "Re-hide all archived subtrees after a visibility state change."
4611 (when (and (not org-cycle-open-archived-trees)
4612 (not (memq state '(overview folded))))
4613 (save-excursion
4614 (let* ((globalp (memq state '(contents all)))
4615 (beg (if globalp (point-min) (point)))
4616 (end (if globalp (point-max) (org-end-of-subtree t))))
4617 (org-hide-archived-subtrees beg end)
4618 (goto-char beg)
4619 (if (looking-at (concat ".*:" org-archive-tag ":"))
4620 (message "%s" (substitute-command-keys
4621 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4623 (defun org-force-cycle-archived ()
4624 "Cycle subtree even if it is archived."
4625 (interactive)
4626 (setq this-command 'org-cycle)
4627 (let ((org-cycle-open-archived-trees t))
4628 (call-interactively 'org-cycle)))
4630 (defun org-hide-archived-subtrees (beg end)
4631 "Re-hide all archived subtrees after a visibility state change."
4632 (save-excursion
4633 (let* ((re (concat ":" org-archive-tag ":")))
4634 (goto-char beg)
4635 (while (re-search-forward re end t)
4636 (when (org-at-heading-p)
4637 (org-flag-subtree t)
4638 (org-end-of-subtree t))))))
4640 (declare-function outline-end-of-heading "outline" ())
4641 (declare-function outline-flag-region "outline" (from to flag))
4642 (defun org-flag-subtree (flag)
4643 (save-excursion
4644 (org-back-to-heading t)
4645 (outline-end-of-heading)
4646 (outline-flag-region (point)
4647 (progn (org-end-of-subtree t) (point))
4648 flag)))
4650 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4652 ;; Declare Column View Code
4654 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4655 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4656 (declare-function org-columns-compute "org-colview" (property))
4658 ;; Declare ID code
4660 (declare-function org-id-store-link "org-id")
4661 (declare-function org-id-locations-load "org-id")
4662 (declare-function org-id-locations-save "org-id")
4663 (defvar org-id-track-globally)
4665 ;;; Variables for pre-computed regular expressions, all buffer local
4667 (defvar org-todo-regexp nil
4668 "Matches any of the TODO state keywords.")
4669 (make-variable-buffer-local 'org-todo-regexp)
4670 (defvar org-not-done-regexp nil
4671 "Matches any of the TODO state keywords except the last one.")
4672 (make-variable-buffer-local 'org-not-done-regexp)
4673 (defvar org-not-done-heading-regexp nil
4674 "Matches a TODO headline that is not done.")
4675 (make-variable-buffer-local 'org-not-done-regexp)
4676 (defvar org-todo-line-regexp nil
4677 "Matches a headline and puts TODO state into group 2 if present.")
4678 (make-variable-buffer-local 'org-todo-line-regexp)
4679 (defvar org-complex-heading-regexp nil
4680 "Matches a headline and puts everything into groups:
4681 group 1: the stars
4682 group 2: The todo keyword, maybe
4683 group 3: Priority cookie
4684 group 4: True headline
4685 group 5: Tags")
4686 (make-variable-buffer-local 'org-complex-heading-regexp)
4687 (defvar org-complex-heading-regexp-format nil
4688 "Printf format to make regexp to match an exact headline.
4689 This regexp will match the headline of any node which has the
4690 exact headline text that is put into the format, but may have any
4691 TODO state, priority and tags.")
4692 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4693 (defvar org-todo-line-tags-regexp nil
4694 "Matches a headline and puts TODO state into group 2 if present.
4695 Also put tags into group 4 if tags are present.")
4696 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4697 (defvar org-ds-keyword-length 12
4698 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4699 (make-variable-buffer-local 'org-ds-keyword-length)
4700 (defvar org-deadline-regexp nil
4701 "Matches the DEADLINE keyword.")
4702 (make-variable-buffer-local 'org-deadline-regexp)
4703 (defvar org-deadline-time-regexp nil
4704 "Matches the DEADLINE keyword together with a time stamp.")
4705 (make-variable-buffer-local 'org-deadline-time-regexp)
4706 (defvar org-deadline-time-hour-regexp nil
4707 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4708 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4709 (defvar org-deadline-line-regexp nil
4710 "Matches the DEADLINE keyword and the rest of the line.")
4711 (make-variable-buffer-local 'org-deadline-line-regexp)
4712 (defvar org-scheduled-regexp nil
4713 "Matches the SCHEDULED keyword.")
4714 (make-variable-buffer-local 'org-scheduled-regexp)
4715 (defvar org-scheduled-time-regexp nil
4716 "Matches the SCHEDULED keyword together with a time stamp.")
4717 (make-variable-buffer-local 'org-scheduled-time-regexp)
4718 (defvar org-scheduled-time-hour-regexp nil
4719 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4720 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4721 (defvar org-closed-time-regexp nil
4722 "Matches the CLOSED keyword together with a time stamp.")
4723 (make-variable-buffer-local 'org-closed-time-regexp)
4725 (defvar org-keyword-time-regexp nil
4726 "Matches any of the 4 keywords, together with the time stamp.")
4727 (make-variable-buffer-local 'org-keyword-time-regexp)
4728 (defvar org-keyword-time-not-clock-regexp nil
4729 "Matches any of the 3 keywords, together with the time stamp.")
4730 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4731 (defvar org-maybe-keyword-time-regexp nil
4732 "Matches a timestamp, possibly preceded by a keyword.")
4733 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4734 (defvar org-all-time-keywords nil
4735 "List of time keywords.")
4736 (make-variable-buffer-local 'org-all-time-keywords)
4738 (defconst org-plain-time-of-day-regexp
4739 (concat
4740 "\\(\\<[012]?[0-9]"
4741 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4742 "\\(--?"
4743 "\\(\\<[012]?[0-9]"
4744 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4745 "\\)?")
4746 "Regular expression to match a plain time or time range.
4747 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4748 groups carry important information:
4749 0 the full match
4750 1 the first time, range or not
4751 8 the second time, if it is a range.")
4753 (defconst org-plain-time-extension-regexp
4754 (concat
4755 "\\(\\<[012]?[0-9]"
4756 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4757 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4758 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4759 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4760 groups carry important information:
4761 0 the full match
4762 7 hours of duration
4763 9 minutes of duration")
4765 (defconst org-stamp-time-of-day-regexp
4766 (concat
4767 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4768 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4769 "\\(--?"
4770 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4771 "Regular expression to match a timestamp time or time range.
4772 After a match, the following groups carry important information:
4773 0 the full match
4774 1 date plus weekday, for back referencing to make sure both times are on the same day
4775 2 the first time, range or not
4776 4 the second time, if it is a range.")
4778 (defconst org-startup-options
4779 '(("fold" org-startup-folded t)
4780 ("overview" org-startup-folded t)
4781 ("nofold" org-startup-folded nil)
4782 ("showall" org-startup-folded nil)
4783 ("showeverything" org-startup-folded showeverything)
4784 ("content" org-startup-folded content)
4785 ("indent" org-startup-indented t)
4786 ("noindent" org-startup-indented nil)
4787 ("hidestars" org-hide-leading-stars t)
4788 ("showstars" org-hide-leading-stars nil)
4789 ("odd" org-odd-levels-only t)
4790 ("oddeven" org-odd-levels-only nil)
4791 ("align" org-startup-align-all-tables t)
4792 ("noalign" org-startup-align-all-tables nil)
4793 ("inlineimages" org-startup-with-inline-images t)
4794 ("noinlineimages" org-startup-with-inline-images nil)
4795 ("latexpreview" org-startup-with-latex-preview t)
4796 ("nolatexpreview" org-startup-with-latex-preview nil)
4797 ("customtime" org-display-custom-times t)
4798 ("logdone" org-log-done time)
4799 ("lognotedone" org-log-done note)
4800 ("nologdone" org-log-done nil)
4801 ("lognoteclock-out" org-log-note-clock-out t)
4802 ("nolognoteclock-out" org-log-note-clock-out nil)
4803 ("logrepeat" org-log-repeat state)
4804 ("lognoterepeat" org-log-repeat note)
4805 ("logdrawer" org-log-into-drawer t)
4806 ("nologdrawer" org-log-into-drawer nil)
4807 ("logstatesreversed" org-log-states-order-reversed t)
4808 ("nologstatesreversed" org-log-states-order-reversed nil)
4809 ("nologrepeat" org-log-repeat nil)
4810 ("logreschedule" org-log-reschedule time)
4811 ("lognotereschedule" org-log-reschedule note)
4812 ("nologreschedule" org-log-reschedule nil)
4813 ("logredeadline" org-log-redeadline time)
4814 ("lognoteredeadline" org-log-redeadline note)
4815 ("nologredeadline" org-log-redeadline nil)
4816 ("logrefile" org-log-refile time)
4817 ("lognoterefile" org-log-refile note)
4818 ("nologrefile" org-log-refile nil)
4819 ("fninline" org-footnote-define-inline t)
4820 ("nofninline" org-footnote-define-inline nil)
4821 ("fnlocal" org-footnote-section nil)
4822 ("fnauto" org-footnote-auto-label t)
4823 ("fnprompt" org-footnote-auto-label nil)
4824 ("fnconfirm" org-footnote-auto-label confirm)
4825 ("fnplain" org-footnote-auto-label plain)
4826 ("fnadjust" org-footnote-auto-adjust t)
4827 ("nofnadjust" org-footnote-auto-adjust nil)
4828 ("constcgs" constants-unit-system cgs)
4829 ("constSI" constants-unit-system SI)
4830 ("noptag" org-tag-persistent-alist nil)
4831 ("hideblocks" org-hide-block-startup t)
4832 ("nohideblocks" org-hide-block-startup nil)
4833 ("beamer" org-startup-with-beamer-mode t)
4834 ("entitiespretty" org-pretty-entities t)
4835 ("entitiesplain" org-pretty-entities nil))
4836 "Variable associated with STARTUP options for org-mode.
4837 Each element is a list of three items: the startup options (as written
4838 in the #+STARTUP line), the corresponding variable, and the value to set
4839 this variable to if the option is found. An optional forth element PUSH
4840 means to push this value onto the list in the variable.")
4842 (defun org-update-property-plist (key val props)
4843 "Update PROPS with KEY and VAL."
4844 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4845 (key (if appending (substring key 0 (- (length key) 1)) key))
4846 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4847 (previous (cdr (assoc key props))))
4848 (if appending
4849 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4850 (cons (cons key val) remainder))))
4852 (defcustom org-group-tags t
4853 "When non-nil (the default), use group tags.
4854 This can be turned on/off through `org-toggle-tags-groups'."
4855 :group 'org-tags
4856 :group 'org-startup
4857 :type 'boolean)
4859 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4861 (defun org-toggle-tags-groups ()
4862 "Toggle support for group tags.
4863 Support for group tags is controlled by the option
4864 `org-group-tags', which is non-nil by default."
4865 (interactive)
4866 (setq org-group-tags (not org-group-tags))
4867 (cond ((and (derived-mode-p 'org-agenda-mode)
4868 org-group-tags)
4869 (org-agenda-redo))
4870 ((derived-mode-p 'org-mode)
4871 (let ((org-inhibit-startup t)) (org-mode))))
4872 (message "Groups tags support has been turned %s"
4873 (if org-group-tags "on" "off")))
4875 (defun org-set-regexps-and-options-for-tags ()
4876 "Precompute variables used for tags."
4877 (when (derived-mode-p 'org-mode)
4878 (org-set-local 'org-file-tags nil)
4879 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4880 (splitre "[ \t]+")
4881 (start 0)
4882 tags ftags key value)
4883 (save-excursion
4884 (save-restriction
4885 (widen)
4886 (goto-char (point-min))
4887 (while (re-search-forward re nil t)
4888 (setq key (upcase (org-match-string-no-properties 1))
4889 value (org-match-string-no-properties 2))
4890 (if (stringp value) (setq value (org-trim value)))
4891 (cond
4892 ((equal key "TAGS")
4893 (setq tags (append tags (if tags '("\\n") nil)
4894 (org-split-string value splitre))))
4895 ((equal key "FILETAGS")
4896 (when (string-match "\\S-" value)
4897 (setq ftags
4898 (append
4899 ftags
4900 (apply 'append
4901 (mapcar (lambda (x) (org-split-string x ":"))
4902 (org-split-string value)))))))))))
4903 ;; Process the file tags.
4904 (and ftags (org-set-local 'org-file-tags
4905 (mapcar 'org-add-prop-inherited ftags)))
4906 (org-set-local 'org-tag-groups-alist nil)
4907 ;; Process the tags.
4908 (when (and (not tags) org-tag-alist)
4909 (setq tags
4910 (mapcar
4911 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4912 ((eq (car tg) :endgroup) "}")
4913 ((eq (car tg) :grouptags) ":")
4914 ((eq (car tg) :newline) "\n")
4915 (t (concat (car tg)
4916 (if (characterp (cdr tg))
4917 (format "(%s)" (char-to-string (cdr tg))) "")))))
4918 org-tag-alist)))
4919 (let (e tgs g)
4920 (while (setq e (pop tags))
4921 (cond
4922 ((equal e "{")
4923 (progn (push '(:startgroup) tgs)
4924 (when (equal (nth 1 tags) ":")
4925 (push (list (replace-regexp-in-string
4926 "(.+)$" "" (nth 0 tags)))
4927 org-tag-groups-alist)
4928 (setq g 0))))
4929 ((equal e ":") (push '(:grouptags) tgs))
4930 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4931 ((equal e "\\n") (push '(:newline) tgs))
4932 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4933 (push (cons (match-string 1 e)
4934 (string-to-char (match-string 2 e))) tgs)
4935 (if (and g (> g 0))
4936 (setcar org-tag-groups-alist
4937 (append (car org-tag-groups-alist)
4938 (list (match-string 1 e)))))
4939 (if g (setq g (1+ g))))
4940 (t (push (list e) tgs)
4941 (if (and g (> g 0))
4942 (setcar org-tag-groups-alist
4943 (append (car org-tag-groups-alist) (list e))))
4944 (if g (setq g (1+ g))))))
4945 (org-set-local 'org-tag-alist nil)
4946 (while (setq e (pop tgs))
4947 (or (and (stringp (car e))
4948 (assoc (car e) org-tag-alist))
4949 (push e org-tag-alist)))
4950 ;; Return a list with tag variables
4951 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4953 (defvar org-ota nil)
4954 (defun org-set-regexps-and-options ()
4955 "Precompute regular expressions used in the current buffer."
4956 (when (derived-mode-p 'org-mode)
4957 (org-set-local 'org-todo-kwd-alist nil)
4958 (org-set-local 'org-todo-key-alist nil)
4959 (org-set-local 'org-todo-key-trigger nil)
4960 (org-set-local 'org-todo-keywords-1 nil)
4961 (org-set-local 'org-done-keywords nil)
4962 (org-set-local 'org-todo-heads nil)
4963 (org-set-local 'org-todo-sets nil)
4964 (org-set-local 'org-todo-log-states nil)
4965 (org-set-local 'org-file-properties nil)
4966 (let ((re (org-make-options-regexp
4967 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4968 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4969 "SETUPFILE" "OPTIONS")
4970 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4971 (splitre "[ \t]+")
4972 (scripts org-use-sub-superscripts)
4973 kwds kws0 kwsa key log value cat arch const links hw dws
4974 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4975 (start 0))
4976 (save-excursion
4977 (save-restriction
4978 (widen)
4979 (goto-char (point-min))
4980 (while
4981 (or (and
4982 ext-setup-or-nil
4983 (not org-ota)
4984 (let (ret)
4985 (with-temp-buffer
4986 (insert ext-setup-or-nil)
4987 (let ((major-mode 'org-mode) org-ota)
4988 (setq ret (save-match-data
4989 (org-set-regexps-and-options-for-tags)))))
4990 ;; Append setupfile tags to existing tags
4991 (setq org-ota t)
4992 (setq org-file-tags
4993 (delq nil (append org-file-tags (nth 0 ret)))
4994 org-tag-alist
4995 (delq nil (append org-tag-alist (nth 1 ret)))
4996 org-tag-groups-alist
4997 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4998 (and ext-setup-or-nil
4999 (string-match re ext-setup-or-nil start)
5000 (setq start (match-end 0)))
5001 (and (setq ext-setup-or-nil nil start 0)
5002 (re-search-forward re nil t)))
5003 (setq key (upcase (match-string 1 ext-setup-or-nil))
5004 value (org-match-string-no-properties 2 ext-setup-or-nil))
5005 (if (stringp value) (setq value (org-trim value)))
5006 (cond
5007 ((equal key "CATEGORY")
5008 (setq cat value))
5009 ((member key '("SEQ_TODO" "TODO"))
5010 (push (cons 'sequence (org-split-string value splitre)) kwds))
5011 ((equal key "TYP_TODO")
5012 (push (cons 'type (org-split-string value splitre)) kwds))
5013 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
5014 ;; general TODO-like setup
5015 (push (cons (intern (downcase (match-string 1 key)))
5016 (org-split-string value splitre)) kwds))
5017 ((equal key "COLUMNS")
5018 (org-set-local 'org-columns-default-format value))
5019 ((equal key "LINK")
5020 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5021 (push (cons (match-string 1 value)
5022 (org-trim (match-string 2 value)))
5023 links)))
5024 ((equal key "PRIORITIES")
5025 (setq prio (org-split-string value " +")))
5026 ((equal key "PROPERTY")
5027 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5028 (setq props (org-update-property-plist (match-string 1 value)
5029 (match-string 2 value)
5030 props))))
5031 ((equal key "CONSTANTS")
5032 (org-table-set-constants))
5033 ((equal key "STARTUP")
5034 (let ((opts (org-split-string value splitre))
5035 l var val)
5036 (while (setq l (pop opts))
5037 (when (setq l (assoc l org-startup-options))
5038 (setq var (nth 1 l) val (nth 2 l))
5039 (if (not (nth 3 l))
5040 (set (make-local-variable var) val)
5041 (if (not (listp (symbol-value var)))
5042 (set (make-local-variable var) nil))
5043 (set (make-local-variable var) (symbol-value var))
5044 (add-to-list var val))))))
5045 ((equal key "ARCHIVE")
5046 (setq arch value)
5047 (remove-text-properties 0 (length arch)
5048 '(face t fontified t) arch))
5049 ((equal key "OPTIONS")
5050 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5051 (setq scripts (read (match-string 2 value)))))
5052 ((and (equal key "SETUPFILE")
5053 ;; Prevent checking in Gnus messages
5054 (not buffer-read-only))
5055 (setq setup-contents (org-file-contents
5056 (expand-file-name
5057 (org-remove-double-quotes value))
5058 'noerror))
5059 (if (not ext-setup-or-nil)
5060 (setq ext-setup-or-nil setup-contents start 0)
5061 (setq ext-setup-or-nil
5062 (concat (substring ext-setup-or-nil 0 start)
5063 "\n" setup-contents "\n"
5064 (substring ext-setup-or-nil start)))))))
5065 ;; search for property blocks
5066 (goto-char (point-min))
5067 (while (re-search-forward org-block-regexp nil t)
5068 (when (equal "PROPERTY" (upcase (match-string 1)))
5069 (setq value (replace-regexp-in-string
5070 "[\n\r]" " " (match-string 4)))
5071 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5072 (setq props (org-update-property-plist (match-string 1 value)
5073 (match-string 2 value)
5074 props)))))))
5075 (org-set-local 'org-use-sub-superscripts scripts)
5076 (when cat
5077 (org-set-local 'org-category (intern cat))
5078 (push (cons "CATEGORY" cat) props))
5079 (when prio
5080 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5081 (setq prio (mapcar 'string-to-char prio))
5082 (org-set-local 'org-highest-priority (nth 0 prio))
5083 (org-set-local 'org-lowest-priority (nth 1 prio))
5084 (org-set-local 'org-default-priority (nth 2 prio)))
5085 (and props (org-set-local 'org-file-properties (nreverse props)))
5086 (and arch (org-set-local 'org-archive-location arch))
5087 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5088 ;; Process the TODO keywords
5089 (unless kwds
5090 ;; Use the global values as if they had been given locally.
5091 (setq kwds (default-value 'org-todo-keywords))
5092 (if (stringp (car kwds))
5093 (setq kwds (list (cons org-todo-interpretation
5094 (default-value 'org-todo-keywords)))))
5095 (setq kwds (reverse kwds)))
5096 (setq kwds (nreverse kwds))
5097 (let (inter kws kw)
5098 (while (setq kws (pop kwds))
5099 (let ((kws (or
5100 (run-hook-with-args-until-success
5101 'org-todo-setup-filter-hook kws)
5102 kws)))
5103 (setq inter (pop kws) sep (member "|" kws)
5104 kws0 (delete "|" (copy-sequence kws))
5105 kwsa nil
5106 kws1 (mapcar
5107 (lambda (x)
5108 ;; 1 2
5109 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5110 (progn
5111 (setq kw (match-string 1 x)
5112 key (and (match-end 2) (match-string 2 x))
5113 log (org-extract-log-state-settings x))
5114 (push (cons kw (and key (string-to-char key))) kwsa)
5115 (and log (push log org-todo-log-states))
5117 (error "Invalid TODO keyword %s" x)))
5118 kws0)
5119 kwsa (if kwsa (append '((:startgroup))
5120 (nreverse kwsa)
5121 '((:endgroup))))
5122 hw (car kws1)
5123 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5124 tail (list inter hw (car dws) (org-last dws))))
5125 (add-to-list 'org-todo-heads hw 'append)
5126 (push kws1 org-todo-sets)
5127 (setq org-done-keywords (append org-done-keywords dws nil))
5128 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5129 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5130 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5131 (setq org-todo-sets (nreverse org-todo-sets)
5132 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5133 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5134 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5135 ;; Compute the regular expressions and other local variables.
5136 ;; Using `org-outline-regexp-bol' would complicate them much,
5137 ;; because of the fixed white space at the end of that string.
5138 (if (not org-done-keywords)
5139 (setq org-done-keywords (and org-todo-keywords-1
5140 (list (org-last org-todo-keywords-1)))))
5141 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5142 (length org-scheduled-string)
5143 (length org-clock-string)
5144 (length org-closed-string)))
5145 org-not-done-keywords
5146 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5147 org-todo-regexp
5148 (concat "\\("
5149 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5150 "\\)")
5151 org-not-done-regexp
5152 (concat "\\("
5153 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5154 "\\)")
5155 org-not-done-heading-regexp
5156 (format org-heading-keyword-regexp-format org-not-done-regexp)
5157 org-todo-line-regexp
5158 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5159 org-complex-heading-regexp
5160 (concat "^\\(\\*+\\)"
5161 "\\(?: +" org-todo-regexp "\\)?"
5162 "\\(?: +\\(\\[#.\\]\\)\\)?"
5163 "\\(?: +\\(.*?\\)\\)??"
5164 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5165 "[ \t]*$")
5166 org-complex-heading-regexp-format
5167 (concat "^\\(\\*+\\)"
5168 "\\(?: +" org-todo-regexp "\\)?"
5169 "\\(?: +\\(\\[#.\\]\\)\\)?"
5170 "\\(?: +"
5171 ;; Stats cookies can be stuck to body.
5172 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5173 "\\(%s\\)"
5174 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5175 "\\)"
5176 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5177 "[ \t]*$")
5178 org-todo-line-tags-regexp
5179 (concat "^\\(\\*+\\)"
5180 "\\(?: +" org-todo-regexp "\\)?"
5181 "\\(?: +\\(.*?\\)\\)??"
5182 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5183 "[ \t]*$")
5184 org-deadline-regexp (concat "\\<" org-deadline-string)
5185 org-deadline-time-regexp
5186 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5187 org-deadline-time-hour-regexp
5188 (concat "\\<" org-deadline-string
5189 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5190 org-deadline-line-regexp
5191 (concat "\\<\\(" org-deadline-string "\\).*")
5192 org-scheduled-regexp
5193 (concat "\\<" org-scheduled-string)
5194 org-scheduled-time-regexp
5195 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5196 org-scheduled-time-hour-regexp
5197 (concat "\\<" org-scheduled-string
5198 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5199 org-closed-time-regexp
5200 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5201 org-keyword-time-regexp
5202 (concat "\\<\\(" org-scheduled-string
5203 "\\|" org-deadline-string
5204 "\\|" org-closed-string
5205 "\\|" org-clock-string "\\)"
5206 " *[[<]\\([^]>]+\\)[]>]")
5207 org-keyword-time-not-clock-regexp
5208 (concat "\\<\\(" org-scheduled-string
5209 "\\|" org-deadline-string
5210 "\\|" org-closed-string
5211 "\\)"
5212 " *[[<]\\([^]>]+\\)[]>]")
5213 org-maybe-keyword-time-regexp
5214 (concat "\\(\\<\\(" org-scheduled-string
5215 "\\|" org-deadline-string
5216 "\\|" org-closed-string
5217 "\\|" org-clock-string "\\)\\)?"
5218 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5219 org-all-time-keywords
5220 (mapcar (lambda (w) (substring w 0 -1))
5221 (list org-scheduled-string org-deadline-string
5222 org-clock-string org-closed-string)))
5223 (setq org-ota nil)
5224 (org-compute-latex-and-related-regexp))))
5226 (defun org-file-contents (file &optional noerror)
5227 "Return the contents of FILE, as a string."
5228 (if (or (not file)
5229 (not (file-readable-p file)))
5230 (if noerror
5231 (message "Cannot read file \"%s\"" file)
5232 (error "Cannot read file \"%s\"" file))
5233 (with-temp-buffer
5234 (insert-file-contents file)
5235 (buffer-string))))
5237 (defun org-extract-log-state-settings (x)
5238 "Extract the log state setting from a TODO keyword string.
5239 This will extract info from a string like \"WAIT(w@/!)\"."
5240 (let (kw key log1 log2)
5241 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5242 (setq kw (match-string 1 x)
5243 key (and (match-end 2) (match-string 2 x))
5244 log1 (and (match-end 3) (match-string 3 x))
5245 log2 (and (match-end 4) (match-string 4 x)))
5246 (and (or log1 log2)
5247 (list kw
5248 (and log1 (if (equal log1 "!") 'time 'note))
5249 (and log2 (if (equal log2 "!") 'time 'note)))))))
5251 (defun org-remove-keyword-keys (list)
5252 "Remove a pair of parenthesis at the end of each string in LIST."
5253 (mapcar (lambda (x)
5254 (if (string-match "(.*)$" x)
5255 (substring x 0 (match-beginning 0))
5257 list))
5259 (defun org-assign-fast-keys (alist)
5260 "Assign fast keys to a keyword-key alist.
5261 Respect keys that are already there."
5262 (let (new e (alt ?0))
5263 (while (setq e (pop alist))
5264 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5265 (cdr e)) ;; Key already assigned.
5266 (push e new)
5267 (let ((clist (string-to-list (downcase (car e))))
5268 (used (append new alist)))
5269 (when (= (car clist) ?@)
5270 (pop clist))
5271 (while (and clist (rassoc (car clist) used))
5272 (pop clist))
5273 (unless clist
5274 (while (rassoc alt used)
5275 (incf alt)))
5276 (push (cons (car e) (or (car clist) alt)) new))))
5277 (nreverse new)))
5279 ;;; Some variables used in various places
5281 (defvar org-window-configuration nil
5282 "Used in various places to store a window configuration.")
5283 (defvar org-selected-window nil
5284 "Used in various places to store a window configuration.")
5285 (defvar org-finish-function nil
5286 "Function to be called when `C-c C-c' is used.
5287 This is for getting out of special buffers like capture.")
5290 ;; FIXME: Occasionally check by commenting these, to make sure
5291 ;; no other functions uses these, forgetting to let-bind them.
5292 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5293 (defvar org-last-state)
5294 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5296 ;; Defined somewhere in this file, but used before definition.
5297 (defvar org-entities) ;; defined in org-entities.el
5298 (defvar org-struct-menu)
5299 (defvar org-org-menu)
5300 (defvar org-tbl-menu)
5302 ;;;; Define the Org-mode
5304 ;; We use a before-change function to check if a table might need
5305 ;; an update.
5306 (defvar org-table-may-need-update t
5307 "Indicates that a table might need an update.
5308 This variable is set by `org-before-change-function'.
5309 `org-table-align' sets it back to nil.")
5310 (defun org-before-change-function (beg end)
5311 "Every change indicates that a table might need an update."
5312 (setq org-table-may-need-update t))
5313 (defvar org-mode-map)
5314 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5315 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5316 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5317 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5318 (defvar org-table-buffer-is-an nil)
5320 (defvar bidi-paragraph-direction)
5321 (defvar buffer-face-mode-face)
5323 (require 'outline)
5324 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5325 (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"))
5326 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5328 ;; Other stuff we need.
5329 (require 'time-date)
5330 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5331 (require 'easymenu)
5332 (require 'overlay)
5334 ;; (require 'org-macs) moved higher up in the file before it is first used
5335 (require 'org-entities)
5336 ;; (require 'org-compat) moved higher up in the file before it is first used
5337 (require 'org-faces)
5338 (require 'org-list)
5339 (require 'org-pcomplete)
5340 (require 'org-src)
5341 (require 'org-footnote)
5342 (require 'org-macro)
5344 ;; babel
5345 (require 'ob)
5347 ;;;###autoload
5348 (define-derived-mode org-mode outline-mode "Org"
5349 "Outline-based notes management and organizer, alias
5350 \"Carsten's outline-mode for keeping track of everything.\"
5352 Org-mode develops organizational tasks around a NOTES file which
5353 contains information about projects as plain text. Org-mode is
5354 implemented on top of outline-mode, which is ideal to keep the content
5355 of large files well structured. It supports ToDo items, deadlines and
5356 time stamps, which magically appear in the diary listing of the Emacs
5357 calendar. Tables are easily created with a built-in table editor.
5358 Plain text URL-like links connect to websites, emails (VM), Usenet
5359 messages (Gnus), BBDB entries, and any files related to the project.
5360 For printing and sharing of notes, an Org-mode file (or a part of it)
5361 can be exported as a structured ASCII or HTML file.
5363 The following commands are available:
5365 \\{org-mode-map}"
5367 ;; Get rid of Outline menus, they are not needed
5368 ;; Need to do this here because define-derived-mode sets up
5369 ;; the keymap so late. Still, it is a waste to call this each time
5370 ;; we switch another buffer into org-mode.
5371 (if (featurep 'xemacs)
5372 (when (boundp 'outline-mode-menu-heading)
5373 ;; Assume this is Greg's port, it uses easymenu
5374 (easy-menu-remove outline-mode-menu-heading)
5375 (easy-menu-remove outline-mode-menu-show)
5376 (easy-menu-remove outline-mode-menu-hide))
5377 (define-key org-mode-map [menu-bar headings] 'undefined)
5378 (define-key org-mode-map [menu-bar hide] 'undefined)
5379 (define-key org-mode-map [menu-bar show] 'undefined))
5381 (org-load-modules-maybe)
5382 (easy-menu-add org-org-menu)
5383 (easy-menu-add org-tbl-menu)
5384 (org-install-agenda-files-menu)
5385 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5386 (add-to-invisibility-spec '(org-cwidth))
5387 (add-to-invisibility-spec '(org-hide-block . t))
5388 (when (featurep 'xemacs)
5389 (org-set-local 'line-move-ignore-invisible t))
5390 (org-set-local 'outline-regexp org-outline-regexp)
5391 (org-set-local 'outline-level 'org-outline-level)
5392 (setq bidi-paragraph-direction 'left-to-right)
5393 (when (and org-ellipsis
5394 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5395 (fboundp 'make-glyph-code))
5396 (unless org-display-table
5397 (setq org-display-table (make-display-table)))
5398 (set-display-table-slot
5399 org-display-table 4
5400 (vconcat (mapcar
5401 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5402 org-ellipsis)))
5403 (if (stringp org-ellipsis) org-ellipsis "..."))))
5404 (setq buffer-display-table org-display-table))
5405 (org-set-regexps-and-options-for-tags)
5406 (org-set-regexps-and-options)
5407 (org-set-font-lock-defaults)
5408 (when (and org-tag-faces (not org-tags-special-faces-re))
5409 ;; tag faces set outside customize.... force initialization.
5410 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5411 ;; Calc embedded
5412 (org-set-local 'calc-embedded-open-mode "# ")
5413 ;; Modify a few syntax entries
5414 (modify-syntax-entry ?@ "w")
5415 (modify-syntax-entry ?\" "\"")
5416 (if org-startup-truncated (setq truncate-lines t))
5417 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5418 (org-set-local 'font-lock-unfontify-region-function
5419 'org-unfontify-region)
5420 ;; Activate before-change-function
5421 (org-set-local 'org-table-may-need-update t)
5422 (org-add-hook 'before-change-functions 'org-before-change-function nil
5423 'local)
5424 ;; Check for running clock before killing a buffer
5425 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5426 ;; Initialize macros templates.
5427 (org-macro-initialize-templates)
5428 ;; Initialize radio targets.
5429 (org-update-radio-target-regexp)
5430 ;; Indentation.
5431 (org-set-local 'indent-line-function 'org-indent-line)
5432 (org-set-local 'indent-region-function 'org-indent-region)
5433 ;; Filling and auto-filling.
5434 (org-setup-filling)
5435 ;; Comments.
5436 (org-setup-comments-handling)
5437 ;; Initialize cache.
5438 (org-element-cache-reset)
5439 ;; Beginning/end of defun
5440 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5441 (org-set-local 'end-of-defun-function 'org-forward-element)
5442 ;; Next error for sparse trees
5443 (org-set-local 'next-error-function 'org-occur-next-match)
5444 ;; Make sure dependence stuff works reliably, even for users who set it
5445 ;; too late :-(
5446 (if org-enforce-todo-dependencies
5447 (add-hook 'org-blocker-hook
5448 'org-block-todo-from-children-or-siblings-or-parent)
5449 (remove-hook 'org-blocker-hook
5450 'org-block-todo-from-children-or-siblings-or-parent))
5451 (if org-enforce-todo-checkbox-dependencies
5452 (add-hook 'org-blocker-hook
5453 'org-block-todo-from-checkboxes)
5454 (remove-hook 'org-blocker-hook
5455 'org-block-todo-from-checkboxes))
5457 ;; Align options lines
5458 (org-set-local
5459 'align-mode-rules-list
5460 '((org-in-buffer-settings
5461 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5462 (modes . '(org-mode)))))
5464 ;; Imenu
5465 (org-set-local 'imenu-create-index-function
5466 'org-imenu-get-tree)
5468 ;; Make isearch reveal context
5469 (if (or (featurep 'xemacs)
5470 (not (boundp 'outline-isearch-open-invisible-function)))
5471 ;; Emacs 21 and XEmacs make use of the hook
5472 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5473 ;; Emacs 22 deals with this through a special variable
5474 (org-set-local 'outline-isearch-open-invisible-function
5475 (lambda (&rest ignore) (org-show-context 'isearch)))
5476 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5478 ;; Setup the pcomplete hooks
5479 (set (make-local-variable 'pcomplete-command-completion-function)
5480 'org-pcomplete-initial)
5481 (set (make-local-variable 'pcomplete-command-name-function)
5482 'org-command-at-point)
5483 (set (make-local-variable 'pcomplete-default-completion-function)
5484 'ignore)
5485 (set (make-local-variable 'pcomplete-parse-arguments-function)
5486 'org-parse-arguments)
5487 (set (make-local-variable 'pcomplete-termination-string) "")
5488 (when (>= emacs-major-version 23)
5489 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5491 ;; If empty file that did not turn on org-mode automatically, make it to.
5492 (if (and org-insert-mode-line-in-empty-file
5493 (org-called-interactively-p 'any)
5494 (= (point-min) (point-max)))
5495 (insert "# -*- mode: org -*-\n\n"))
5496 (unless org-inhibit-startup
5497 (org-unmodified
5498 (and org-startup-with-beamer-mode (org-beamer-mode))
5499 (when org-startup-align-all-tables
5500 (org-table-map-tables 'org-table-align 'quietly))
5501 (when org-startup-with-inline-images
5502 (org-display-inline-images))
5503 (when org-startup-with-latex-preview
5504 (org-preview-latex-fragment))
5505 (unless org-inhibit-startup-visibility-stuff
5506 (org-set-startup-visibility))))
5507 ;; Try to set org-hide correctly
5508 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5510 ;; Update `customize-package-emacs-version-alist'
5511 (add-to-list 'customize-package-emacs-version-alist
5512 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5513 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5514 ("8.2.6" . "24.4")))
5516 (defvar org-mode-transpose-word-syntax-table
5517 (let ((st (make-syntax-table)))
5518 (mapc (lambda(c) (modify-syntax-entry
5519 (string-to-char (car c)) "w p" st))
5520 org-emphasis-alist)
5521 st))
5523 (when (fboundp 'abbrev-table-put)
5524 (abbrev-table-put org-mode-abbrev-table
5525 :parents (list text-mode-abbrev-table)))
5527 (defsubst org-fix-ellipsis-at-bol ()
5528 (save-excursion (goto-char (window-start)) (recenter 0)))
5530 (defun org-find-invisible-foreground ()
5531 (let ((candidates (remove
5532 "unspecified-bg"
5533 (nconc
5534 (list (face-background 'default)
5535 (face-background 'org-default))
5536 (mapcar
5537 (lambda (alist)
5538 (when (boundp alist)
5539 (cdr (assoc 'background-color (symbol-value alist)))))
5540 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5541 (list (face-foreground 'org-hide))))))
5542 (car (remove nil candidates))))
5544 (defun org-current-time (&optional rounding-minutes past)
5545 "Current time, possibly rounded to ROUNDING-MINUTES.
5546 When ROUNDING-MINUTES is not an integer, fall back on the car of
5547 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5548 the rounding returns a past time."
5549 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5550 (car org-time-stamp-rounding-minutes)))
5551 (time (decode-time)) res)
5552 (if (< r 1)
5553 (current-time)
5554 (setq res
5555 (apply 'encode-time
5556 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5557 (nthcdr 2 time))))
5558 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5559 (seconds-to-time (- (org-float-time res) (* r 60)))
5560 res))))
5562 (defun org-today ()
5563 "Return today date, considering `org-extend-today-until'."
5564 (time-to-days
5565 (time-subtract (current-time)
5566 (list 0 (* 3600 org-extend-today-until) 0))))
5568 ;;;; Font-Lock stuff, including the activators
5570 (defvar org-mouse-map (make-sparse-keymap))
5571 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5572 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5573 (when org-mouse-1-follows-link
5574 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5575 (when org-tab-follows-link
5576 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5577 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5579 (require 'font-lock)
5581 (defconst org-non-link-chars "]\t\n\r<>")
5582 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5583 "shell" "elisp" "doi" "message"))
5584 (defvar org-link-types-re nil
5585 "Matches a link that has a url-like prefix like \"http:\"")
5586 (defvar org-link-re-with-space nil
5587 "Matches a link with spaces, optional angular brackets around it.")
5588 (defvar org-link-re-with-space2 nil
5589 "Matches a link with spaces, optional angular brackets around it.")
5590 (defvar org-link-re-with-space3 nil
5591 "Matches a link with spaces, only for internal part in bracket links.")
5592 (defvar org-angle-link-re nil
5593 "Matches link with angular brackets, spaces are allowed.")
5594 (defvar org-plain-link-re nil
5595 "Matches plain link, without spaces.")
5596 (defvar org-bracket-link-regexp nil
5597 "Matches a link in double brackets.")
5598 (defvar org-bracket-link-analytic-regexp nil
5599 "Regular expression used to analyze links.
5600 Here is what the match groups contain after a match:
5601 1: http:
5602 2: http
5603 3: path
5604 4: [desc]
5605 5: desc")
5606 (defvar org-bracket-link-analytic-regexp++ nil
5607 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5608 (defvar org-any-link-re nil
5609 "Regular expression matching any link.")
5611 (defconst org-match-sexp-depth 3
5612 "Number of stacked braces for sub/superscript matching.")
5614 (defun org-create-multibrace-regexp (left right n)
5615 "Create a regular expression which will match a balanced sexp.
5616 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5617 as single character strings.
5618 The regexp returned will match the entire expression including the
5619 delimiters. It will also define a single group which contains the
5620 match except for the outermost delimiters. The maximum depth of
5621 stacked delimiters is N. Escaping delimiters is not possible."
5622 (let* ((nothing (concat "[^" left right "]*?"))
5623 (or "\\|")
5624 (re nothing)
5625 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5626 (while (> n 1)
5627 (setq n (1- n)
5628 re (concat re or next)
5629 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5630 (concat left "\\(" re "\\)" right)))
5632 (defconst org-match-substring-regexp
5633 (concat
5634 "\\(\\S-\\)\\([_^]\\)\\("
5635 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5636 "\\|"
5637 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5638 "\\|"
5639 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5640 "The regular expression matching a sub- or superscript.")
5642 (defconst org-match-substring-with-braces-regexp
5643 (concat
5644 "\\(\\S-\\)\\([_^]\\)"
5645 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5646 "The regular expression matching a sub- or superscript, forcing braces.")
5648 (defun org-make-link-regexps ()
5649 "Update the link regular expressions.
5650 This should be called after the variable `org-link-types' has changed."
5651 (setq org-link-types-re
5652 (concat
5653 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5654 org-link-re-with-space
5655 (concat
5656 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5657 "\\([^" org-non-link-chars " ]"
5658 "[^" org-non-link-chars "]*"
5659 "[^" org-non-link-chars " ]\\)>?")
5660 org-link-re-with-space2
5661 (concat
5662 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5663 "\\([^" org-non-link-chars " ]"
5664 "[^\t\n\r]*"
5665 "[^" org-non-link-chars " ]\\)>?")
5666 org-link-re-with-space3
5667 (concat
5668 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5669 "\\([^" org-non-link-chars " ]"
5670 "[^\t\n\r]*\\)")
5671 org-angle-link-re
5672 (concat
5673 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5674 "\\([^" org-non-link-chars " ]"
5675 "[^" org-non-link-chars "]*"
5676 "\\)>")
5677 org-plain-link-re
5678 (concat
5679 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5680 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5681 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5682 org-bracket-link-regexp
5683 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5684 org-bracket-link-analytic-regexp
5685 (concat
5686 "\\[\\["
5687 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5688 "\\([^]]+\\)"
5689 "\\]"
5690 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5691 "\\]")
5692 org-bracket-link-analytic-regexp++
5693 (concat
5694 "\\[\\["
5695 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5696 "\\([^]]+\\)"
5697 "\\]"
5698 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5699 "\\]")
5700 org-any-link-re
5701 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5702 org-angle-link-re "\\)\\|\\("
5703 org-plain-link-re "\\)")))
5705 (org-make-link-regexps)
5707 (defvar org-emph-face nil)
5709 (defun org-do-emphasis-faces (limit)
5710 "Run through the buffer and add overlays to emphasized strings."
5711 (let (rtn a)
5712 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5713 (if (not (= (char-after (match-beginning 3))
5714 (char-after (match-beginning 4))))
5715 (progn
5716 (setq rtn t)
5717 (setq a (assoc (match-string 3) org-emphasis-alist))
5718 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5719 'face
5720 (nth 1 a))
5721 (and (nth 2 a)
5722 (org-remove-flyspell-overlays-in
5723 (match-beginning 0) (match-end 0)))
5724 (add-text-properties (match-beginning 2) (match-end 2)
5725 '(font-lock-multiline t org-emphasis t))
5726 (when org-hide-emphasis-markers
5727 (add-text-properties (match-end 4) (match-beginning 5)
5728 '(invisible org-link))
5729 (add-text-properties (match-beginning 3) (match-end 3)
5730 '(invisible org-link)))))
5731 (goto-char (1+ (match-beginning 0))))
5732 rtn))
5734 (defun org-emphasize (&optional char)
5735 "Insert or change an emphasis, i.e. a font like bold or italic.
5736 If there is an active region, change that region to a new emphasis.
5737 If there is no region, just insert the marker characters and position
5738 the cursor between them.
5739 CHAR should be the marker character. If it is a space, it means to
5740 remove the emphasis of the selected region.
5741 If CHAR is not given (for example in an interactive call) it will be
5742 prompted for."
5743 (interactive)
5744 (let ((erc org-emphasis-regexp-components)
5745 (prompt "")
5746 (string "") beg end move c s)
5747 (if (org-region-active-p)
5748 (setq beg (region-beginning) end (region-end)
5749 string (buffer-substring beg end))
5750 (setq move t))
5752 (unless char
5753 (message "Emphasis marker or tag: [%s]"
5754 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5755 (setq char (read-char-exclusive)))
5756 (if (equal char ?\ )
5757 (setq s "" move nil)
5758 (unless (assoc (char-to-string char) org-emphasis-alist)
5759 (user-error "No such emphasis marker: \"%c\"" char))
5760 (setq s (char-to-string char)))
5761 (while (and (> (length string) 1)
5762 (equal (substring string 0 1) (substring string -1))
5763 (assoc (substring string 0 1) org-emphasis-alist))
5764 (setq string (substring string 1 -1)))
5765 (setq string (concat s string s))
5766 (if beg (delete-region beg end))
5767 (unless (or (bolp)
5768 (string-match (concat "[" (nth 0 erc) "\n]")
5769 (char-to-string (char-before (point)))))
5770 (insert " "))
5771 (unless (or (eobp)
5772 (string-match (concat "[" (nth 1 erc) "\n]")
5773 (char-to-string (char-after (point)))))
5774 (insert " ") (backward-char 1))
5775 (insert string)
5776 (and move (backward-char 1))))
5778 (defconst org-nonsticky-props
5779 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5781 (defsubst org-rear-nonsticky-at (pos)
5782 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5784 (defun org-activate-plain-links (limit)
5785 "Run through the buffer and add overlays to links."
5786 (let (f hl)
5787 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5788 (not (org-in-src-block-p)))
5789 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5790 (setq f (get-text-property (match-beginning 0) 'face))
5791 (setq hl (org-match-string-no-properties 0))
5792 (if (or (eq f 'org-tag)
5793 (and (listp f) (memq 'org-tag f)))
5795 (add-text-properties (match-beginning 0) (match-end 0)
5796 (list 'mouse-face 'highlight
5797 'face 'org-link
5798 'htmlize-link `(:uri ,hl)
5799 'keymap org-mouse-map))
5800 (org-rear-nonsticky-at (match-end 0)))
5801 t)))
5803 (defun org-activate-code (limit)
5804 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5805 (progn
5806 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5807 (remove-text-properties (match-beginning 0) (match-end 0)
5808 '(display t invisible t intangible t))
5809 t)))
5811 (defcustom org-src-fontify-natively t
5812 "When non-nil, fontify code in code blocks."
5813 :type 'boolean
5814 :version "24.4"
5815 :package-version '(Org . "8.3")
5816 :group 'org-appearance
5817 :group 'org-babel)
5819 (defcustom org-allow-promoting-top-level-subtree nil
5820 "When non-nil, allow promoting a top level subtree.
5821 The leading star of the top level headline will be replaced
5822 by a #."
5823 :type 'boolean
5824 :version "24.1"
5825 :group 'org-appearance)
5827 (defun org-fontify-meta-lines-and-blocks (limit)
5828 (condition-case nil
5829 (org-fontify-meta-lines-and-blocks-1 limit)
5830 (error (message "org-mode fontification error"))))
5832 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5833 "Fontify #+ lines and blocks."
5834 (let ((case-fold-search t))
5835 (if (re-search-forward
5836 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5837 limit t)
5838 (let ((beg (match-beginning 0))
5839 (block-start (match-end 0))
5840 (block-end nil)
5841 (lang (match-string 7))
5842 (beg1 (line-beginning-position 2))
5843 (dc1 (downcase (match-string 2)))
5844 (dc3 (downcase (match-string 3)))
5845 end end1 quoting block-type ovl)
5846 (cond
5847 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5848 ;; a single line of backend-specific content
5849 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5850 (remove-text-properties (match-beginning 0) (match-end 0)
5851 '(display t invisible t intangible t))
5852 (add-text-properties (match-beginning 1) (match-end 3)
5853 '(font-lock-fontified t face org-meta-line))
5854 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5855 '(font-lock-fontified t face org-block))
5856 ; for backend-specific code
5858 ((and (match-end 4) (equal dc3 "+begin"))
5859 ;; Truly a block
5860 (setq block-type (downcase (match-string 5))
5861 quoting (member block-type org-protecting-blocks))
5862 (when (re-search-forward
5863 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5864 nil t) ;; on purpose, we look further than LIMIT
5865 (setq end (min (point-max) (match-end 0))
5866 end1 (min (point-max) (1- (match-beginning 0))))
5867 (setq block-end (match-beginning 0))
5868 (when quoting
5869 (org-remove-flyspell-overlays-in beg1 end1)
5870 (remove-text-properties beg end
5871 '(display t invisible t intangible t)))
5872 (add-text-properties
5873 beg end '(font-lock-fontified t font-lock-multiline t))
5874 (add-text-properties beg beg1 '(face org-meta-line))
5875 (org-remove-flyspell-overlays-in beg beg1)
5876 (add-text-properties ; For end_src
5877 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5878 (org-remove-flyspell-overlays-in end1 end)
5879 (cond
5880 ((and lang (not (string= lang "")) org-src-fontify-natively)
5881 (org-src-font-lock-fontify-block lang block-start block-end)
5882 ;; remove old background overlays
5883 (mapc (lambda (ov)
5884 (if (eq (overlay-get ov 'face) 'org-block-background)
5885 (delete-overlay ov)))
5886 (overlays-at (/ (+ beg1 block-end) 2)))
5887 ;; add a background overlay
5888 (setq ovl (make-overlay beg1 block-end))
5889 (overlay-put ovl 'face 'org-block-background)
5890 (overlay-put ovl 'evaporate t)) ; make it go away when empty
5891 (quoting
5892 (add-text-properties beg1 (min (point-max) (1+ end1))
5893 '(face org-block))) ; end of source block
5894 ((not org-fontify-quote-and-verse-blocks))
5895 ((string= block-type "quote")
5896 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5897 ((string= block-type "verse")
5898 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5899 (add-text-properties beg beg1 '(face org-block-begin-line))
5900 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5901 '(face org-block-end-line))
5903 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5904 (org-remove-flyspell-overlays-in
5905 (match-beginning 0)
5906 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5907 (add-text-properties
5908 beg (match-end 3)
5909 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5910 '(font-lock-fontified t invisible t)
5911 '(font-lock-fontified t face org-document-info-keyword)))
5912 (add-text-properties
5913 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5914 (if (string-equal dc1 "+title:")
5915 '(font-lock-fontified t face org-document-title)
5916 '(font-lock-fontified t face org-document-info))))
5917 ((or (equal dc1 "+results")
5918 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5919 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5920 "+call:" "+header:" "+headers:" "+name:"))
5921 (and (match-end 4) (equal dc3 "+attr")))
5922 (org-remove-flyspell-overlays-in
5923 (match-beginning 0)
5924 (if (equal "+caption:" dc1) (match-end 2) (match-end 0)))
5925 (add-text-properties
5926 beg (match-end 0)
5927 '(font-lock-fontified t face org-meta-line))
5929 ((member dc3 '(" " ""))
5930 (org-remove-flyspell-overlays-in beg (match-end 0))
5931 (add-text-properties
5932 beg (match-end 0)
5933 '(font-lock-fontified t face font-lock-comment-face)))
5934 ((not (member (char-after beg) '(?\ ?\t)))
5935 ;; just any other in-buffer setting, but not indented
5936 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5937 (add-text-properties
5938 beg (match-end 0)
5939 '(font-lock-fontified t face org-meta-line))
5941 (t nil))))))
5943 (defun org-fontify-drawers (limit)
5944 "Fontify drawers."
5945 (when (re-search-forward org-drawer-regexp limit t)
5946 (add-text-properties
5947 (match-beginning 0) (match-end 0)
5948 '(font-lock-fontified t face org-special-keyword))
5949 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5952 (defun org-activate-angle-links (limit)
5953 "Run through the buffer and add overlays to links."
5954 (if (and (re-search-forward org-angle-link-re limit t)
5955 (not (org-in-src-block-p)))
5956 (progn
5957 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5958 (add-text-properties (match-beginning 0) (match-end 0)
5959 (list 'mouse-face 'highlight
5960 'keymap org-mouse-map))
5961 (org-rear-nonsticky-at (match-end 0))
5962 t)))
5964 (defun org-activate-footnote-links (limit)
5965 "Run through the buffer and add overlays to footnotes."
5966 (let ((fn (org-footnote-next-reference-or-definition limit)))
5967 (when fn
5968 (let* ((beg (nth 1 fn))
5969 (end (nth 2 fn))
5970 (label (car fn))
5971 (referencep (/= (line-beginning-position) beg)))
5972 (when (and referencep (nth 3 fn))
5973 (save-excursion
5974 (goto-char beg)
5975 (search-forward (or label "fn:"))
5976 (org-remove-flyspell-overlays-in beg (match-end 0))))
5977 (add-text-properties beg end
5978 (list 'mouse-face 'highlight
5979 'keymap org-mouse-map
5980 'help-echo
5981 (if referencep "Footnote reference"
5982 "Footnote definition")
5983 'font-lock-fontified t
5984 'font-lock-multiline t
5985 'face 'org-footnote))))))
5987 (defun org-activate-bracket-links (limit)
5988 "Run through the buffer and add overlays to bracketed links."
5989 (if (and (re-search-forward org-bracket-link-regexp limit t)
5990 (not (org-in-src-block-p)))
5991 (let* ((hl (org-match-string-no-properties 1))
5992 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5993 (ip (org-maybe-intangible
5994 (list 'invisible 'org-link
5995 'keymap org-mouse-map 'mouse-face 'highlight
5996 'font-lock-multiline t 'help-echo help
5997 'htmlize-link `(:uri ,hl))))
5998 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5999 'font-lock-multiline t 'help-echo help
6000 'htmlize-link `(:uri ,hl))))
6001 ;; We need to remove the invisible property here. Table narrowing
6002 ;; may have made some of this invisible.
6003 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6004 (remove-text-properties (match-beginning 0) (match-end 0)
6005 '(invisible nil))
6006 (if (match-end 3)
6007 (progn
6008 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6009 (org-rear-nonsticky-at (match-beginning 3))
6010 (add-text-properties (match-beginning 3) (match-end 3) vp)
6011 (org-rear-nonsticky-at (match-end 3))
6012 (add-text-properties (match-end 3) (match-end 0) ip)
6013 (org-rear-nonsticky-at (match-end 0)))
6014 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6015 (org-rear-nonsticky-at (match-beginning 1))
6016 (add-text-properties (match-beginning 1) (match-end 1) vp)
6017 (org-rear-nonsticky-at (match-end 1))
6018 (add-text-properties (match-end 1) (match-end 0) ip)
6019 (org-rear-nonsticky-at (match-end 0)))
6020 t)))
6022 (defun org-activate-dates (limit)
6023 "Run through the buffer and add overlays to dates."
6024 (if (and (re-search-forward org-tsr-regexp-both limit t)
6025 (not (equal (char-before (match-beginning 0)) 91)))
6026 (progn
6027 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6028 (add-text-properties (match-beginning 0) (match-end 0)
6029 (list 'mouse-face 'highlight
6030 'keymap org-mouse-map))
6031 (org-rear-nonsticky-at (match-end 0))
6032 (when org-display-custom-times
6033 (if (match-end 3)
6034 (org-display-custom-time (match-beginning 3) (match-end 3)))
6035 (org-display-custom-time (match-beginning 1) (match-end 1)))
6036 t)))
6038 (defvar org-target-link-regexp nil
6039 "Regular expression matching radio targets in plain text.")
6040 (make-variable-buffer-local 'org-target-link-regexp)
6041 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
6042 "Regular expression matching a link target.")
6043 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
6044 "Regular expression matching a radio target.")
6045 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
6046 "Regular expression matching any target.")
6048 (defun org-activate-target-links (limit)
6049 "Run through the buffer and add overlays to target matches."
6050 (when org-target-link-regexp
6051 (let ((case-fold-search t))
6052 (if (re-search-forward org-target-link-regexp limit t)
6053 (progn
6054 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6055 (add-text-properties (match-beginning 0) (match-end 0)
6056 (list 'mouse-face 'highlight
6057 'keymap org-mouse-map
6058 'help-echo "Radio target link"
6059 'org-linked-text t))
6060 (org-rear-nonsticky-at (match-end 0))
6061 t)))))
6063 (defun org-update-radio-target-regexp ()
6064 "Find all radio targets in this file and update the regular expression."
6065 (interactive)
6066 (when (memq 'radio org-activate-links)
6067 (setq org-target-link-regexp
6068 (org-make-target-link-regexp (org-all-targets 'radio)))
6069 (org-restart-font-lock)))
6071 (defun org-hide-wide-columns (limit)
6072 (let (s e)
6073 (setq s (text-property-any (point) (or limit (point-max))
6074 'org-cwidth t))
6075 (when s
6076 (setq e (next-single-property-change s 'org-cwidth))
6077 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6078 (goto-char e)
6079 t)))
6081 (defvar org-latex-and-related-regexp nil
6082 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6084 (defun org-compute-latex-and-related-regexp ()
6085 "Compute regular expression for LaTeX, entities and sub/superscript.
6086 Result depends on variable `org-highlight-latex-and-related'."
6087 (org-set-local
6088 'org-latex-and-related-regexp
6089 (let* ((re-sub
6090 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6091 ((eq org-use-sub-superscripts '{})
6092 (list org-match-substring-with-braces-regexp))
6093 (org-use-sub-superscripts (list org-match-substring-regexp))))
6094 (re-latex
6095 (when (memq 'latex org-highlight-latex-and-related)
6096 (let ((matchers (plist-get org-format-latex-options :matchers)))
6097 (delq nil
6098 (mapcar (lambda (x)
6099 (and (member (car x) matchers) (nth 1 x)))
6100 org-latex-regexps)))))
6101 (re-entities
6102 (when (memq 'entities org-highlight-latex-and-related)
6103 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6104 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6106 (defun org-do-latex-and-related (limit)
6107 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6108 LIMIT bounds the search for syntax to highlight. Stop at first
6109 highlighted object, if any. Return t if some highlighting was
6110 done, nil otherwise."
6111 (when (org-string-nw-p org-latex-and-related-regexp)
6112 (catch 'found
6113 (while (re-search-forward org-latex-and-related-regexp limit t)
6114 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6115 'face))
6116 '(org-code org-verbatim underline))
6117 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6118 '(?_ ?^))
6120 0)))
6121 (font-lock-prepend-text-property
6122 (+ offset (match-beginning 0)) (match-end 0)
6123 'face 'org-latex-and-related)
6124 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6125 '(font-lock-multiline t)))
6126 (throw 'found t)))
6127 nil)))
6129 (defun org-restart-font-lock ()
6130 "Restart `font-lock-mode', to force refontification."
6131 (when (and (boundp 'font-lock-mode) font-lock-mode)
6132 (font-lock-mode -1)
6133 (font-lock-mode 1)))
6135 (defun org-all-targets (&optional radio)
6136 "Return a list of all targets in this file.
6137 When optional argument RADIO is non-nil, only find radio
6138 targets."
6139 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6140 (save-excursion
6141 (goto-char (point-min))
6142 (while (re-search-forward re nil t)
6143 ;; Make sure point is really within the object.
6144 (backward-char)
6145 (let ((obj (org-element-context)))
6146 (when (memq (org-element-type obj) '(radio-target target))
6147 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6148 rtn)))
6150 (defun org-make-target-link-regexp (targets)
6151 "Make regular expression matching all strings in TARGETS.
6152 The regular expression finds the targets also if there is a line break
6153 between words."
6154 (and targets
6155 (concat
6156 "\\<\\("
6157 (mapconcat
6158 (lambda (x)
6159 (setq x (regexp-quote x))
6160 (while (string-match " +" x)
6161 (setq x (replace-match "\\s-+" t t x)))
6163 targets
6164 "\\|")
6165 "\\)\\>")))
6167 (defun org-activate-tags (limit)
6168 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6169 (progn
6170 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6171 (add-text-properties (match-beginning 1) (match-end 1)
6172 (list 'mouse-face 'highlight
6173 'keymap org-mouse-map))
6174 (org-rear-nonsticky-at (match-end 1))
6175 t)))
6177 (defun org-outline-level ()
6178 "Compute the outline level of the heading at point.
6179 If this is called at a normal headline, the level is the number of stars.
6180 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6181 (save-excursion
6182 (if (not (condition-case nil
6183 (org-back-to-heading t)
6184 (error nil)))
6186 (looking-at org-outline-regexp)
6187 (1- (- (match-end 0) (match-beginning 0))))))
6189 (defvar org-font-lock-keywords nil)
6191 (defsubst org-re-property (property &optional literal)
6192 "Return a regexp matching a PROPERTY line.
6193 Match group 3 will be set to the value if it exists."
6194 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6195 (if literal property (regexp-quote property))
6196 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6198 (defconst org-property-re
6199 (org-re-property ".*?" 'literal)
6200 "Regular expression matching a property line.
6201 There are four matching groups:
6202 1: :PROPKEY: including the leading and trailing colon,
6203 2: PROPKEY without the leading and trailing colon,
6204 3: PROPVAL without leading or trailing spaces,
6205 4: the indentation of the current line,
6206 5: trailing whitespace.")
6208 (defvar org-font-lock-hook nil
6209 "Functions to be called for special font lock stuff.")
6211 (defvar org-font-lock-set-keywords-hook nil
6212 "Functions that can manipulate `org-font-lock-extra-keywords'.
6213 This is called after `org-font-lock-extra-keywords' is defined, but before
6214 it is installed to be used by font lock. This can be useful if something
6215 needs to be inserted at a specific position in the font-lock sequence.")
6217 (defun org-font-lock-hook (limit)
6218 "Run `org-font-lock-hook' within LIMIT."
6219 (run-hook-with-args 'org-font-lock-hook limit))
6221 (defun org-set-font-lock-defaults ()
6222 "Set font lock defaults for the current buffer."
6223 (let* ((em org-fontify-emphasized-text)
6224 (lk org-activate-links)
6225 (org-font-lock-extra-keywords
6226 (list
6227 ;; Call the hook
6228 '(org-font-lock-hook)
6229 ;; Headlines
6230 `(,(if org-fontify-whole-heading-line
6231 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6232 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6233 (1 (org-get-level-face 1))
6234 (2 (org-get-level-face 2))
6235 (3 (org-get-level-face 3)))
6236 ;; Table lines
6237 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6238 (1 'org-table t))
6239 ;; Table internals
6240 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6241 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6242 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6243 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6244 ;; Drawers
6245 '(org-fontify-drawers)
6246 ;; Properties
6247 (list org-property-re
6248 '(1 'org-special-keyword t)
6249 '(3 'org-property-value t))
6250 ;; Links
6251 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6252 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6253 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6254 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6255 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6256 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6257 (if (memq 'footnote lk) '(org-activate-footnote-links))
6258 ;; Targets.
6259 (list org-any-target-regexp '(0 'org-target t))
6260 ;; Diary sexps.
6261 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6262 ;; Macro
6263 '("{{{.+?}}}" (0 'org-macro t))
6264 '(org-hide-wide-columns (0 nil append))
6265 ;; TODO keyword
6266 (list (format org-heading-keyword-regexp-format
6267 org-todo-regexp)
6268 '(2 (org-get-todo-face 2) t))
6269 ;; DONE
6270 (if org-fontify-done-headline
6271 (list (format org-heading-keyword-regexp-format
6272 (concat
6273 "\\(?:"
6274 (mapconcat 'regexp-quote org-done-keywords "\\|")
6275 "\\)"))
6276 '(2 'org-headline-done t))
6277 nil)
6278 ;; Priorities
6279 '(org-font-lock-add-priority-faces)
6280 ;; Tags
6281 '(org-font-lock-add-tag-faces)
6282 ;; Tags groups
6283 (if (and org-group-tags org-tag-groups-alist)
6284 (list (concat org-outline-regexp-bol ".+\\(:"
6285 (regexp-opt (mapcar 'car org-tag-groups-alist))
6286 ":\\).*$")
6287 '(1 'org-tag-group prepend)))
6288 ;; Special keywords
6289 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6290 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6291 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6292 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6293 ;; Emphasis
6294 (if em
6295 (if (featurep 'xemacs)
6296 '(org-do-emphasis-faces (0 nil append))
6297 '(org-do-emphasis-faces)))
6298 ;; Checkboxes
6299 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6300 1 'org-checkbox prepend)
6301 (if (cdr (assq 'checkbox org-list-automatic-rules))
6302 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6303 (0 (org-get-checkbox-statistics-face) t)))
6304 ;; Description list items
6305 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6306 1 'org-list-dt prepend)
6307 ;; ARCHIVEd headings
6308 (list (concat
6309 org-outline-regexp-bol
6310 "\\(.*:" org-archive-tag ":.*\\)")
6311 '(1 'org-archived prepend))
6312 ;; Specials
6313 '(org-do-latex-and-related)
6314 '(org-fontify-entities)
6315 '(org-raise-scripts)
6316 ;; Code
6317 '(org-activate-code (1 'org-code t))
6318 ;; COMMENT
6319 (list (format org-heading-keyword-regexp-format
6320 (concat "\\(" org-comment-string "\\)"))
6321 '(2 'org-special-keyword t))
6322 ;; Blocks and meta lines
6323 '(org-fontify-meta-lines-and-blocks))))
6324 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6325 (run-hooks 'org-font-lock-set-keywords-hook)
6326 ;; Now set the full font-lock-keywords
6327 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6328 (org-set-local 'font-lock-defaults
6329 '(org-font-lock-keywords t nil nil backward-paragraph))
6330 (kill-local-variable 'font-lock-keywords) nil))
6332 (defun org-toggle-pretty-entities ()
6333 "Toggle the composition display of entities as UTF8 characters."
6334 (interactive)
6335 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6336 (org-restart-font-lock)
6337 (if org-pretty-entities
6338 (message "Entities are now displayed as UTF8 characters")
6339 (save-restriction
6340 (widen)
6341 (org-decompose-region (point-min) (point-max))
6342 (message "Entities are now displayed as plain text"))))
6344 (defvar org-custom-properties-overlays nil
6345 "List of overlays used for custom properties.")
6346 (make-variable-buffer-local 'org-custom-properties-overlays)
6348 (defun org-toggle-custom-properties-visibility ()
6349 "Display or hide properties in `org-custom-properties'."
6350 (interactive)
6351 (if org-custom-properties-overlays
6352 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6353 (setq org-custom-properties-overlays nil))
6354 (unless (not org-custom-properties)
6355 (save-excursion
6356 (save-restriction
6357 (widen)
6358 (goto-char (point-min))
6359 (while (re-search-forward org-property-re nil t)
6360 (mapc (lambda(p)
6361 (when (equal p (substring (match-string 1) 1 -1))
6362 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6363 (overlay-put o 'invisible t)
6364 (overlay-put o 'org-custom-property t)
6365 (push o org-custom-properties-overlays))))
6366 org-custom-properties)))))))
6368 (defun org-fontify-entities (limit)
6369 "Find an entity to fontify."
6370 (let (ee)
6371 (when org-pretty-entities
6372 (catch 'match
6373 (while (re-search-forward
6374 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6375 limit t)
6376 (if (and (not (org-in-indented-comment-line))
6377 (setq ee (org-entity-get (match-string 1)))
6378 (= (length (nth 6 ee)) 1))
6379 (let*
6380 ((end (if (equal (match-string 2) "{}")
6381 (match-end 2)
6382 (match-end 1))))
6383 (add-text-properties
6384 (match-beginning 0) end
6385 (list 'font-lock-fontified t))
6386 (compose-region (match-beginning 0) end
6387 (nth 6 ee) nil)
6388 (backward-char 1)
6389 (throw 'match t))))
6390 nil))))
6392 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6393 "Fontify string S like in Org-mode."
6394 (with-temp-buffer
6395 (insert s)
6396 (let ((org-odd-levels-only odd-levels))
6397 (org-mode)
6398 (font-lock-fontify-buffer)
6399 (buffer-string))))
6401 (defvar org-m nil)
6402 (defvar org-l nil)
6403 (defvar org-f nil)
6404 (defun org-get-level-face (n)
6405 "Get the right face for match N in font-lock matching of headlines."
6406 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6407 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6408 (if org-cycle-level-faces
6409 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6410 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6411 (cond
6412 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6413 ((eq n 2) org-f)
6414 (t (if org-level-color-stars-only nil org-f))))
6417 (defun org-get-todo-face (kwd)
6418 "Get the right face for a TODO keyword KWD.
6419 If KWD is a number, get the corresponding match group."
6420 (if (numberp kwd) (setq kwd (match-string kwd)))
6421 (or (org-face-from-face-or-color
6422 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6423 (and (member kwd org-done-keywords) 'org-done)
6424 'org-todo))
6426 (defun org-face-from-face-or-color (context inherit face-or-color)
6427 "Create a face list that inherits INHERIT, but sets the foreground color.
6428 When FACE-OR-COLOR is not a string, just return it."
6429 (if (stringp face-or-color)
6430 (list :inherit inherit
6431 (cdr (assoc context org-faces-easy-properties))
6432 face-or-color)
6433 face-or-color))
6435 (defun org-font-lock-add-tag-faces (limit)
6436 "Add the special tag faces."
6437 (when (and org-tag-faces org-tags-special-faces-re)
6438 (while (re-search-forward org-tags-special-faces-re limit t)
6439 (add-text-properties (match-beginning 1) (match-end 1)
6440 (list 'face (org-get-tag-face 1)
6441 'font-lock-fontified t))
6442 (backward-char 1))))
6444 (defun org-font-lock-add-priority-faces (limit)
6445 "Add the special priority faces."
6446 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6447 (when (save-match-data (org-at-heading-p))
6448 (add-text-properties
6449 (match-beginning 0) (match-end 0)
6450 (list 'face (or (org-face-from-face-or-color
6451 'priority 'org-priority
6452 (cdr (assoc (char-after (match-beginning 1))
6453 org-priority-faces)))
6454 'org-priority)
6455 'font-lock-fontified t)))))
6457 (defun org-get-tag-face (kwd)
6458 "Get the right face for a TODO keyword KWD.
6459 If KWD is a number, get the corresponding match group."
6460 (if (numberp kwd) (setq kwd (match-string kwd)))
6461 (or (org-face-from-face-or-color
6462 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6463 'org-tag))
6465 (defun org-unfontify-region (beg end &optional maybe_loudly)
6466 "Remove fontification and activation overlays from links."
6467 (font-lock-default-unfontify-region beg end)
6468 (let* ((buffer-undo-list t)
6469 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6470 (inhibit-modification-hooks t)
6471 deactivate-mark buffer-file-name buffer-file-truename)
6472 (org-decompose-region beg end)
6473 (remove-text-properties beg end
6474 '(mouse-face t keymap t org-linked-text t
6475 invisible t intangible t
6476 org-emphasis t))
6477 (org-remove-font-lock-display-properties beg end)))
6479 (defconst org-script-display '(((raise -0.3) (height 0.7))
6480 ((raise 0.3) (height 0.7))
6481 ((raise -0.5))
6482 ((raise 0.5)))
6483 "Display properties for showing superscripts and subscripts.")
6485 (defun org-remove-font-lock-display-properties (beg end)
6486 "Remove specific display properties that have been added by font lock.
6487 The will remove the raise properties that are used to show superscripts
6488 and subscripts."
6489 (let (next prop)
6490 (while (< beg end)
6491 (setq next (next-single-property-change beg 'display nil end)
6492 prop (get-text-property beg 'display))
6493 (if (member prop org-script-display)
6494 (put-text-property beg next 'display nil))
6495 (setq beg next))))
6497 (defun org-raise-scripts (limit)
6498 "Add raise properties to sub/superscripts."
6499 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6500 (if (re-search-forward
6501 (if (eq org-use-sub-superscripts t)
6502 org-match-substring-regexp
6503 org-match-substring-with-braces-regexp)
6504 limit t)
6505 (let* ((pos (point)) table-p comment-p
6506 (mpos (match-beginning 3))
6507 (emph-p (get-text-property mpos 'org-emphasis))
6508 (link-p (get-text-property mpos 'mouse-face))
6509 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6510 (goto-char (point-at-bol))
6511 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6512 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6513 (goto-char pos)
6514 ;; Handle a_b^c
6515 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6516 (if (or comment-p emph-p link-p keyw-p)
6518 (put-text-property (match-beginning 3) (match-end 0)
6519 'display
6520 (if (equal (char-after (match-beginning 2)) ?^)
6521 (nth (if table-p 3 1) org-script-display)
6522 (nth (if table-p 2 0) org-script-display)))
6523 (add-text-properties (match-beginning 2) (match-end 2)
6524 (list 'invisible t
6525 'org-dwidth t 'org-dwidth-n 1))
6526 (if (and (eq (char-after (match-beginning 3)) ?{)
6527 (eq (char-before (match-end 3)) ?}))
6528 (progn
6529 (add-text-properties
6530 (match-beginning 3) (1+ (match-beginning 3))
6531 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6532 (add-text-properties
6533 (1- (match-end 3)) (match-end 3)
6534 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6535 t)))))
6537 ;;;; Visibility cycling, including org-goto and indirect buffer
6539 ;;; Cycling
6541 (defvar org-cycle-global-status nil)
6542 (make-variable-buffer-local 'org-cycle-global-status)
6543 (put 'org-cycle-global-status 'org-state t)
6544 (defvar org-cycle-subtree-status nil)
6545 (make-variable-buffer-local 'org-cycle-subtree-status)
6546 (put 'org-cycle-subtree-status 'org-state t)
6548 (defvar org-inlinetask-min-level)
6550 (defun org-unlogged-message (&rest args)
6551 "Display a message, but avoid logging it in the *Messages* buffer."
6552 (let ((message-log-max nil))
6553 (apply 'message args)))
6555 ;;;###autoload
6556 (defun org-cycle (&optional arg)
6557 "TAB-action and visibility cycling for Org-mode.
6559 This is the command invoked in Org-mode by the TAB key. Its main purpose
6560 is outline visibility cycling, but it also invokes other actions
6561 in special contexts.
6563 - When this function is called with a prefix argument, rotate the entire
6564 buffer through 3 states (global cycling)
6565 1. OVERVIEW: Show only top-level headlines.
6566 2. CONTENTS: Show all headlines of all levels, but no body text.
6567 3. SHOW ALL: Show everything.
6568 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6569 determined by the variable `org-startup-folded', and by any VISIBILITY
6570 properties in the buffer.
6571 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6572 including any drawers.
6574 - When inside a table, re-align the table and move to the next field.
6576 - When point is at the beginning of a headline, rotate the subtree started
6577 by this line through 3 different states (local cycling)
6578 1. FOLDED: Only the main headline is shown.
6579 2. CHILDREN: The main headline and the direct children are shown.
6580 From this state, you can move to one of the children
6581 and zoom in further.
6582 3. SUBTREE: Show the entire subtree, including body text.
6583 If there is no subtree, switch directly from CHILDREN to FOLDED.
6585 - When point is at the beginning of an empty headline and the variable
6586 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6587 of the headline by demoting and promoting it to likely levels. This
6588 speeds up creation document structure by pressing TAB once or several
6589 times right after creating a new headline.
6591 - When there is a numeric prefix, go up to a heading with level ARG, do
6592 a `show-subtree' and return to the previous cursor position. If ARG
6593 is negative, go up that many levels.
6595 - When point is not at the beginning of a headline, execute the global
6596 binding for TAB, which is re-indenting the line. See the option
6597 `org-cycle-emulate-tab' for details.
6599 - Special case: if point is at the beginning of the buffer and there is
6600 no headline in line 1, this function will act as if called with prefix arg
6601 (C-u TAB, same as S-TAB) also when called without prefix arg.
6602 But only if also the variable `org-cycle-global-at-bob' is t."
6603 (interactive "P")
6604 (org-load-modules-maybe)
6605 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6606 (and org-cycle-level-after-item/entry-creation
6607 (or (org-cycle-level)
6608 (org-cycle-item-indentation))))
6609 (let* ((limit-level
6610 (or org-cycle-max-level
6611 (and (boundp 'org-inlinetask-min-level)
6612 org-inlinetask-min-level
6613 (1- org-inlinetask-min-level))))
6614 (nstars (and limit-level
6615 (if org-odd-levels-only
6616 (and limit-level (1- (* limit-level 2)))
6617 limit-level)))
6618 (org-outline-regexp
6619 (if (not (derived-mode-p 'org-mode))
6620 outline-regexp
6621 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6622 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6623 (not (looking-at org-outline-regexp))))
6624 (org-cycle-hook
6625 (if bob-special
6626 (delq 'org-optimize-window-after-visibility-change
6627 (copy-sequence org-cycle-hook))
6628 org-cycle-hook))
6629 (pos (point)))
6631 (if (or bob-special (equal arg '(4)))
6632 ;; special case: use global cycling
6633 (setq arg t))
6635 (cond
6637 ((equal arg '(16))
6638 (setq last-command 'dummy)
6639 (org-set-startup-visibility)
6640 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6642 ((equal arg '(64))
6643 (show-all)
6644 (org-unlogged-message "Entire buffer visible, including drawers"))
6646 ;; Table: enter it or move to the next field.
6647 ((org-at-table-p 'any)
6648 (if (org-at-table.el-p)
6649 (message "Use C-c ' to edit table.el tables")
6650 (if arg (org-table-edit-field t)
6651 (org-table-justify-field-maybe)
6652 (call-interactively 'org-table-next-field))))
6654 ((run-hook-with-args-until-success
6655 'org-tab-after-check-for-table-hook))
6657 ;; Global cycling: delegate to `org-cycle-internal-global'.
6658 ((eq arg t) (org-cycle-internal-global))
6660 ;; Drawers: delegate to `org-flag-drawer'.
6661 ((save-excursion
6662 (beginning-of-line 1)
6663 (looking-at org-drawer-regexp))
6664 (org-flag-drawer ; toggle block visibility
6665 (not (get-char-property (match-end 0) 'invisible))))
6667 ;; Show-subtree, ARG levels up from here.
6668 ((integerp arg)
6669 (save-excursion
6670 (org-back-to-heading)
6671 (outline-up-heading (if (< arg 0) (- arg)
6672 (- (funcall outline-level) arg)))
6673 (org-show-subtree)))
6675 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6676 ((and (featurep 'org-inlinetask)
6677 (org-inlinetask-at-task-p)
6678 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6679 (org-inlinetask-toggle-visibility))
6681 ((org-try-cdlatex-tab))
6683 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6684 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6685 (save-excursion (beginning-of-line 1)
6686 (looking-at org-outline-regexp)))
6687 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6688 (org-cycle-internal-local))
6690 ;; From there: TAB emulation and template completion.
6691 (buffer-read-only (org-back-to-heading))
6693 ((run-hook-with-args-until-success
6694 'org-tab-after-check-for-cycling-hook))
6696 ((org-try-structure-completion))
6698 ((run-hook-with-args-until-success
6699 'org-tab-before-tab-emulation-hook))
6701 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6702 (or (not (bolp))
6703 (not (looking-at org-outline-regexp))))
6704 (call-interactively (global-key-binding "\t")))
6706 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6707 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6708 (or (and (eq org-cycle-emulate-tab 'white)
6709 (= (match-end 0) (point-at-eol)))
6710 (and (eq org-cycle-emulate-tab 'whitestart)
6711 (>= (match-end 0) pos))))
6713 (eq org-cycle-emulate-tab t))
6714 (call-interactively (global-key-binding "\t")))
6716 (t (save-excursion
6717 (org-back-to-heading)
6718 (org-cycle)))))))
6720 (defun org-cycle-internal-global ()
6721 "Do the global cycling action."
6722 ;; Hack to avoid display of messages for .org attachments in Gnus
6723 (let ((ga (string-match "\\*fontification" (buffer-name))))
6724 (cond
6725 ((and (eq last-command this-command)
6726 (eq org-cycle-global-status 'overview))
6727 ;; We just created the overview - now do table of contents
6728 ;; This can be slow in very large buffers, so indicate action
6729 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6730 (unless ga (org-unlogged-message "CONTENTS..."))
6731 (org-content)
6732 (unless ga (org-unlogged-message "CONTENTS...done"))
6733 (setq org-cycle-global-status 'contents)
6734 (run-hook-with-args 'org-cycle-hook 'contents))
6736 ((and (eq last-command this-command)
6737 (eq org-cycle-global-status 'contents))
6738 ;; We just showed the table of contents - now show everything
6739 (run-hook-with-args 'org-pre-cycle-hook 'all)
6740 (show-all)
6741 (unless ga (org-unlogged-message "SHOW ALL"))
6742 (setq org-cycle-global-status 'all)
6743 (run-hook-with-args 'org-cycle-hook 'all))
6746 ;; Default action: go to overview
6747 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6748 (org-overview)
6749 (unless ga (org-unlogged-message "OVERVIEW"))
6750 (setq org-cycle-global-status 'overview)
6751 (run-hook-with-args 'org-cycle-hook 'overview)))))
6753 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6755 (defun org-cycle-internal-local ()
6756 "Do the local cycling action."
6757 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6758 ;; First, determine end of headline (EOH), end of subtree or item
6759 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6760 (save-excursion
6761 (if (org-at-item-p)
6762 (progn
6763 (beginning-of-line)
6764 (setq struct (org-list-struct))
6765 (setq eoh (point-at-eol))
6766 (setq eos (org-list-get-item-end-before-blank (point) struct))
6767 (setq has-children (org-list-has-child-p (point) struct)))
6768 (org-back-to-heading)
6769 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6770 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6771 (setq has-children
6772 (or (save-excursion
6773 (let ((level (funcall outline-level)))
6774 (outline-next-heading)
6775 (and (org-at-heading-p t)
6776 (> (funcall outline-level) level))))
6777 (save-excursion
6778 (org-list-search-forward (org-item-beginning-re) eos t)))))
6779 ;; Determine end invisible part of buffer (EOL)
6780 (beginning-of-line 2)
6781 ;; XEmacs doesn't have `next-single-char-property-change'
6782 (if (featurep 'xemacs)
6783 (while (and (not (eobp)) ;; this is like `next-line'
6784 (get-char-property (1- (point)) 'invisible))
6785 (beginning-of-line 2))
6786 (while (and (not (eobp)) ;; this is like `next-line'
6787 (get-char-property (1- (point)) 'invisible))
6788 (goto-char (next-single-char-property-change (point) 'invisible))
6789 (and (eolp) (beginning-of-line 2))))
6790 (setq eol (point)))
6791 ;; Find out what to do next and set `this-command'
6792 (cond
6793 ((= eos eoh)
6794 ;; Nothing is hidden behind this heading
6795 (unless (org-before-first-heading-p)
6796 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6797 (org-unlogged-message "EMPTY ENTRY")
6798 (setq org-cycle-subtree-status nil)
6799 (save-excursion
6800 (goto-char eos)
6801 (outline-next-heading)
6802 (if (outline-invisible-p) (org-flag-heading nil))))
6803 ((and (or (>= eol eos)
6804 (not (string-match "\\S-" (buffer-substring eol eos))))
6805 (or has-children
6806 (not (setq children-skipped
6807 org-cycle-skip-children-state-if-no-children))))
6808 ;; Entire subtree is hidden in one line: children view
6809 (unless (org-before-first-heading-p)
6810 (run-hook-with-args 'org-pre-cycle-hook 'children))
6811 (if (org-at-item-p)
6812 (org-list-set-item-visibility (point-at-bol) struct 'children)
6813 (org-show-entry)
6814 (org-with-limited-levels (show-children))
6815 ;; FIXME: This slows down the func way too much.
6816 ;; How keep drawers hidden in subtree anyway?
6817 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6818 ;; (org-cycle-hide-drawers 'subtree))
6820 ;; Fold every list in subtree to top-level items.
6821 (when (eq org-cycle-include-plain-lists 'integrate)
6822 (save-excursion
6823 (org-back-to-heading)
6824 (while (org-list-search-forward (org-item-beginning-re) eos t)
6825 (beginning-of-line 1)
6826 (let* ((struct (org-list-struct))
6827 (prevs (org-list-prevs-alist struct))
6828 (end (org-list-get-bottom-point struct)))
6829 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6830 (org-list-get-all-items (point) struct prevs))
6831 (goto-char (if (< end eos) end eos)))))))
6832 (org-unlogged-message "CHILDREN")
6833 (save-excursion
6834 (goto-char eos)
6835 (outline-next-heading)
6836 (if (outline-invisible-p) (org-flag-heading nil)))
6837 (setq org-cycle-subtree-status 'children)
6838 (unless (org-before-first-heading-p)
6839 (run-hook-with-args 'org-cycle-hook 'children)))
6840 ((or children-skipped
6841 (and (eq last-command this-command)
6842 (eq org-cycle-subtree-status 'children)))
6843 ;; We just showed the children, or no children are there,
6844 ;; now show everything.
6845 (unless (org-before-first-heading-p)
6846 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6847 (outline-flag-region eoh eos nil)
6848 (org-unlogged-message
6849 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6850 (setq org-cycle-subtree-status 'subtree)
6851 (unless (org-before-first-heading-p)
6852 (run-hook-with-args 'org-cycle-hook 'subtree)))
6854 ;; Default action: hide the subtree.
6855 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6856 (outline-flag-region eoh eos t)
6857 (org-unlogged-message "FOLDED")
6858 (setq org-cycle-subtree-status 'folded)
6859 (unless (org-before-first-heading-p)
6860 (run-hook-with-args 'org-cycle-hook 'folded))))))
6862 ;;;###autoload
6863 (defun org-global-cycle (&optional arg)
6864 "Cycle the global visibility. For details see `org-cycle'.
6865 With \\[universal-argument] prefix arg, switch to startup visibility.
6866 With a numeric prefix, show all headlines up to that level."
6867 (interactive "P")
6868 (let ((org-cycle-include-plain-lists
6869 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6870 (cond
6871 ((integerp arg)
6872 (show-all)
6873 (hide-sublevels arg)
6874 (setq org-cycle-global-status 'contents))
6875 ((equal arg '(4))
6876 (org-set-startup-visibility)
6877 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6879 (org-cycle '(4))))))
6881 (defun org-set-startup-visibility ()
6882 "Set the visibility required by startup options and properties."
6883 (cond
6884 ((eq org-startup-folded t)
6885 (org-overview))
6886 ((eq org-startup-folded 'content)
6887 (org-content))
6888 ((or (eq org-startup-folded 'showeverything)
6889 (eq org-startup-folded nil))
6890 (show-all)))
6891 (unless (eq org-startup-folded 'showeverything)
6892 (if org-hide-block-startup (org-hide-block-all))
6893 (org-set-visibility-according-to-property 'no-cleanup)
6894 (org-cycle-hide-archived-subtrees 'all)
6895 (org-cycle-hide-drawers 'all)
6896 (org-cycle-show-empty-lines t)))
6898 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6899 "Switch subtree visibilities according to :VISIBILITY: property."
6900 (interactive)
6901 (let (org-show-entry-below state)
6902 (save-excursion
6903 (goto-char (point-min))
6904 (while (re-search-forward
6905 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6906 nil t)
6907 (setq state (match-string 1))
6908 (save-excursion
6909 (org-back-to-heading t)
6910 (hide-subtree)
6911 (org-reveal)
6912 (cond
6913 ((equal state '("fold" "folded"))
6914 (hide-subtree))
6915 ((equal state "children")
6916 (org-show-hidden-entry)
6917 (show-children))
6918 ((equal state "content")
6919 (save-excursion
6920 (save-restriction
6921 (org-narrow-to-subtree)
6922 (org-content))))
6923 ((member state '("all" "showall"))
6924 (show-subtree)))))
6925 (unless no-cleanup
6926 (org-cycle-hide-archived-subtrees 'all)
6927 (org-cycle-hide-drawers 'all)
6928 (org-cycle-show-empty-lines 'all)))))
6930 ;; This function uses outline-regexp instead of the more fundamental
6931 ;; org-outline-regexp so that org-cycle-global works outside of Org
6932 ;; buffers, where outline-regexp is needed.
6933 (defun org-overview ()
6934 "Switch to overview mode, showing only top-level headlines.
6935 Really, this shows all headlines with level equal or greater than the level
6936 of the first headline in the buffer. This is important, because if the
6937 first headline is not level one, then (hide-sublevels 1) gives confusing
6938 results."
6939 (interactive)
6940 (let ((pos (point))
6941 (level (save-excursion
6942 (goto-char (point-min))
6943 (if (re-search-forward (concat "^" outline-regexp) nil t)
6944 (progn
6945 (goto-char (match-beginning 0))
6946 (funcall outline-level))))))
6947 (and level (hide-sublevels level))
6948 (recenter '(4))
6949 (goto-char pos)))
6951 (defun org-content (&optional arg)
6952 "Show all headlines in the buffer, like a table of contents.
6953 With numerical argument N, show content up to level N."
6954 (interactive "P")
6955 (save-excursion
6956 ;; Visit all headings and show their offspring
6957 (and (integerp arg) (org-overview))
6958 (goto-char (point-max))
6959 (catch 'exit
6960 (while (and (progn (condition-case nil
6961 (outline-previous-visible-heading 1)
6962 (error (goto-char (point-min))))
6964 (looking-at org-outline-regexp))
6965 (if (integerp arg)
6966 (show-children (1- arg))
6967 (show-branches))
6968 (if (bobp) (throw 'exit nil))))))
6970 (defun org-optimize-window-after-visibility-change (state)
6971 "Adjust the window after a change in outline visibility.
6972 This function is the default value of the hook `org-cycle-hook'."
6973 (when (get-buffer-window (current-buffer))
6974 (cond
6975 ((eq state 'content) nil)
6976 ((eq state 'all) nil)
6977 ((eq state 'folded) nil)
6978 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6979 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6981 (defun org-remove-empty-overlays-at (pos)
6982 "Remove outline overlays that do not contain non-white stuff."
6983 (mapc
6984 (lambda (o)
6985 (and (eq 'outline (overlay-get o 'invisible))
6986 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6987 (overlay-end o))))
6988 (delete-overlay o)))
6989 (overlays-at pos)))
6991 (defun org-clean-visibility-after-subtree-move ()
6992 "Fix visibility issues after moving a subtree."
6993 ;; First, find a reasonable region to look at:
6994 ;; Start two siblings above, end three below
6995 (let* ((beg (save-excursion
6996 (and (org-get-last-sibling)
6997 (org-get-last-sibling))
6998 (point)))
6999 (end (save-excursion
7000 (and (org-get-next-sibling)
7001 (org-get-next-sibling)
7002 (org-get-next-sibling))
7003 (if (org-at-heading-p)
7004 (point-at-eol)
7005 (point))))
7006 (level (looking-at "\\*+"))
7007 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7008 (save-excursion
7009 (save-restriction
7010 (narrow-to-region beg end)
7011 (when re
7012 ;; Properly fold already folded siblings
7013 (goto-char (point-min))
7014 (while (re-search-forward re nil t)
7015 (if (and (not (outline-invisible-p))
7016 (save-excursion
7017 (goto-char (point-at-eol)) (outline-invisible-p)))
7018 (hide-entry))))
7019 (org-cycle-show-empty-lines 'overview)
7020 (org-cycle-hide-drawers 'overview)))))
7022 (defun org-cycle-show-empty-lines (state)
7023 "Show empty lines above all visible headlines.
7024 The region to be covered depends on STATE when called through
7025 `org-cycle-hook'. Lisp program can use t for STATE to get the
7026 entire buffer covered. Note that an empty line is only shown if there
7027 are at least `org-cycle-separator-lines' empty lines before the headline."
7028 (when (not (= org-cycle-separator-lines 0))
7029 (save-excursion
7030 (let* ((n (abs org-cycle-separator-lines))
7031 (re (cond
7032 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7033 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7034 (t (let ((ns (number-to-string (- n 2))))
7035 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7036 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7037 beg end b e)
7038 (cond
7039 ((memq state '(overview contents t))
7040 (setq beg (point-min) end (point-max)))
7041 ((memq state '(children folded))
7042 (setq beg (point) end (progn (org-end-of-subtree t t)
7043 (beginning-of-line 2)
7044 (point)))))
7045 (when beg
7046 (goto-char beg)
7047 (while (re-search-forward re end t)
7048 (unless (get-char-property (match-end 1) 'invisible)
7049 (setq e (match-end 1))
7050 (if (< org-cycle-separator-lines 0)
7051 (setq b (save-excursion
7052 (goto-char (match-beginning 0))
7053 (org-back-over-empty-lines)
7054 (if (save-excursion
7055 (goto-char (max (point-min) (1- (point))))
7056 (org-at-heading-p))
7057 (1- (point))
7058 (point))))
7059 (setq b (match-beginning 1)))
7060 (outline-flag-region b e nil)))))))
7061 ;; Never hide empty lines at the end of the file.
7062 (save-excursion
7063 (goto-char (point-max))
7064 (outline-previous-heading)
7065 (outline-end-of-heading)
7066 (if (and (looking-at "[ \t\n]+")
7067 (= (match-end 0) (point-max)))
7068 (outline-flag-region (point) (match-end 0) nil))))
7070 (defun org-show-empty-lines-in-parent ()
7071 "Move to the parent and re-show empty lines before visible headlines."
7072 (save-excursion
7073 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7074 (org-cycle-show-empty-lines context))))
7076 (defun org-files-list ()
7077 "Return `org-agenda-files' list, plus all open org-mode files.
7078 This is useful for operations that need to scan all of a user's
7079 open and agenda-wise Org files."
7080 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7081 (dolist (buf (buffer-list))
7082 (with-current-buffer buf
7083 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7084 (let ((file (expand-file-name (buffer-file-name))))
7085 (unless (member file files)
7086 (push file files))))))
7087 files))
7089 (defsubst org-entry-beginning-position ()
7090 "Return the beginning position of the current entry."
7091 (save-excursion (outline-back-to-heading t) (point)))
7093 (defsubst org-entry-end-position ()
7094 "Return the end position of the current entry."
7095 (save-excursion (outline-next-heading) (point)))
7097 (defun org-cycle-hide-drawers (state &optional exceptions)
7098 "Re-hide all drawers after a visibility state change.
7099 When non-nil, optional argument EXCEPTIONS is a list of strings
7100 specifying which drawers should not be hidden."
7101 (when (and (derived-mode-p 'org-mode)
7102 (not (memq state '(overview folded contents))))
7103 (save-excursion
7104 (let* ((globalp (memq state '(contents all)))
7105 (beg (if globalp (point-min) (point)))
7106 (end (if globalp (point-max)
7107 (if (eq state 'children)
7108 (save-excursion (outline-next-heading) (point))
7109 (org-end-of-subtree t)))))
7110 (goto-char beg)
7111 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7112 (unless (member-ignore-case (match-string 1) exceptions)
7113 (let ((drawer (org-element-at-point)))
7114 (when (memq (org-element-type drawer) '(drawer property-drawer))
7115 (org-flag-drawer t drawer)
7116 ;; Make sure to skip drawer entirely or we might flag
7117 ;; it another time when matching its ending line with
7118 ;; `org-drawer-regexp'.
7119 (goto-char (org-element-property :end drawer))))))))))
7121 (defun org-cycle-hide-inline-tasks (state)
7122 "Re-hide inline tasks when switching to 'contents or 'children
7123 visibility state."
7124 (case state
7125 (contents
7126 (when (org-bound-and-true-p org-inlinetask-min-level)
7127 (hide-sublevels (1- org-inlinetask-min-level))))
7128 (children
7129 (when (featurep 'org-inlinetask)
7130 (save-excursion
7131 (while (and (outline-next-heading)
7132 (org-inlinetask-at-task-p))
7133 (org-inlinetask-toggle-visibility)
7134 (org-inlinetask-goto-end)))))))
7136 (defun org-flag-drawer (flag &optional element)
7137 "When FLAG is non-nil, hide the drawer we are at.
7138 Otherwise make it visible. When optional argument ELEMENT is
7139 a parsed drawer, as returned by `org-element-at-point', hide or
7140 show that drawer instead."
7141 (let ((drawer (or element (org-element-at-point))))
7142 (when (memq (org-element-type drawer) '(drawer property-drawer))
7143 (save-excursion
7144 (goto-char (org-element-property :post-affiliated drawer))
7145 (outline-flag-region
7146 (line-end-position)
7147 (progn (goto-char (org-element-property :end drawer))
7148 (skip-chars-backward " \r\t\n")
7149 (line-end-position))
7150 flag)))))
7152 (defun org-subtree-end-visible-p ()
7153 "Is the end of the current subtree visible?"
7154 (pos-visible-in-window-p
7155 (save-excursion (org-end-of-subtree t) (point))))
7157 (defun org-first-headline-recenter (&optional N)
7158 "Move cursor to the first headline and recenter the headline.
7159 Optional argument N means put the headline into the Nth line of the window."
7160 (goto-char (point-min))
7161 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7162 (beginning-of-line)
7163 (recenter (prefix-numeric-value N))))
7165 ;;; Saving and restoring visibility
7167 (defun org-outline-overlay-data (&optional use-markers)
7168 "Return a list of the locations of all outline overlays.
7169 These are overlays with the `invisible' property value `outline'.
7170 The return value is a list of cons cells, with start and stop
7171 positions for each overlay.
7172 If USE-MARKERS is set, return the positions as markers."
7173 (let (beg end)
7174 (save-excursion
7175 (save-restriction
7176 (widen)
7177 (delq nil
7178 (mapcar (lambda (o)
7179 (when (eq (overlay-get o 'invisible) 'outline)
7180 (setq beg (overlay-start o)
7181 end (overlay-end o))
7182 (and beg end (> end beg)
7183 (if use-markers
7184 (cons (copy-marker beg)
7185 (copy-marker end t))
7186 (cons beg end)))))
7187 (overlays-in (point-min) (point-max))))))))
7189 (defun org-set-outline-overlay-data (data)
7190 "Create visibility overlays for all positions in DATA.
7191 DATA should have been made by `org-outline-overlay-data'."
7192 (let (o)
7193 (save-excursion
7194 (save-restriction
7195 (widen)
7196 (show-all)
7197 (mapc (lambda (c)
7198 (outline-flag-region (car c) (cdr c) t))
7199 data)))))
7201 ;;; Folding of blocks
7203 (defvar org-hide-block-overlays nil
7204 "Overlays hiding blocks.")
7205 (make-variable-buffer-local 'org-hide-block-overlays)
7207 (defun org-block-map (function &optional start end)
7208 "Call FUNCTION at the head of all source blocks in the current buffer.
7209 Optional arguments START and END can be used to limit the range."
7210 (let ((start (or start (point-min)))
7211 (end (or end (point-max))))
7212 (save-excursion
7213 (goto-char start)
7214 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7215 (save-excursion
7216 (save-match-data
7217 (goto-char (match-beginning 0))
7218 (funcall function)))))))
7220 (defun org-hide-block-toggle-all ()
7221 "Toggle the visibility of all blocks in the current buffer."
7222 (org-block-map #'org-hide-block-toggle))
7224 (defun org-hide-block-all ()
7225 "Fold all blocks in the current buffer."
7226 (interactive)
7227 (org-show-block-all)
7228 (org-block-map #'org-hide-block-toggle-maybe))
7230 (defun org-show-block-all ()
7231 "Unfold all blocks in the current buffer."
7232 (interactive)
7233 (mapc 'delete-overlay org-hide-block-overlays)
7234 (setq org-hide-block-overlays nil))
7236 (defun org-hide-block-toggle-maybe ()
7237 "Toggle visibility of block at point."
7238 (interactive)
7239 (let ((case-fold-search t))
7240 (if (save-excursion
7241 (beginning-of-line 1)
7242 (looking-at org-block-regexp))
7243 (progn (org-hide-block-toggle)
7244 t) ;; to signal that we took action
7245 nil))) ;; to signal that we did not
7247 (defun org-hide-block-toggle (&optional force)
7248 "Toggle the visibility of the current block."
7249 (interactive)
7250 (save-excursion
7251 (beginning-of-line)
7252 (if (re-search-forward org-block-regexp nil t)
7253 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7254 (end (match-end 0)) ;; end of entire body
7256 (if (memq t (mapcar (lambda (overlay)
7257 (eq (overlay-get overlay 'invisible)
7258 'org-hide-block))
7259 (overlays-at start)))
7260 (if (or (not force) (eq force 'off))
7261 (mapc (lambda (ov)
7262 (when (member ov org-hide-block-overlays)
7263 (setq org-hide-block-overlays
7264 (delq ov org-hide-block-overlays)))
7265 (when (eq (overlay-get ov 'invisible)
7266 'org-hide-block)
7267 (delete-overlay ov)))
7268 (overlays-at start)))
7269 (setq ov (make-overlay start end))
7270 (overlay-put ov 'invisible 'org-hide-block)
7271 ;; make the block accessible to isearch
7272 (overlay-put
7273 ov 'isearch-open-invisible
7274 (lambda (ov)
7275 (when (member ov org-hide-block-overlays)
7276 (setq org-hide-block-overlays
7277 (delq ov org-hide-block-overlays)))
7278 (when (eq (overlay-get ov 'invisible)
7279 'org-hide-block)
7280 (delete-overlay ov))))
7281 (push ov org-hide-block-overlays)))
7282 (user-error "Not looking at a source block"))))
7284 ;; org-tab-after-check-for-cycling-hook
7285 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7286 ;; Remove overlays when changing major mode
7287 (add-hook 'org-mode-hook
7288 (lambda () (org-add-hook 'change-major-mode-hook
7289 'org-show-block-all 'append 'local)))
7291 ;;; Org-goto
7293 (defvar org-goto-window-configuration nil)
7294 (defvar org-goto-marker nil)
7295 (defvar org-goto-map)
7296 (defun org-goto-map ()
7297 "Set the keymap `org-goto'."
7298 (setq org-goto-map
7299 (let ((map (make-sparse-keymap)))
7300 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7301 mouse-drag-region universal-argument org-occur))
7302 cmd)
7303 (while (setq cmd (pop cmds))
7304 (substitute-key-definition cmd cmd map global-map)))
7305 (suppress-keymap map)
7306 (org-defkey map "\C-m" 'org-goto-ret)
7307 (org-defkey map [(return)] 'org-goto-ret)
7308 (org-defkey map [(left)] 'org-goto-left)
7309 (org-defkey map [(right)] 'org-goto-right)
7310 (org-defkey map [(control ?g)] 'org-goto-quit)
7311 (org-defkey map "\C-i" 'org-cycle)
7312 (org-defkey map [(tab)] 'org-cycle)
7313 (org-defkey map [(down)] 'outline-next-visible-heading)
7314 (org-defkey map [(up)] 'outline-previous-visible-heading)
7315 (if org-goto-auto-isearch
7316 (if (fboundp 'define-key-after)
7317 (define-key-after map [t] 'org-goto-local-auto-isearch)
7318 nil)
7319 (org-defkey map "q" 'org-goto-quit)
7320 (org-defkey map "n" 'outline-next-visible-heading)
7321 (org-defkey map "p" 'outline-previous-visible-heading)
7322 (org-defkey map "f" 'outline-forward-same-level)
7323 (org-defkey map "b" 'outline-backward-same-level)
7324 (org-defkey map "u" 'outline-up-heading))
7325 (org-defkey map "/" 'org-occur)
7326 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7327 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7328 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7329 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7330 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7331 map)))
7333 (defconst org-goto-help
7334 "Browse buffer copy, to find location or copy text.%s
7335 RET=jump to location C-g=quit and return to previous location
7336 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7338 (defvar org-goto-start-pos) ; dynamically scoped parameter
7340 (defun org-goto (&optional alternative-interface)
7341 "Look up a different location in the current file, keeping current visibility.
7343 When you want look-up or go to a different location in a
7344 document, the fastest way is often to fold the entire buffer and
7345 then dive into the tree. This method has the disadvantage, that
7346 the previous location will be folded, which may not be what you
7347 want.
7349 This command works around this by showing a copy of the current
7350 buffer in an indirect buffer, in overview mode. You can dive
7351 into the tree in that copy, use org-occur and incremental search
7352 to find a location. When pressing RET or `Q', the command
7353 returns to the original buffer in which the visibility is still
7354 unchanged. After RET it will also jump to the location selected
7355 in the indirect buffer and expose the headline hierarchy above.
7357 With a prefix argument, use the alternative interface: e.g. if
7358 `org-goto-interface' is 'outline use 'outline-path-completion."
7359 (interactive "P")
7360 (org-goto-map)
7361 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7362 (org-refile-use-outline-path t)
7363 (org-refile-target-verify-function nil)
7364 (interface
7365 (if (not alternative-interface)
7366 org-goto-interface
7367 (if (eq org-goto-interface 'outline)
7368 'outline-path-completion
7369 'outline)))
7370 (org-goto-start-pos (point))
7371 (selected-point
7372 (if (eq interface 'outline)
7373 (car (org-get-location (current-buffer) org-goto-help))
7374 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7375 (org-refile-check-position pa)
7376 (nth 3 pa)))))
7377 (if selected-point
7378 (progn
7379 (org-mark-ring-push org-goto-start-pos)
7380 (goto-char selected-point)
7381 (if (or (outline-invisible-p) (org-invisible-p2))
7382 (org-show-context 'org-goto)))
7383 (message "Quit"))))
7385 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7386 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7387 (defvar org-goto-local-auto-isearch-map) ; defined below
7389 (defun org-get-location (buf help)
7390 "Let the user select a location in the Org-mode buffer BUF.
7391 This function uses a recursive edit. It returns the selected position
7392 or nil."
7393 (org-no-popups
7394 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7395 (isearch-hide-immediately nil)
7396 (isearch-search-fun-function
7397 (lambda () 'org-goto-local-search-headings))
7398 (org-goto-selected-point org-goto-exit-command))
7399 (save-excursion
7400 (save-window-excursion
7401 (delete-other-windows)
7402 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7403 (org-pop-to-buffer-same-window
7404 (condition-case nil
7405 (make-indirect-buffer (current-buffer) "*org-goto*")
7406 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7407 (with-output-to-temp-buffer "*Org Help*"
7408 (princ (format help (if org-goto-auto-isearch
7409 " Just type for auto-isearch."
7410 " n/p/f/b/u to navigate, q to quit."))))
7411 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7412 (setq buffer-read-only nil)
7413 (let ((org-startup-truncated t)
7414 (org-startup-folded nil)
7415 (org-startup-align-all-tables nil))
7416 (org-mode)
7417 (org-overview))
7418 (setq buffer-read-only t)
7419 (if (and (boundp 'org-goto-start-pos)
7420 (integer-or-marker-p org-goto-start-pos))
7421 (let ((org-show-hierarchy-above t)
7422 (org-show-siblings t)
7423 (org-show-following-heading t))
7424 (goto-char org-goto-start-pos)
7425 (and (outline-invisible-p) (org-show-context)))
7426 (goto-char (point-min)))
7427 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7428 (message "Select location and press RET")
7429 (use-local-map org-goto-map)
7430 (recursive-edit)))
7431 (kill-buffer "*org-goto*")
7432 (cons org-goto-selected-point org-goto-exit-command))))
7434 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7435 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7436 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7437 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7439 (defun org-goto-local-search-headings (string bound noerror)
7440 "Search and make sure that any matches are in headlines."
7441 (catch 'return
7442 (while (if isearch-forward
7443 (search-forward string bound noerror)
7444 (search-backward string bound noerror))
7445 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7446 (and (member :headline context)
7447 (not (member :tags context))))
7448 (throw 'return (point))))))
7450 (defun org-goto-local-auto-isearch ()
7451 "Start isearch."
7452 (interactive)
7453 (goto-char (point-min))
7454 (let ((keys (this-command-keys)))
7455 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7456 (isearch-mode t)
7457 (isearch-process-search-char (string-to-char keys)))))
7459 (defun org-goto-ret (&optional arg)
7460 "Finish `org-goto' by going to the new location."
7461 (interactive "P")
7462 (setq org-goto-selected-point (point)
7463 org-goto-exit-command 'return)
7464 (throw 'exit nil))
7466 (defun org-goto-left ()
7467 "Finish `org-goto' by going to the new location."
7468 (interactive)
7469 (if (org-at-heading-p)
7470 (progn
7471 (beginning-of-line 1)
7472 (setq org-goto-selected-point (point)
7473 org-goto-exit-command 'left)
7474 (throw 'exit nil))
7475 (user-error "Not on a heading")))
7477 (defun org-goto-right ()
7478 "Finish `org-goto' by going to the new location."
7479 (interactive)
7480 (if (org-at-heading-p)
7481 (progn
7482 (setq org-goto-selected-point (point)
7483 org-goto-exit-command 'right)
7484 (throw 'exit nil))
7485 (user-error "Not on a heading")))
7487 (defun org-goto-quit ()
7488 "Finish `org-goto' without cursor motion."
7489 (interactive)
7490 (setq org-goto-selected-point nil)
7491 (setq org-goto-exit-command 'quit)
7492 (throw 'exit nil))
7494 ;;; Indirect buffer display of subtrees
7496 (defvar org-indirect-dedicated-frame nil
7497 "This is the frame being used for indirect tree display.")
7498 (defvar org-last-indirect-buffer nil)
7500 (defun org-tree-to-indirect-buffer (&optional arg)
7501 "Create indirect buffer and narrow it to current subtree.
7502 With a numerical prefix ARG, go up to this level and then take that tree.
7503 If ARG is negative, go up that many levels.
7505 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7506 indirect buffer previously made with this command, to avoid proliferation of
7507 indirect buffers. However, when you call the command with a \
7508 \\[universal-argument] prefix, or
7509 when `org-indirect-buffer-display' is `new-frame', the last buffer
7510 is kept so that you can work with several indirect buffers at the same time.
7511 If `org-indirect-buffer-display' is `dedicated-frame', the \
7512 \\[universal-argument] prefix also
7513 requests that a new frame be made for the new buffer, so that the dedicated
7514 frame is not changed."
7515 (interactive "P")
7516 (let ((cbuf (current-buffer))
7517 (cwin (selected-window))
7518 (pos (point))
7519 beg end level heading ibuf)
7520 (save-excursion
7521 (org-back-to-heading t)
7522 (when (numberp arg)
7523 (setq level (org-outline-level))
7524 (if (< arg 0) (setq arg (+ level arg)))
7525 (while (> (setq level (org-outline-level)) arg)
7526 (org-up-heading-safe)))
7527 (setq beg (point)
7528 heading (org-get-heading))
7529 (org-end-of-subtree t t)
7530 (if (org-at-heading-p) (backward-char 1))
7531 (setq end (point)))
7532 (if (and (buffer-live-p org-last-indirect-buffer)
7533 (not (eq org-indirect-buffer-display 'new-frame))
7534 (not arg))
7535 (kill-buffer org-last-indirect-buffer))
7536 (setq ibuf (org-get-indirect-buffer cbuf heading)
7537 org-last-indirect-buffer ibuf)
7538 (cond
7539 ((or (eq org-indirect-buffer-display 'new-frame)
7540 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7541 (select-frame (make-frame))
7542 (delete-other-windows)
7543 (org-pop-to-buffer-same-window ibuf)
7544 (org-set-frame-title heading))
7545 ((eq org-indirect-buffer-display 'dedicated-frame)
7546 (raise-frame
7547 (select-frame (or (and org-indirect-dedicated-frame
7548 (frame-live-p org-indirect-dedicated-frame)
7549 org-indirect-dedicated-frame)
7550 (setq org-indirect-dedicated-frame (make-frame)))))
7551 (delete-other-windows)
7552 (org-pop-to-buffer-same-window ibuf)
7553 (org-set-frame-title (concat "Indirect: " heading)))
7554 ((eq org-indirect-buffer-display 'current-window)
7555 (org-pop-to-buffer-same-window ibuf))
7556 ((eq org-indirect-buffer-display 'other-window)
7557 (pop-to-buffer ibuf))
7558 (t (error "Invalid value")))
7559 (if (featurep 'xemacs)
7560 (save-excursion (org-mode) (turn-on-font-lock)))
7561 (narrow-to-region beg end)
7562 (show-all)
7563 (goto-char pos)
7564 (run-hook-with-args 'org-cycle-hook 'all)
7565 (and (window-live-p cwin) (select-window cwin))))
7567 (defun org-get-indirect-buffer (&optional buffer heading)
7568 (setq buffer (or buffer (current-buffer)))
7569 (let ((n 1) (base (buffer-name buffer)) bname)
7570 (while (buffer-live-p
7571 (get-buffer
7572 (setq bname
7573 (concat base "-"
7574 (if heading (concat heading "-" (number-to-string n))
7575 (number-to-string n))))))
7576 (setq n (1+ n)))
7577 (condition-case nil
7578 (make-indirect-buffer buffer bname 'clone)
7579 (error (make-indirect-buffer buffer bname)))))
7581 (defun org-set-frame-title (title)
7582 "Set the title of the current frame to the string TITLE."
7583 ;; FIXME: how to name a single frame in XEmacs???
7584 (unless (featurep 'xemacs)
7585 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7587 ;;;; Structure editing
7589 ;;; Inserting headlines
7591 (defun org-previous-line-empty-p (&optional next)
7592 "Is the previous line a blank line?
7593 When NEXT is non-nil, check the next line instead."
7594 (save-excursion
7595 (and (not (bobp))
7596 (or (beginning-of-line (if next 2 0)) t)
7597 (save-match-data
7598 (looking-at "[ \t]*$")))))
7600 (defun org-insert-heading (&optional arg invisible-ok)
7601 "Insert a new heading or item with same depth at point.
7602 If point is in a plain list and ARG is nil, create a new list item.
7603 With one universal prefix argument, insert a heading even in lists.
7604 With two universal prefix arguments, insert the heading at the end
7605 of the parent subtree.
7607 If point is at the beginning of a headline, insert a sibling before
7608 the current headline. If point is not at the beginning, split the line
7609 and create a new headline with the text in the current line after point
7610 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7612 If point is at the beginning of a normal line, turn this line into
7613 a heading.
7615 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7616 This is important for non-interactive uses of the command."
7617 (interactive "P")
7618 (if (org-called-interactively-p 'any) (org-reveal))
7619 (let ((itemp (org-in-item-p))
7620 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7621 (respect-content (or org-insert-heading-respect-content
7622 (equal arg '(16))))
7623 (initial-content "")
7624 (adjust-empty-lines t))
7626 (cond
7628 ((or (= (buffer-size) 0)
7629 (and (not (save-excursion
7630 (and (ignore-errors (org-back-to-heading invisible-ok))
7631 (org-at-heading-p))))
7632 (or arg (not itemp))))
7633 ;; At beginning of buffer or so high up that only a heading
7634 ;; makes sense.
7635 (insert
7636 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7637 (if (org-in-src-block-p) ",* " "* "))
7638 (run-hooks 'org-insert-heading-hook))
7640 ((and itemp (not (equal arg '(4))))
7641 ;; Insert an item
7642 (org-insert-item))
7645 ;; Insert a heading
7646 (save-restriction
7647 (widen)
7648 (let* ((level nil)
7649 (on-heading (org-at-heading-p))
7650 (empty-line-p (if on-heading
7651 (org-previous-line-empty-p)
7652 ;; We will decide later
7653 nil))
7654 ;; Get a level string to fall back on
7655 (fix-level
7656 (save-excursion
7657 (org-back-to-heading t)
7658 (if (org-previous-line-empty-p) (setq empty-line-p t))
7659 (looking-at org-outline-regexp)
7660 (make-string (1- (length (match-string 0))) ?*)))
7661 (stars
7662 (save-excursion
7663 (condition-case nil
7664 (progn
7665 (org-back-to-heading invisible-ok)
7666 (when (and (not on-heading)
7667 (featurep 'org-inlinetask)
7668 (integerp org-inlinetask-min-level)
7669 (>= (length (match-string 0))
7670 org-inlinetask-min-level))
7671 ;; Find a heading level before the inline task
7672 (while (and (setq level (org-up-heading-safe))
7673 (>= level org-inlinetask-min-level)))
7674 (if (org-at-heading-p)
7675 (org-back-to-heading invisible-ok)
7676 (error "This should not happen")))
7677 (unless (and (save-excursion
7678 (save-match-data
7679 (org-backward-heading-same-level
7680 1 invisible-ok))
7681 (= (point) (match-beginning 0)))
7682 (not (org-previous-line-empty-p t)))
7683 (setq empty-line-p (or empty-line-p
7684 (org-previous-line-empty-p))))
7685 (match-string 0))
7686 (error (or fix-level "* ")))))
7687 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7688 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7689 pos hide-previous previous-pos)
7691 ;; If we insert after content, move there and clean up whitespace
7692 (when respect-content
7693 (org-end-of-subtree nil t)
7694 (skip-chars-backward " \r\n")
7695 (and (looking-at "[ \t]+") (replace-match ""))
7696 (unless (eobp) (forward-char 1))
7697 (when (looking-at "^\\*")
7698 (unless (bobp) (backward-char 1))
7699 (insert "\n")))
7701 ;; If we are splitting, grab the text that should be moved to the new headline
7702 (when may-split
7703 (if (org-on-heading-p)
7704 ;; This is a heading, we split intelligently (keeping tags)
7705 (let ((pos (point)))
7706 (goto-char (point-at-bol))
7707 (unless (looking-at org-complex-heading-regexp)
7708 (error "This should not happen"))
7709 (when (and (match-beginning 4)
7710 (> pos (match-beginning 4))
7711 (< pos (match-end 4)))
7712 (setq initial-content (buffer-substring pos (match-end 4)))
7713 (goto-char pos)
7714 (delete-region (point) (match-end 4))
7715 (if (looking-at "[ \t]*$")
7716 (replace-match "")
7717 (insert (make-string (length initial-content) ?\ )))
7718 (setq initial-content (org-trim initial-content)))
7719 (goto-char pos))
7720 ;; a normal line
7721 (unless (bolp)
7722 (setq initial-content (buffer-substring (point) (point-at-eol)))
7723 (delete-region (point) (point-at-eol))
7724 (setq initial-content (org-trim initial-content)))))
7726 ;; If we are at the beginning of the line, insert before it. Else after
7727 (cond
7728 ((and (bolp) (looking-at "[ \t]*$")))
7729 ((and (bolp) (not (looking-at "[ \t]*$")))
7730 (open-line 1))
7732 (goto-char (point-at-eol))
7733 (insert "\n")))
7735 ;; Insert the new heading
7736 (insert stars)
7737 (just-one-space)
7738 (insert initial-content)
7739 (when adjust-empty-lines
7740 (if (or (not blank)
7741 (and blank (not (org-previous-line-empty-p))))
7742 (org-N-empty-lines-before-current (if blank 1 0))))
7743 (run-hooks 'org-insert-heading-hook)))))))
7745 (defun org-N-empty-lines-before-current (N)
7746 "Make the number of empty lines before current exactly N.
7747 So this will delete or add empty lines."
7748 (save-excursion
7749 (goto-char (point-at-bol))
7750 (if (looking-back "\\s-+" nil 'greedy)
7751 (replace-match ""))
7752 (or (bobp) (insert "\n"))
7753 (while (> N 0)
7754 (insert "\n")
7755 (setq N (1- N)))))
7757 (defun org-get-heading (&optional no-tags no-todo)
7758 "Return the heading of the current entry, without the stars.
7759 When NO-TAGS is non-nil, don't include tags.
7760 When NO-TODO is non-nil, don't include TODO keywords."
7761 (save-excursion
7762 (org-back-to-heading t)
7763 (cond
7764 ((and no-tags no-todo)
7765 (looking-at org-complex-heading-regexp)
7766 (match-string 4))
7767 (no-tags
7768 (looking-at (concat org-outline-regexp
7769 "\\(.*?\\)"
7770 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7771 (match-string 1))
7772 (no-todo
7773 (looking-at org-todo-line-regexp)
7774 (match-string 3))
7775 (t (looking-at org-heading-regexp)
7776 (match-string 2)))))
7778 (defvar orgstruct-mode) ; defined below
7780 (defun org-heading-components ()
7781 "Return the components of the current heading.
7782 This is a list with the following elements:
7783 - the level as an integer
7784 - the reduced level, different if `org-odd-levels-only' is set.
7785 - the TODO keyword, or nil
7786 - the priority character, like ?A, or nil if no priority is given
7787 - the headline text itself, or the tags string if no headline text
7788 - the tags string, or nil."
7789 (save-excursion
7790 (org-back-to-heading t)
7791 (if (let (case-fold-search)
7792 (looking-at
7793 (if orgstruct-mode
7794 org-heading-regexp
7795 org-complex-heading-regexp)))
7796 (if orgstruct-mode
7797 (list (length (match-string 1))
7798 (org-reduced-level (length (match-string 1)))
7801 (match-string 2)
7802 nil)
7803 (list (length (match-string 1))
7804 (org-reduced-level (length (match-string 1)))
7805 (org-match-string-no-properties 2)
7806 (and (match-end 3) (aref (match-string 3) 2))
7807 (org-match-string-no-properties 4)
7808 (org-match-string-no-properties 5))))))
7810 (defun org-get-entry ()
7811 "Get the entry text, after heading, entire subtree."
7812 (save-excursion
7813 (org-back-to-heading t)
7814 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7816 (defun org-insert-heading-after-current ()
7817 "Insert a new heading with same level as current, after current subtree."
7818 (interactive)
7819 (org-back-to-heading)
7820 (org-insert-heading)
7821 (org-move-subtree-down)
7822 (end-of-line 1))
7824 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7825 "Insert heading with `org-insert-heading-respect-content' set to t."
7826 (interactive "P")
7827 (let ((org-insert-heading-respect-content t))
7828 (org-insert-heading '(4) invisible-ok)))
7830 (defun org-insert-todo-heading-respect-content (&optional force-state)
7831 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7832 (interactive "P")
7833 (let ((org-insert-heading-respect-content t))
7834 (org-insert-todo-heading force-state '(4))))
7836 (defun org-insert-todo-heading (arg &optional force-heading)
7837 "Insert a new heading with the same level and TODO state as current heading.
7838 If the heading has no TODO state, or if the state is DONE, use the first
7839 state (TODO by default). Also one prefix arg, force first state. With two
7840 prefix args, force inserting at the end of the parent subtree."
7841 (interactive "P")
7842 (when (or force-heading (not (org-insert-item 'checkbox)))
7843 (org-insert-heading (or (and (equal arg '(16)) '(16))
7844 force-heading))
7845 (save-excursion
7846 (org-back-to-heading)
7847 (outline-previous-heading)
7848 (looking-at org-todo-line-regexp))
7849 (let*
7850 ((new-mark-x
7851 (if (or arg
7852 (not (match-beginning 2))
7853 (member (match-string 2) org-done-keywords))
7854 (car org-todo-keywords-1)
7855 (match-string 2)))
7856 (new-mark
7858 (run-hook-with-args-until-success
7859 'org-todo-get-default-hook new-mark-x nil)
7860 new-mark-x)))
7861 (beginning-of-line 1)
7862 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7863 (if org-treat-insert-todo-heading-as-state-change
7864 (org-todo new-mark)
7865 (insert new-mark " "))))
7866 (when org-provide-todo-statistics
7867 (org-update-parent-todo-statistics))))
7869 (defun org-insert-subheading (arg)
7870 "Insert a new subheading and demote it.
7871 Works for outline headings and for plain lists alike."
7872 (interactive "P")
7873 (org-insert-heading arg)
7874 (cond
7875 ((org-at-heading-p) (org-do-demote))
7876 ((org-at-item-p) (org-indent-item))))
7878 (defun org-insert-todo-subheading (arg)
7879 "Insert a new subheading with TODO keyword or checkbox and demote it.
7880 Works for outline headings and for plain lists alike."
7881 (interactive "P")
7882 (org-insert-todo-heading arg)
7883 (cond
7884 ((org-at-heading-p) (org-do-demote))
7885 ((org-at-item-p) (org-indent-item))))
7887 ;;; Promotion and Demotion
7889 (defvar org-after-demote-entry-hook nil
7890 "Hook run after an entry has been demoted.
7891 The cursor will be at the beginning of the entry.
7892 When a subtree is being demoted, the hook will be called for each node.")
7894 (defvar org-after-promote-entry-hook nil
7895 "Hook run after an entry has been promoted.
7896 The cursor will be at the beginning of the entry.
7897 When a subtree is being promoted, the hook will be called for each node.")
7899 (defun org-promote-subtree ()
7900 "Promote the entire subtree.
7901 See also `org-promote'."
7902 (interactive)
7903 (save-excursion
7904 (org-with-limited-levels (org-map-tree 'org-promote)))
7905 (org-fix-position-after-promote))
7907 (defun org-demote-subtree ()
7908 "Demote the entire subtree. See `org-demote'.
7909 See also `org-promote'."
7910 (interactive)
7911 (save-excursion
7912 (org-with-limited-levels (org-map-tree 'org-demote)))
7913 (org-fix-position-after-promote))
7916 (defun org-do-promote ()
7917 "Promote the current heading higher up the tree.
7918 If the region is active in `transient-mark-mode', promote all headings
7919 in the region."
7920 (interactive)
7921 (save-excursion
7922 (if (org-region-active-p)
7923 (org-map-region 'org-promote (region-beginning) (region-end))
7924 (org-promote)))
7925 (org-fix-position-after-promote))
7927 (defun org-do-demote ()
7928 "Demote the current heading lower down the tree.
7929 If the region is active in `transient-mark-mode', demote all headings
7930 in the region."
7931 (interactive)
7932 (save-excursion
7933 (if (org-region-active-p)
7934 (org-map-region 'org-demote (region-beginning) (region-end))
7935 (org-demote)))
7936 (org-fix-position-after-promote))
7938 (defun org-fix-position-after-promote ()
7939 "Make sure that after pro/demotion cursor position is right."
7940 (let ((pos (point)))
7941 (when (save-excursion
7942 (beginning-of-line 1)
7943 (looking-at org-todo-line-regexp)
7944 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7945 (cond ((eobp) (insert " "))
7946 ((eolp) (insert " "))
7947 ((equal (char-after) ?\ ) (forward-char 1))))))
7949 (defun org-current-level ()
7950 "Return the level of the current entry, or nil if before the first headline.
7951 The level is the number of stars at the beginning of the headline."
7952 (save-excursion
7953 (org-with-limited-levels
7954 (if (ignore-errors (org-back-to-heading t))
7955 (funcall outline-level)))))
7957 (defun org-get-previous-line-level ()
7958 "Return the outline depth of the last headline before the current line.
7959 Returns 0 for the first headline in the buffer, and nil if before the
7960 first headline."
7961 (and (org-current-level)
7962 (or (and (/= (line-beginning-position) (point-min))
7963 (save-excursion (beginning-of-line 0) (org-current-level)))
7964 0)))
7966 (defun org-reduced-level (l)
7967 "Compute the effective level of a heading.
7968 This takes into account the setting of `org-odd-levels-only'."
7969 (cond
7970 ((zerop l) 0)
7971 (org-odd-levels-only (1+ (floor (/ l 2))))
7972 (t l)))
7974 (defun org-level-increment ()
7975 "Return the number of stars that will be added or removed at a
7976 time to headlines when structure editing, based on the value of
7977 `org-odd-levels-only'."
7978 (if org-odd-levels-only 2 1))
7980 (defun org-get-valid-level (level &optional change)
7981 "Rectify a level change under the influence of `org-odd-levels-only'
7982 LEVEL is a current level, CHANGE is by how much the level should be
7983 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7984 even level numbers will become the next higher odd number."
7985 (if org-odd-levels-only
7986 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7987 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7988 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7989 (max 1 (+ level (or change 0)))))
7991 (if (boundp 'define-obsolete-function-alias)
7992 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7993 (define-obsolete-function-alias 'org-get-legal-level
7994 'org-get-valid-level)
7995 (define-obsolete-function-alias 'org-get-legal-level
7996 'org-get-valid-level "23.1")))
7998 (defun org-promote ()
7999 "Promote the current heading higher up the tree.
8000 If the region is active in `transient-mark-mode', promote all headings
8001 in the region."
8002 (org-back-to-heading t)
8003 (let* ((level (save-match-data (funcall outline-level)))
8004 (after-change-functions (remove 'flyspell-after-change-function
8005 after-change-functions))
8006 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8007 (diff (abs (- level (length up-head) -1))))
8008 (cond ((and (= level 1) org-called-with-limited-levels
8009 org-allow-promoting-top-level-subtree)
8010 (replace-match "# " nil t))
8011 ((= level 1)
8012 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8013 (t (replace-match up-head nil t)))
8014 ;; Fixup tag positioning
8015 (unless (= level 1)
8016 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8017 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8018 (run-hooks 'org-after-promote-entry-hook)))
8020 (defun org-demote ()
8021 "Demote the current heading lower down the tree.
8022 If the region is active in `transient-mark-mode', demote all headings
8023 in the region."
8024 (org-back-to-heading t)
8025 (let* ((level (save-match-data (funcall outline-level)))
8026 (after-change-functions (remove 'flyspell-after-change-function
8027 after-change-functions))
8028 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8029 (diff (abs (- level (length down-head) -1))))
8030 (replace-match down-head nil t)
8031 ;; Fixup tag positioning
8032 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8033 (if org-adapt-indentation (org-fixup-indentation diff))
8034 (run-hooks 'org-after-demote-entry-hook)))
8036 (defun org-cycle-level ()
8037 "Cycle the level of an empty headline through possible states.
8038 This goes first to child, then to parent, level, then up the hierarchy.
8039 After top level, it switches back to sibling level."
8040 (interactive)
8041 (let ((org-adapt-indentation nil))
8042 (when (org-point-at-end-of-empty-headline)
8043 (setq this-command 'org-cycle-level) ; Only needed for caching
8044 (let ((cur-level (org-current-level))
8045 (prev-level (org-get-previous-line-level)))
8046 (cond
8047 ;; If first headline in file, promote to top-level.
8048 ((= prev-level 0)
8049 (loop repeat (/ (- cur-level 1) (org-level-increment))
8050 do (org-do-promote)))
8051 ;; If same level as prev, demote one.
8052 ((= prev-level cur-level)
8053 (org-do-demote))
8054 ;; If parent is top-level, promote to top level if not already.
8055 ((= prev-level 1)
8056 (loop repeat (/ (- cur-level 1) (org-level-increment))
8057 do (org-do-promote)))
8058 ;; If top-level, return to prev-level.
8059 ((= cur-level 1)
8060 (loop repeat (/ (- prev-level 1) (org-level-increment))
8061 do (org-do-demote)))
8062 ;; If less than prev-level, promote one.
8063 ((< cur-level prev-level)
8064 (org-do-promote))
8065 ;; If deeper than prev-level, promote until higher than
8066 ;; prev-level.
8067 ((> cur-level prev-level)
8068 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8069 do (org-do-promote))))
8070 t))))
8072 (defun org-map-tree (fun)
8073 "Call FUN for every heading underneath the current one."
8074 (org-back-to-heading)
8075 (let ((level (funcall outline-level)))
8076 (save-excursion
8077 (funcall fun)
8078 (while (and (progn
8079 (outline-next-heading)
8080 (> (funcall outline-level) level))
8081 (not (eobp)))
8082 (funcall fun)))))
8084 (defun org-map-region (fun beg end)
8085 "Call FUN for every heading between BEG and END."
8086 (let ((org-ignore-region t))
8087 (save-excursion
8088 (setq end (copy-marker end))
8089 (goto-char beg)
8090 (if (and (re-search-forward org-outline-regexp-bol nil t)
8091 (< (point) end))
8092 (funcall fun))
8093 (while (and (progn
8094 (outline-next-heading)
8095 (< (point) end))
8096 (not (eobp)))
8097 (funcall fun)))))
8099 (defvar org-property-end-re) ; silence byte-compiler
8100 (defun org-fixup-indentation (diff)
8101 "Change the indentation in the current entry by DIFF.
8102 However, if any line in the current entry has no indentation, or if it
8103 would end up with no indentation after the change, nothing at all is done."
8104 (save-excursion
8105 (let ((end (save-excursion (outline-next-heading)
8106 (point-marker)))
8107 (prohibit (if (> diff 0)
8108 "^\\S-"
8109 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8110 col)
8111 (unless (save-excursion (end-of-line 1)
8112 (re-search-forward prohibit end t))
8113 (while (and (< (point) end)
8114 (re-search-forward "^[ \t]+" end t))
8115 (goto-char (match-end 0))
8116 (setq col (current-column))
8117 (if (< diff 0) (replace-match ""))
8118 (org-indent-to-column (+ diff col))))
8119 (move-marker end nil))))
8121 (defun org-convert-to-odd-levels ()
8122 "Convert an org-mode file with all levels allowed to one with odd levels.
8123 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8124 level 5 etc."
8125 (interactive)
8126 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8127 (let ((outline-level 'org-outline-level)
8128 (org-odd-levels-only nil) n)
8129 (save-excursion
8130 (goto-char (point-min))
8131 (while (re-search-forward "^\\*\\*+ " nil t)
8132 (setq n (- (length (match-string 0)) 2))
8133 (while (>= (setq n (1- n)) 0)
8134 (org-demote))
8135 (end-of-line 1))))))
8137 (defun org-convert-to-oddeven-levels ()
8138 "Convert an org-mode file with only odd levels to one with odd/even levels.
8139 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8140 file contains a section with an even level, conversion would
8141 destroy the structure of the file. An error is signaled in this
8142 case."
8143 (interactive)
8144 (goto-char (point-min))
8145 ;; First check if there are no even levels
8146 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8147 (org-show-context t)
8148 (error "Not all levels are odd in this file. Conversion not possible"))
8149 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8150 (let ((outline-regexp org-outline-regexp)
8151 (outline-level 'org-outline-level)
8152 (org-odd-levels-only nil) n)
8153 (save-excursion
8154 (goto-char (point-min))
8155 (while (re-search-forward "^\\*\\*+ " nil t)
8156 (setq n (/ (1- (length (match-string 0))) 2))
8157 (while (>= (setq n (1- n)) 0)
8158 (org-promote))
8159 (end-of-line 1))))))
8161 (defun org-tr-level (n)
8162 "Make N odd if required."
8163 (if org-odd-levels-only (1+ (/ n 2)) n))
8165 ;;; Vertical tree motion, cutting and pasting of subtrees
8167 (defun org-move-subtree-up (&optional arg)
8168 "Move the current subtree up past ARG headlines of the same level."
8169 (interactive "p")
8170 (org-move-subtree-down (- (prefix-numeric-value arg))))
8172 (defun org-move-subtree-down (&optional arg)
8173 "Move the current subtree down past ARG headlines of the same level."
8174 (interactive "p")
8175 (setq arg (prefix-numeric-value arg))
8176 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8177 'org-get-last-sibling))
8178 (ins-point (make-marker))
8179 (cnt (abs arg))
8180 (col (current-column))
8181 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8182 ;; Select the tree
8183 (org-back-to-heading)
8184 (setq beg0 (point))
8185 (save-excursion
8186 (setq ne-beg (org-back-over-empty-lines))
8187 (setq beg (point)))
8188 (save-match-data
8189 (save-excursion (outline-end-of-heading)
8190 (setq folded (outline-invisible-p)))
8191 (outline-end-of-subtree))
8192 (outline-next-heading)
8193 (setq ne-end (org-back-over-empty-lines))
8194 (setq end (point))
8195 (goto-char beg0)
8196 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8197 ;; include less whitespace
8198 (save-excursion
8199 (goto-char beg)
8200 (forward-line (- ne-beg ne-end))
8201 (setq beg (point))))
8202 ;; Find insertion point, with error handling
8203 (while (> cnt 0)
8204 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8205 (progn (goto-char beg0)
8206 (user-error "Cannot move past superior level or buffer limit")))
8207 (setq cnt (1- cnt)))
8208 (if (> arg 0)
8209 ;; Moving forward - still need to move over subtree
8210 (progn (org-end-of-subtree t t)
8211 (save-excursion
8212 (org-back-over-empty-lines)
8213 (or (bolp) (newline)))))
8214 (setq ne-ins (org-back-over-empty-lines))
8215 (move-marker ins-point (point))
8216 (setq txt (buffer-substring beg end))
8217 (org-save-markers-in-region beg end)
8218 (delete-region beg end)
8219 (org-remove-empty-overlays-at beg)
8220 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8221 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8222 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8223 (let ((bbb (point)))
8224 (insert-before-markers txt)
8225 (org-reinstall-markers-in-region bbb)
8226 (move-marker ins-point bbb))
8227 (or (bolp) (insert "\n"))
8228 (setq ins-end (point))
8229 (goto-char ins-point)
8230 (org-skip-whitespace)
8231 (when (and (< arg 0)
8232 (org-first-sibling-p)
8233 (> ne-ins ne-beg))
8234 ;; Move whitespace back to beginning
8235 (save-excursion
8236 (goto-char ins-end)
8237 (let ((kill-whole-line t))
8238 (kill-line (- ne-ins ne-beg)) (point)))
8239 (insert (make-string (- ne-ins ne-beg) ?\n)))
8240 (move-marker ins-point nil)
8241 (if folded
8242 (hide-subtree)
8243 (org-show-entry)
8244 (show-children)
8245 (org-cycle-hide-drawers 'children))
8246 (org-clean-visibility-after-subtree-move)
8247 ;; move back to the initial column we were at
8248 (move-to-column col)))
8250 (defvar org-subtree-clip ""
8251 "Clipboard for cut and paste of subtrees.
8252 This is actually only a copy of the kill, because we use the normal kill
8253 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8255 (defvar org-subtree-clip-folded nil
8256 "Was the last copied subtree folded?
8257 This is used to fold the tree back after pasting.")
8259 (defun org-cut-subtree (&optional n)
8260 "Cut the current subtree into the clipboard.
8261 With prefix arg N, cut this many sequential subtrees.
8262 This is a short-hand for marking the subtree and then cutting it."
8263 (interactive "p")
8264 (org-copy-subtree n 'cut))
8266 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8267 "Copy the current subtree it in the clipboard.
8268 With prefix arg N, copy this many sequential subtrees.
8269 This is a short-hand for marking the subtree and then copying it.
8270 If CUT is non-nil, actually cut the subtree.
8271 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8272 of some markers in the region, even if CUT is non-nil. This is
8273 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8274 (interactive "p")
8275 (let (beg end folded (beg0 (point)))
8276 (if (org-called-interactively-p 'any)
8277 (org-back-to-heading nil) ; take what looks like a subtree
8278 (org-back-to-heading t)) ; take what is really there
8279 (setq beg (point))
8280 (skip-chars-forward " \t\r\n")
8281 (save-match-data
8282 (if nosubtrees
8283 (outline-next-heading)
8284 (save-excursion (outline-end-of-heading)
8285 (setq folded (outline-invisible-p)))
8286 (condition-case nil
8287 (org-forward-heading-same-level (1- n) t)
8288 (error nil))
8289 (org-end-of-subtree t t)))
8290 (setq end (point))
8291 (goto-char beg0)
8292 (when (> end beg)
8293 (setq org-subtree-clip-folded folded)
8294 (when (or cut force-store-markers)
8295 (org-save-markers-in-region beg end))
8296 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8297 (setq org-subtree-clip (current-kill 0))
8298 (message "%s: Subtree(s) with %d characters"
8299 (if cut "Cut" "Copied")
8300 (length org-subtree-clip)))))
8302 (defun org-paste-subtree (&optional level tree for-yank)
8303 "Paste the clipboard as a subtree, with modification of headline level.
8304 The entire subtree is promoted or demoted in order to match a new headline
8305 level.
8307 If the cursor is at the beginning of a headline, the same level as
8308 that headline is used to paste the tree.
8310 If not, the new level is derived from the *visible* headings
8311 before and after the insertion point, and taken to be the inferior headline
8312 level of the two. So if the previous visible heading is level 3 and the
8313 next is level 4 (or vice versa), level 4 will be used for insertion.
8314 This makes sure that the subtree remains an independent subtree and does
8315 not swallow low level entries.
8317 You can also force a different level, either by using a numeric prefix
8318 argument, or by inserting the heading marker by hand. For example, if the
8319 cursor is after \"*****\", then the tree will be shifted to level 5.
8321 If optional TREE is given, use this text instead of the kill ring.
8323 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8324 move back over whitespace before inserting, and move point to the end of
8325 the inserted text when done."
8326 (interactive "P")
8327 (setq tree (or tree (and kill-ring (current-kill 0))))
8328 (unless (org-kill-is-subtree-p tree)
8329 (user-error "%s"
8330 (substitute-command-keys
8331 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8332 (org-with-limited-levels
8333 (let* ((visp (not (outline-invisible-p)))
8334 (txt tree)
8335 (^re_ "\\(\\*+\\)[ \t]*")
8336 (old-level (if (string-match org-outline-regexp-bol txt)
8337 (- (match-end 0) (match-beginning 0) 1)
8338 -1))
8339 (force-level (cond (level (prefix-numeric-value level))
8340 ((and (looking-at "[ \t]*$")
8341 (string-match
8342 "^\\*+$" (buffer-substring
8343 (point-at-bol) (point))))
8344 (- (match-end 1) (match-beginning 1)))
8345 ((and (bolp)
8346 (looking-at org-outline-regexp))
8347 (- (match-end 0) (point) 1))))
8348 (previous-level (save-excursion
8349 (condition-case nil
8350 (progn
8351 (outline-previous-visible-heading 1)
8352 (if (looking-at ^re_)
8353 (- (match-end 0) (match-beginning 0) 1)
8355 (error 1))))
8356 (next-level (save-excursion
8357 (condition-case nil
8358 (progn
8359 (or (looking-at org-outline-regexp)
8360 (outline-next-visible-heading 1))
8361 (if (looking-at ^re_)
8362 (- (match-end 0) (match-beginning 0) 1)
8364 (error 1))))
8365 (new-level (or force-level (max previous-level next-level)))
8366 (shift (if (or (= old-level -1)
8367 (= new-level -1)
8368 (= old-level new-level))
8370 (- new-level old-level)))
8371 (delta (if (> shift 0) -1 1))
8372 (func (if (> shift 0) 'org-demote 'org-promote))
8373 (org-odd-levels-only nil)
8374 beg end newend)
8375 ;; Remove the forced level indicator
8376 (if force-level
8377 (delete-region (point-at-bol) (point)))
8378 ;; Paste
8379 (beginning-of-line (if (bolp) 1 2))
8380 (setq beg (point))
8381 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8382 (insert-before-markers txt)
8383 (unless (string-match "\n\\'" txt) (insert "\n"))
8384 (setq newend (point))
8385 (org-reinstall-markers-in-region beg)
8386 (setq end (point))
8387 (goto-char beg)
8388 (skip-chars-forward " \t\n\r")
8389 (setq beg (point))
8390 (if (and (outline-invisible-p) visp)
8391 (save-excursion (outline-show-heading)))
8392 ;; Shift if necessary
8393 (unless (= shift 0)
8394 (save-restriction
8395 (narrow-to-region beg end)
8396 (while (not (= shift 0))
8397 (org-map-region func (point-min) (point-max))
8398 (setq shift (+ delta shift)))
8399 (goto-char (point-min))
8400 (setq newend (point-max))))
8401 (when (or (org-called-interactively-p 'interactive) for-yank)
8402 (message "Clipboard pasted as level %d subtree" new-level))
8403 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8404 kill-ring
8405 (eq org-subtree-clip (current-kill 0))
8406 org-subtree-clip-folded)
8407 ;; The tree was folded before it was killed/copied
8408 (hide-subtree))
8409 (and for-yank (goto-char newend)))))
8411 (defun org-kill-is-subtree-p (&optional txt)
8412 "Check if the current kill is an outline subtree, or a set of trees.
8413 Returns nil if kill does not start with a headline, or if the first
8414 headline level is not the largest headline level in the tree.
8415 So this will actually accept several entries of equal levels as well,
8416 which is OK for `org-paste-subtree'.
8417 If optional TXT is given, check this string instead of the current kill."
8418 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8419 (re (org-get-limited-outline-regexp))
8420 (^re (concat "^" re))
8421 (start-level (and kill
8422 (string-match
8423 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8424 kill)
8425 (- (match-end 2) (match-beginning 2) 1)))
8426 (start (1+ (or (match-beginning 2) -1))))
8427 (if (not start-level)
8428 (progn
8429 nil) ;; does not even start with a heading
8430 (catch 'exit
8431 (while (setq start (string-match ^re kill (1+ start)))
8432 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8433 (throw 'exit nil)))
8434 t))))
8436 (defvar org-markers-to-move nil
8437 "Markers that should be moved with a cut-and-paste operation.
8438 Those markers are stored together with their positions relative to
8439 the start of the region.")
8441 (defun org-save-markers-in-region (beg end)
8442 "Check markers in region.
8443 If these markers are between BEG and END, record their position relative
8444 to BEG, so that after moving the block of text, we can put the markers back
8445 into place.
8446 This function gets called just before an entry or tree gets cut from the
8447 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8448 called immediately, to move the markers with the entries."
8449 (setq org-markers-to-move nil)
8450 (when (featurep 'org-clock)
8451 (org-clock-save-markers-for-cut-and-paste beg end))
8452 (when (featurep 'org-agenda)
8453 (org-agenda-save-markers-for-cut-and-paste beg end)))
8455 (defun org-check-and-save-marker (marker beg end)
8456 "Check if MARKER is between BEG and END.
8457 If yes, remember the marker and the distance to BEG."
8458 (when (and (marker-buffer marker)
8459 (equal (marker-buffer marker) (current-buffer)))
8460 (if (and (>= marker beg) (< marker end))
8461 (push (cons marker (- marker beg)) org-markers-to-move))))
8463 (defun org-reinstall-markers-in-region (beg)
8464 "Move all remembered markers to their position relative to BEG."
8465 (mapc (lambda (x)
8466 (move-marker (car x) (+ beg (cdr x))))
8467 org-markers-to-move)
8468 (setq org-markers-to-move nil))
8470 (defun org-narrow-to-subtree ()
8471 "Narrow buffer to the current subtree."
8472 (interactive)
8473 (save-excursion
8474 (save-match-data
8475 (org-with-limited-levels
8476 (narrow-to-region
8477 (progn (org-back-to-heading t) (point))
8478 (progn (org-end-of-subtree t t)
8479 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8480 (point)))))))
8482 (defun org-narrow-to-block ()
8483 "Narrow buffer to the current block."
8484 (interactive)
8485 (let* ((case-fold-search t)
8486 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8487 "^[ \t]*#\\+end_.*")))
8488 (if blockp
8489 (narrow-to-region (car blockp) (cdr blockp))
8490 (user-error "Not in a block"))))
8492 (eval-when-compile
8493 (defvar org-property-drawer-re))
8495 (defvar org-property-start-re) ;; defined below
8496 (defun org-clone-subtree-with-time-shift (n &optional shift)
8497 "Clone the task (subtree) at point N times.
8498 The clones will be inserted as siblings.
8500 In interactive use, the user will be prompted for the number of
8501 clones to be produced. If the entry has a timestamp, the user
8502 will also be prompted for a time shift, which may be a repeater
8503 as used in time stamps, for example `+3d'. To disable this,
8504 you can call the function with a universal prefix argument.
8506 When a valid repeater is given and the entry contains any time
8507 stamps, the clones will become a sequence in time, with time
8508 stamps in the subtree shifted for each clone produced. If SHIFT
8509 is nil or the empty string, time stamps will be left alone. The
8510 ID property of the original subtree is removed.
8512 If the original subtree did contain time stamps with a repeater,
8513 the following will happen:
8514 - the repeater will be removed in each clone
8515 - an additional clone will be produced, with the current, unshifted
8516 date(s) in the entry.
8517 - the original entry will be placed *after* all the clones, with
8518 repeater intact.
8519 - the start days in the repeater in the original entry will be shifted
8520 to past the last clone.
8521 In this way you can spell out a number of instances of a repeating task,
8522 and still retain the repeater to cover future instances of the task."
8523 (interactive "nNumber of clones to produce: ")
8524 (let ((shift
8525 (or shift
8526 (if (and (not (equal current-prefix-arg '(4)))
8527 (save-excursion
8528 (re-search-forward org-ts-regexp-both
8529 (save-excursion
8530 (org-end-of-subtree t)
8531 (point)) t)))
8532 (read-from-minibuffer
8533 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8534 ""))) ;; No time shift
8535 (n-no-remove -1)
8536 (drawer-re org-drawer-regexp)
8537 beg end template task idprop
8538 shift-n shift-what doshift nmin nmax)
8539 (if (not (and (integerp n) (> n 0)))
8540 (error "Invalid number of replications %s" n))
8541 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8542 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8543 shift)))
8544 (error "Invalid shift specification %s" shift))
8545 (when doshift
8546 (setq shift-n (string-to-number (match-string 1 shift))
8547 shift-what (cdr (assoc (match-string 2 shift)
8548 '(("d" . day) ("w" . week)
8549 ("m" . month) ("y" . year))))))
8550 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8551 (setq nmin 1 nmax n)
8552 (org-back-to-heading t)
8553 (setq beg (point))
8554 (setq idprop (org-entry-get nil "ID"))
8555 (org-end-of-subtree t t)
8556 (or (bolp) (insert "\n"))
8557 (setq end (point))
8558 (setq template (buffer-substring beg end))
8559 (when (and doshift
8560 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8561 (delete-region beg end)
8562 (setq end beg)
8563 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8564 (goto-char end)
8565 (loop for n from nmin to nmax do
8566 ;; prepare clone
8567 (with-temp-buffer
8568 (insert template)
8569 (org-mode)
8570 (goto-char (point-min))
8571 (org-show-subtree)
8572 (and idprop (if org-clone-delete-id
8573 (org-entry-delete nil "ID")
8574 (org-id-get-create t)))
8575 (unless (= n 0)
8576 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8577 (kill-whole-line))
8578 (goto-char (point-min))
8579 (while (re-search-forward drawer-re nil t)
8580 (org-remove-empty-drawer-at (point))))
8581 (goto-char (point-min))
8582 (when doshift
8583 (while (re-search-forward org-ts-regexp-both nil t)
8584 (org-timestamp-change (* n shift-n) shift-what))
8585 (unless (= n n-no-remove)
8586 (goto-char (point-min))
8587 (while (re-search-forward org-ts-regexp nil t)
8588 (save-excursion
8589 (goto-char (match-beginning 0))
8590 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8591 (delete-region (match-beginning 1) (match-end 1)))))))
8592 (setq task (buffer-string)))
8593 (insert task))
8594 (goto-char beg)))
8596 ;;; Outline Sorting
8598 (defun org-sort (with-case)
8599 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8600 Optional argument WITH-CASE means sort case-sensitively."
8601 (interactive "P")
8602 (cond
8603 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8604 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8606 (org-call-with-arg 'org-sort-entries with-case))))
8608 (defun org-sort-remove-invisible (s)
8609 "Remove invisible links from string S."
8610 (remove-text-properties 0 (length s) org-rm-props s)
8611 (while (string-match org-bracket-link-regexp s)
8612 (setq s (replace-match (if (match-end 2)
8613 (match-string 3 s)
8614 (match-string 1 s)) t t s)))
8615 (let ((st (format " %s " s)))
8616 (while (string-match org-emph-re st)
8617 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8618 (setq s (substring st 1 -1)))
8621 (defvar org-priority-regexp) ; defined later in the file
8623 (defvar org-after-sorting-entries-or-items-hook nil
8624 "Hook that is run after a bunch of entries or items have been sorted.
8625 When children are sorted, the cursor is in the parent line when this
8626 hook gets called. When a region or a plain list is sorted, the cursor
8627 will be in the first entry of the sorted region/list.")
8629 (defun org-sort-entries
8630 (&optional with-case sorting-type getkey-func compare-func property)
8631 "Sort entries on a certain level of an outline tree.
8632 If there is an active region, the entries in the region are sorted.
8633 Else, if the cursor is before the first entry, sort the top-level items.
8634 Else, the children of the entry at point are sorted.
8636 Sorting can be alphabetically, numerically, by date/time as given by
8637 a time stamp, by a property, by priority order, or by a custom function.
8639 The command prompts for the sorting type unless it has been given to the
8640 function through the SORTING-TYPE argument, which needs to be a character,
8641 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8642 precise meaning of each character:
8644 n Numerically, by converting the beginning of the entry/item to a number.
8645 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8646 o By order of TODO keywords.
8647 t By date/time, either the first active time stamp in the entry, or, if
8648 none exist, by the first inactive one.
8649 s By the scheduled date/time.
8650 d By deadline date/time.
8651 c By creation time, which is assumed to be the first inactive time stamp
8652 at the beginning of a line.
8653 p By priority according to the cookie.
8654 r By the value of a property.
8656 Capital letters will reverse the sort order.
8658 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8659 called with point at the beginning of the record. It must return either
8660 a string or a number that should serve as the sorting key for that record.
8662 Comparing entries ignores case by default. However, with an optional argument
8663 WITH-CASE, the sorting considers case as well.
8665 Sorting is done against the visible part of the headlines, it ignores hidden
8666 links.
8668 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8669 (interactive "P")
8670 (let ((case-func (if with-case 'identity 'downcase))
8671 (cmstr
8672 ;; The clock marker is lost when using `sort-subr', let's
8673 ;; store the clocking string.
8674 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8675 (save-excursion
8676 (goto-char org-clock-marker)
8677 (looking-back "^.*") (match-string-no-properties 0))))
8678 start beg end stars re re2
8679 txt what tmp)
8680 ;; Find beginning and end of region to sort
8681 (cond
8682 ((org-region-active-p)
8683 ;; we will sort the region
8684 (setq end (region-end)
8685 what "region")
8686 (goto-char (region-beginning))
8687 (if (not (org-at-heading-p)) (outline-next-heading))
8688 (setq start (point)))
8689 ((or (org-at-heading-p)
8690 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8691 ;; we will sort the children of the current headline
8692 (org-back-to-heading)
8693 (setq start (point)
8694 end (progn (org-end-of-subtree t t)
8695 (or (bolp) (insert "\n"))
8696 (org-back-over-empty-lines)
8697 (point))
8698 what "children")
8699 (goto-char start)
8700 (show-subtree)
8701 (outline-next-heading))
8703 ;; we will sort the top-level entries in this file
8704 (goto-char (point-min))
8705 (or (org-at-heading-p) (outline-next-heading))
8706 (setq start (point))
8707 (goto-char (point-max))
8708 (beginning-of-line 1)
8709 (when (looking-at ".*?\\S-")
8710 ;; File ends in a non-white line
8711 (end-of-line 1)
8712 (insert "\n"))
8713 (setq end (point-max))
8714 (setq what "top-level")
8715 (goto-char start)
8716 (show-all)))
8718 (setq beg (point))
8719 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8721 (looking-at "\\(\\*+\\)")
8722 (setq stars (match-string 1)
8723 re (concat "^" (regexp-quote stars) " +")
8724 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8725 txt (buffer-substring beg end))
8726 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8727 (if (and (not (equal stars "*")) (string-match re2 txt))
8728 (user-error "Region to sort contains a level above the first entry"))
8730 (unless sorting-type
8731 (message
8732 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8733 [t]ime [s]cheduled [d]eadline [c]reated
8734 A/N/P/R/O/F/T/S/D/C means reversed:"
8735 what)
8736 (setq sorting-type (read-char-exclusive))
8738 (unless getkey-func
8739 (and (= (downcase sorting-type) ?f)
8740 (setq getkey-func
8741 (org-icompleting-read "Sort using function: "
8742 obarray 'fboundp t nil nil))
8743 (setq getkey-func (intern getkey-func))))
8745 (and (= (downcase sorting-type) ?r)
8746 (not property)
8747 (setq property
8748 (org-icompleting-read "Property: "
8749 (mapcar 'list (org-buffer-property-keys t))
8750 nil t))))
8752 (message "Sorting entries...")
8754 (save-restriction
8755 (narrow-to-region start end)
8756 (let ((dcst (downcase sorting-type))
8757 (case-fold-search nil)
8758 (now (current-time)))
8759 (sort-subr
8760 (/= dcst sorting-type)
8761 ;; This function moves to the beginning character of the "record" to
8762 ;; be sorted.
8763 (lambda nil
8764 (if (re-search-forward re nil t)
8765 (goto-char (match-beginning 0))
8766 (goto-char (point-max))))
8767 ;; This function moves to the last character of the "record" being
8768 ;; sorted.
8769 (lambda nil
8770 (save-match-data
8771 (condition-case nil
8772 (outline-forward-same-level 1)
8773 (error
8774 (goto-char (point-max))))))
8775 ;; This function returns the value that gets sorted against.
8776 (lambda nil
8777 (cond
8778 ((= dcst ?n)
8779 (if (looking-at org-complex-heading-regexp)
8780 (string-to-number (org-sort-remove-invisible (match-string 4)))
8781 nil))
8782 ((= dcst ?a)
8783 (if (looking-at org-complex-heading-regexp)
8784 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8785 nil))
8786 ((= dcst ?t)
8787 (let ((end (save-excursion (outline-next-heading) (point))))
8788 (if (or (re-search-forward org-ts-regexp end t)
8789 (re-search-forward org-ts-regexp-both end t))
8790 (org-time-string-to-seconds (match-string 0))
8791 (org-float-time now))))
8792 ((= dcst ?c)
8793 (let ((end (save-excursion (outline-next-heading) (point))))
8794 (if (re-search-forward
8795 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8796 end t)
8797 (org-time-string-to-seconds (match-string 0))
8798 (org-float-time now))))
8799 ((= dcst ?s)
8800 (let ((end (save-excursion (outline-next-heading) (point))))
8801 (if (re-search-forward org-scheduled-time-regexp end t)
8802 (org-time-string-to-seconds (match-string 1))
8803 (org-float-time now))))
8804 ((= dcst ?d)
8805 (let ((end (save-excursion (outline-next-heading) (point))))
8806 (if (re-search-forward org-deadline-time-regexp end t)
8807 (org-time-string-to-seconds (match-string 1))
8808 (org-float-time now))))
8809 ((= dcst ?p)
8810 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8811 (string-to-char (match-string 2))
8812 org-default-priority))
8813 ((= dcst ?r)
8814 (or (org-entry-get nil property) ""))
8815 ((= dcst ?o)
8816 (if (looking-at org-complex-heading-regexp)
8817 (- 9999 (length (member (match-string 2)
8818 org-todo-keywords-1)))))
8819 ((= dcst ?f)
8820 (if getkey-func
8821 (progn
8822 (setq tmp (funcall getkey-func))
8823 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8824 tmp)
8825 (error "Invalid key function `%s'" getkey-func)))
8826 (t (error "Invalid sorting type `%c'" sorting-type))))
8828 (cond
8829 ((= dcst ?a) 'string<)
8830 ((= dcst ?f) compare-func)
8831 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8832 (run-hooks 'org-after-sorting-entries-or-items-hook)
8833 ;; Reset the clock marker if needed
8834 (when cmstr
8835 (save-excursion
8836 (goto-char start)
8837 (search-forward cmstr nil t)
8838 (move-marker org-clock-marker (point))))
8839 (message "Sorting entries...done")))
8841 (defun org-do-sort (table what &optional with-case sorting-type)
8842 "Sort TABLE of WHAT according to SORTING-TYPE.
8843 The user will be prompted for the SORTING-TYPE if the call to this
8844 function does not specify it. WHAT is only for the prompt, to indicate
8845 what is being sorted. The sorting key will be extracted from
8846 the car of the elements of the table.
8847 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8848 (unless sorting-type
8849 (message
8850 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8851 what)
8852 (setq sorting-type (read-char-exclusive)))
8853 (let ((dcst (downcase sorting-type))
8854 extractfun comparefun)
8855 ;; Define the appropriate functions
8856 (cond
8857 ((= dcst ?n)
8858 (setq extractfun 'string-to-number
8859 comparefun (if (= dcst sorting-type) '< '>)))
8860 ((= dcst ?a)
8861 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8862 (lambda(x) (downcase (org-sort-remove-invisible x))))
8863 comparefun (if (= dcst sorting-type)
8864 'string<
8865 (lambda (a b) (and (not (string< a b))
8866 (not (string= a b)))))))
8867 ((= dcst ?t)
8868 (setq extractfun
8869 (lambda (x)
8870 (if (or (string-match org-ts-regexp x)
8871 (string-match org-ts-regexp-both x))
8872 (org-float-time
8873 (org-time-string-to-time (match-string 0 x)))
8875 comparefun (if (= dcst sorting-type) '< '>)))
8876 (t (error "Invalid sorting type `%c'" sorting-type)))
8878 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8879 table)
8880 (lambda (a b) (funcall comparefun (car a) (car b))))))
8883 ;;; The orgstruct minor mode
8885 ;; Define a minor mode which can be used in other modes in order to
8886 ;; integrate the org-mode structure editing commands.
8888 ;; This is really a hack, because the org-mode structure commands use
8889 ;; keys which normally belong to the major mode. Here is how it
8890 ;; works: The minor mode defines all the keys necessary to operate the
8891 ;; structure commands, but wraps the commands into a function which
8892 ;; tests if the cursor is currently at a headline or a plain list
8893 ;; item. If that is the case, the structure command is used,
8894 ;; temporarily setting many Org-mode variables like regular
8895 ;; expressions for filling etc. However, when any of those keys is
8896 ;; used at a different location, function uses `key-binding' to look
8897 ;; up if the key has an associated command in another currently active
8898 ;; keymap (minor modes, major mode, global), and executes that
8899 ;; command. There might be problems if any of the keys is otherwise
8900 ;; used as a prefix key.
8902 (defcustom orgstruct-heading-prefix-regexp ""
8903 "Regexp that matches the custom prefix of Org headlines in
8904 orgstruct(++)-mode."
8905 :group 'org
8906 :version "24.4"
8907 :package-version '(Org . "8.3")
8908 :type 'regexp)
8909 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8911 (defcustom orgstruct-setup-hook nil
8912 "Hook run after orgstruct-mode-map is filled."
8913 :group 'org
8914 :version "24.4"
8915 :package-version '(Org . "8.0")
8916 :type 'hook)
8918 (defvar orgstruct-initialized nil)
8920 (defvar org-local-vars nil
8921 "List of local variables, for use by `orgstruct-mode'.")
8923 ;;;###autoload
8924 (define-minor-mode orgstruct-mode
8925 "Toggle the minor mode `orgstruct-mode'.
8926 This mode is for using Org-mode structure commands in other
8927 modes. The following keys behave as if Org-mode were active, if
8928 the cursor is on a headline, or on a plain list item (both as
8929 defined by Org-mode)."
8930 nil " OrgStruct" (make-sparse-keymap)
8931 (funcall (if orgstruct-mode
8932 'add-to-invisibility-spec
8933 'remove-from-invisibility-spec)
8934 '(outline . t))
8935 (when orgstruct-mode
8936 (org-load-modules-maybe)
8937 (unless orgstruct-initialized
8938 (orgstruct-setup)
8939 (setq orgstruct-initialized t))))
8941 ;;;###autoload
8942 (defun turn-on-orgstruct ()
8943 "Unconditionally turn on `orgstruct-mode'."
8944 (orgstruct-mode 1))
8946 (defvar org-fb-vars nil)
8947 (make-variable-buffer-local 'org-fb-vars)
8948 (defun orgstruct++-mode (&optional arg)
8949 "Toggle `orgstruct-mode', the enhanced version of it.
8950 In addition to setting orgstruct-mode, this also exports all
8951 indentation and autofilling variables from org-mode into the
8952 buffer. It will also recognize item context in multiline items."
8953 (interactive "P")
8954 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8955 (if (< arg 1)
8956 (progn (orgstruct-mode -1)
8957 (mapc (lambda(v)
8958 (org-set-local (car v)
8959 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8960 org-fb-vars))
8961 (orgstruct-mode 1)
8962 (setq org-fb-vars nil)
8963 (unless org-local-vars
8964 (setq org-local-vars (org-get-local-variables)))
8965 (let (var val)
8966 (mapc
8967 (lambda (x)
8968 (when (string-match
8969 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8970 (symbol-name (car x)))
8971 (setq var (car x) val (nth 1 x))
8972 (push (list var `(quote ,(eval var))) org-fb-vars)
8973 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8974 org-local-vars)
8975 (org-set-local 'orgstruct-is-++ t))))
8977 (defvar orgstruct-is-++ nil
8978 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8979 (make-variable-buffer-local 'orgstruct-is-++)
8981 ;;;###autoload
8982 (defun turn-on-orgstruct++ ()
8983 "Unconditionally turn on `orgstruct++-mode'."
8984 (orgstruct++-mode 1))
8986 (defun orgstruct-error ()
8987 "Error when there is no default binding for a structure key."
8988 (interactive)
8989 (funcall (if (fboundp 'user-error)
8990 'user-error
8991 'error)
8992 "This key has no function outside structure elements"))
8994 (defun orgstruct-setup ()
8995 "Setup orgstruct keymap."
8996 (dolist (cell '((org-demote . t)
8997 (org-metaleft . t)
8998 (org-metaright . t)
8999 (org-promote . t)
9000 (org-shiftmetaleft . t)
9001 (org-shiftmetaright . t)
9002 org-backward-element
9003 org-backward-heading-same-level
9004 org-ctrl-c-ret
9005 org-ctrl-c-minus
9006 org-ctrl-c-star
9007 org-cycle
9008 org-forward-heading-same-level
9009 org-insert-heading
9010 org-insert-heading-respect-content
9011 org-kill-note-or-show-branches
9012 org-mark-subtree
9013 org-meta-return
9014 org-metadown
9015 org-metaup
9016 org-narrow-to-subtree
9017 org-promote-subtree
9018 org-reveal
9019 org-shiftdown
9020 org-shiftleft
9021 org-shiftmetadown
9022 org-shiftmetaup
9023 org-shiftright
9024 org-shifttab
9025 org-shifttab
9026 org-shiftup
9027 org-show-subtree
9028 org-sort
9029 org-up-element
9030 outline-demote
9031 outline-next-visible-heading
9032 outline-previous-visible-heading
9033 outline-promote
9034 outline-up-heading
9035 show-children))
9036 (let ((f (or (car-safe cell) cell))
9037 (disable-when-heading-prefix (cdr-safe cell)))
9038 (when (fboundp f)
9039 (let ((new-bindings))
9040 (dolist (binding (nconc (where-is-internal f org-mode-map)
9041 (where-is-internal f outline-mode-map)))
9042 (push binding new-bindings)
9043 ;; TODO use local-function-key-map
9044 (dolist (rep '(("<tab>" . "TAB")
9045 ("<return>" . "RET")
9046 ("<escape>" . "ESC")
9047 ("<delete>" . "DEL")))
9048 (setq binding (read-kbd-macro
9049 (let ((case-fold-search))
9050 (replace-regexp-in-string
9051 (regexp-quote (cdr rep))
9052 (car rep)
9053 (key-description binding)))))
9054 (pushnew binding new-bindings :test 'equal)))
9055 (dolist (binding new-bindings)
9056 (let ((key (lookup-key orgstruct-mode-map binding)))
9057 (when (or (not key) (numberp key))
9058 (condition-case nil
9059 (org-defkey orgstruct-mode-map
9060 binding
9061 (orgstruct-make-binding f binding disable-when-heading-prefix))
9062 (error nil)))))))))
9063 (run-hooks 'orgstruct-setup-hook))
9065 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9066 "Create a function for binding in the structure minor mode.
9067 FUN is the command to call inside a table. KEY is the key that
9068 should be checked in for a command to execute outside of tables.
9069 Non-nil `disable-when-heading-prefix' means to disable the command
9070 if `orgstruct-heading-prefix-regexp' is not empty."
9071 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9072 (let ((nname name)
9073 (i 0))
9074 (while (fboundp (intern nname))
9075 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9076 (setq name (intern nname)))
9077 (eval
9078 (let ((bindings '((org-heading-regexp
9079 (concat "^"
9080 orgstruct-heading-prefix-regexp
9081 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9082 (org-outline-regexp
9083 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9084 (org-outline-regexp-bol
9085 (concat "^" org-outline-regexp))
9086 (outline-regexp org-outline-regexp)
9087 (outline-heading-end-regexp "\n")
9088 (outline-level 'org-outline-level)
9089 (outline-heading-alist))))
9090 `(defun ,name (arg)
9091 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9092 "Outside of structure, run the binding of `"
9093 (key-description key) "'."
9094 (when disable-when-heading-prefix
9095 (concat
9096 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9097 "back to the default binding due to limitations of Org's implementation of\n"
9098 "`" (symbol-name fun) "'.")))
9099 (interactive "p")
9100 (let* ((disable
9101 ,(and disable-when-heading-prefix
9102 '(not (string= orgstruct-heading-prefix-regexp ""))))
9103 (fallback
9104 (or disable
9105 (not
9106 (let* ,bindings
9107 (org-context-p 'headline 'item
9108 ,(when (memq fun
9109 '(org-insert-heading
9110 org-insert-heading-respect-content
9111 org-meta-return))
9112 '(when orgstruct-is-++
9113 'item-body))))))))
9114 (if fallback
9115 (let* ((orgstruct-mode)
9116 (binding
9117 (loop with key = ,key
9118 for rep in
9119 '(nil
9120 ("<\\([^>]*\\)tab>" . "\\1TAB")
9121 ("<\\([^>]*\\)return>" . "\\1RET")
9122 ("<\\([^>]*\\)escape>" . "\\1ESC")
9123 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9125 (when rep
9126 (setq key (read-kbd-macro
9127 (let ((case-fold-search))
9128 (replace-regexp-in-string
9129 (car rep)
9130 (cdr rep)
9131 (key-description key))))))
9132 thereis (key-binding key))))
9133 (if (keymapp binding)
9134 (org-set-transient-map binding)
9135 (let ((func (or binding
9136 (unless disable
9137 'orgstruct-error))))
9138 (when func
9139 (call-interactively func)))))
9140 (org-run-like-in-org-mode
9141 (lambda ()
9142 (interactive)
9143 (let* ,bindings
9144 (call-interactively ',fun)))))))))
9145 name))
9147 (defun org-contextualize-keys (alist contexts)
9148 "Return valid elements in ALIST depending on CONTEXTS.
9150 `org-agenda-custom-commands' or `org-capture-templates' are the
9151 values used for ALIST, and `org-agenda-custom-commands-contexts'
9152 or `org-capture-templates-contexts' are the associated contexts
9153 definitions."
9154 (let ((contexts
9155 ;; normalize contexts
9156 (mapcar
9157 (lambda(c) (cond ((listp (cadr c))
9158 (list (car c) (car c) (cadr c)))
9159 ((string= "" (cadr c))
9160 (list (car c) (car c) (caddr c)))
9161 (t c))) contexts))
9162 (a alist) c r s)
9163 ;; loop over all commands or templates
9164 (while (setq c (pop a))
9165 (let (vrules repl)
9166 (cond
9167 ((not (assoc (car c) contexts))
9168 (push c r))
9169 ((and (assoc (car c) contexts)
9170 (setq vrules (org-contextualize-validate-key
9171 (car c) contexts)))
9172 (mapc (lambda (vr)
9173 (when (not (equal (car vr) (cadr vr)))
9174 (setq repl vr))) vrules)
9175 (if (not repl) (push c r)
9176 (push (cadr repl) s)
9177 (push
9178 (cons (car c)
9179 (cdr (or (assoc (cadr repl) alist)
9180 (error "Undefined key `%s' as contextual replacement for `%s'"
9181 (cadr repl) (car c)))))
9182 r))))))
9183 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9184 (delq
9186 (delete-dups
9187 (mapcar (lambda (x)
9188 (let ((tpl (car x)))
9189 (when (not (delq
9191 (mapcar (lambda(y)
9192 (equal y tpl)) s))) x)))
9193 (reverse r))))))
9195 (defun org-contextualize-validate-key (key contexts)
9196 "Check CONTEXTS for agenda or capture KEY."
9197 (let (r rr res)
9198 (while (setq r (pop contexts))
9199 (mapc
9200 (lambda (rr)
9201 (when
9202 (and (equal key (car r))
9203 (if (functionp rr) (funcall rr)
9204 (or (and (eq (car rr) 'in-file)
9205 (buffer-file-name)
9206 (string-match (cdr rr) (buffer-file-name)))
9207 (and (eq (car rr) 'in-mode)
9208 (string-match (cdr rr) (symbol-name major-mode)))
9209 (and (eq (car rr) 'in-buffer)
9210 (string-match (cdr rr) (buffer-name)))
9211 (when (and (eq (car rr) 'not-in-file)
9212 (buffer-file-name))
9213 (not (string-match (cdr rr) (buffer-file-name))))
9214 (when (eq (car rr) 'not-in-mode)
9215 (not (string-match (cdr rr) (symbol-name major-mode))))
9216 (when (eq (car rr) 'not-in-buffer)
9217 (not (string-match (cdr rr) (buffer-name)))))))
9218 (push r res)))
9219 (car (last r))))
9220 (delete-dups (delq nil res))))
9222 (defun org-context-p (&rest contexts)
9223 "Check if local context is any of CONTEXTS.
9224 Possible values in the list of contexts are `table', `headline', and `item'."
9225 (let ((pos (point)))
9226 (goto-char (point-at-bol))
9227 (prog1 (or (and (memq 'table contexts)
9228 (looking-at "[ \t]*|"))
9229 (and (memq 'headline contexts)
9230 (looking-at org-outline-regexp))
9231 (and (memq 'item contexts)
9232 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9233 (and (memq 'item-body contexts)
9234 (org-in-item-p)))
9235 (goto-char pos))))
9237 (defun org-get-local-variables ()
9238 "Return a list of all local variables in an Org mode buffer."
9239 (let (varlist)
9240 (with-current-buffer (get-buffer-create "*Org tmp*")
9241 (erase-buffer)
9242 (org-mode)
9243 (setq varlist (buffer-local-variables)))
9244 (kill-buffer "*Org tmp*")
9245 (delq nil
9246 (mapcar
9247 (lambda (x)
9248 (setq x
9249 (if (symbolp x)
9250 (list x)
9251 (list (car x) (cdr x))))
9252 (if (and (not (get (car x) 'org-state))
9253 (string-match
9254 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9255 (symbol-name (car x))))
9256 x nil))
9257 varlist))))
9259 (defun org-clone-local-variables (from-buffer &optional regexp)
9260 "Clone local variables from FROM-BUFFER.
9261 Optional argument REGEXP selects variables to clone."
9262 (mapc
9263 (lambda (pair)
9264 (and (symbolp (car pair))
9265 (or (null regexp)
9266 (string-match regexp (symbol-name (car pair))))
9267 (set (make-local-variable (car pair))
9268 (cdr pair))))
9269 (buffer-local-variables from-buffer)))
9271 ;;;###autoload
9272 (defun org-run-like-in-org-mode (cmd)
9273 "Run a command, pretending that the current buffer is in Org-mode.
9274 This will temporarily bind local variables that are typically bound in
9275 Org-mode to the values they have in Org-mode, and then interactively
9276 call CMD."
9277 (org-load-modules-maybe)
9278 (unless org-local-vars
9279 (setq org-local-vars (org-get-local-variables)))
9280 (let (binds)
9281 (dolist (var org-local-vars)
9282 (when (or (not (boundp (car var)))
9283 (eq (symbol-value (car var))
9284 (default-value (car var))))
9285 (push (list (car var) `(quote ,(cadr var))) binds)))
9286 (eval `(let ,binds
9287 (call-interactively (quote ,cmd))))))
9289 ;;;; Archiving
9291 (defun org-get-category (&optional pos force-refresh)
9292 "Get the category applying to position POS."
9293 (save-match-data
9294 (if force-refresh (org-refresh-category-properties))
9295 (let ((pos (or pos (point))))
9296 (or (get-text-property pos 'org-category)
9297 (progn (org-refresh-category-properties)
9298 (get-text-property pos 'org-category))))))
9300 (defun org-refresh-category-properties ()
9301 "Refresh category text properties in the buffer."
9302 (let ((case-fold-search t)
9303 (inhibit-read-only t)
9304 (def-cat (cond
9305 ((null org-category)
9306 (if buffer-file-name
9307 (file-name-sans-extension
9308 (file-name-nondirectory buffer-file-name))
9309 "???"))
9310 ((symbolp org-category) (symbol-name org-category))
9311 (t org-category)))
9312 beg end cat pos optionp)
9313 (org-with-silent-modifications
9314 (save-excursion
9315 (save-restriction
9316 (widen)
9317 (goto-char (point-min))
9318 (put-text-property (point) (point-max) 'org-category def-cat)
9319 (while (re-search-forward
9320 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9321 (setq pos (match-end 0)
9322 optionp (equal (char-after (match-beginning 0)) ?#)
9323 cat (org-trim (match-string 2)))
9324 (if optionp
9325 (setq beg (point-at-bol) end (point-max))
9326 (org-back-to-heading t)
9327 (setq beg (point) end (org-end-of-subtree t t)))
9328 (put-text-property beg end 'org-category cat)
9329 (put-text-property beg end 'org-category-position beg)
9330 (goto-char pos)))))))
9332 (defun org-refresh-properties (dprop tprop)
9333 "Refresh buffer text properties.
9334 DPROP is the drawer property and TPROP is the corresponding text
9335 property to set."
9336 (let ((case-fold-search t)
9337 (inhibit-read-only t) p)
9338 (org-with-silent-modifications
9339 (save-excursion
9340 (save-restriction
9341 (widen)
9342 (goto-char (point-min))
9343 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9344 (setq p (org-match-string-no-properties 1))
9345 (save-excursion
9346 (org-back-to-heading t)
9347 (put-text-property
9348 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9351 ;;;; Link Stuff
9353 ;;; Link abbreviations
9355 (defun org-link-expand-abbrev (link)
9356 "Apply replacements as defined in `org-link-abbrev-alist'."
9357 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9358 (let* ((key (match-string 1 link))
9359 (as (or (assoc key org-link-abbrev-alist-local)
9360 (assoc key org-link-abbrev-alist)))
9361 (tag (and (match-end 2) (match-string 3 link)))
9362 rpl)
9363 (if (not as)
9364 link
9365 (setq rpl (cdr as))
9366 (cond
9367 ((symbolp rpl) (funcall rpl tag))
9368 ((string-match "%(\\([^)]+\\))" rpl)
9369 (replace-match
9370 (save-match-data
9371 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9372 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9373 ((string-match "%h" rpl)
9374 (replace-match (url-hexify-string (or tag "")) t t rpl))
9375 (t (concat rpl tag)))))
9376 link))
9378 ;;; Storing and inserting links
9380 (defvar org-insert-link-history nil
9381 "Minibuffer history for links inserted with `org-insert-link'.")
9383 (defvar org-stored-links nil
9384 "Contains the links stored with `org-store-link'.")
9386 (defvar org-store-link-plist nil
9387 "Plist with info about the most recently link created with `org-store-link'.")
9389 (defvar org-link-protocols nil
9390 "Link protocols added to Org-mode using `org-add-link-type'.")
9392 (defvar org-store-link-functions nil
9393 "List of functions that are called to create and store a link.
9394 Each function will be called in turn until one returns a non-nil
9395 value. Each function should check if it is responsible for creating
9396 this link (for example by looking at the major mode).
9397 If not, it must exit and return nil.
9398 If yes, it should return a non-nil value after a calling
9399 `org-store-link-props' with a list of properties and values.
9400 Special properties are:
9402 :type The link prefix, like \"http\". This must be given.
9403 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9404 This is obligatory as well.
9405 :description Optional default description for the second pair
9406 of brackets in an Org-mode link. The user can still change
9407 this when inserting this link into an Org-mode buffer.
9409 In addition to these, any additional properties can be specified
9410 and then used in capture templates.")
9412 (defun org-add-link-type (type &optional follow export)
9413 "Add TYPE to the list of `org-link-types'.
9414 Re-compute all regular expressions depending on `org-link-types'
9416 FOLLOW and EXPORT are two functions.
9418 FOLLOW should take the link path as the single argument and do whatever
9419 is necessary to follow the link, for example find a file or display
9420 a mail message.
9422 EXPORT should format the link path for export to one of the export formats.
9423 It should be a function accepting three arguments:
9425 path the path of the link, the text after the prefix (like \"http:\")
9426 desc the description of the link, if any, or a description added by
9427 org-export-normalize-links if there is none
9428 format the export format, a symbol like `html' or `latex' or `ascii'..
9430 The function may use the FORMAT information to return different values
9431 depending on the format. The return value will be put literally into
9432 the exported file. If the return value is nil, this means Org should
9433 do what it normally does with links which do not have EXPORT defined.
9435 Org-mode has a built-in default for exporting links. If you are happy with
9436 this default, there is no need to define an export function for the link
9437 type. For a simple example of an export function, see `org-bbdb.el'."
9438 (add-to-list 'org-link-types type t)
9439 (org-make-link-regexps)
9440 (if (assoc type org-link-protocols)
9441 (setcdr (assoc type org-link-protocols) (list follow export))
9442 (push (list type follow export) org-link-protocols)))
9444 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9445 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9447 ;;;###autoload
9448 (defun org-store-link (arg)
9449 "\\<org-mode-map>Store an org-link to the current location.
9450 This link is added to `org-stored-links' and can later be inserted
9451 into an org-buffer with \\[org-insert-link].
9453 For some link types, a prefix arg is interpreted.
9454 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9455 For file links, arg negates `org-context-in-file-links'.
9457 A double prefix arg force skipping storing functions that are not
9458 part of Org's core.
9460 A triple prefix arg force storing a link for each line in the
9461 active region."
9462 (interactive "P")
9463 (org-load-modules-maybe)
9464 (if (and (equal arg '(64)) (org-region-active-p))
9465 (save-excursion
9466 (let ((end (region-end)))
9467 (goto-char (region-beginning))
9468 (set-mark (point))
9469 (while (< (point-at-eol) end)
9470 (move-end-of-line 1) (activate-mark)
9471 (let (current-prefix-arg)
9472 (call-interactively 'org-store-link))
9473 (move-beginning-of-line 2)
9474 (set-mark (point)))))
9475 (org-with-limited-levels
9476 (setq org-store-link-plist nil)
9477 (let (link cpltxt desc description search
9478 txt custom-id agenda-link sfuns sfunsn)
9479 (cond
9481 ;; Store a link using an external link type
9482 ((and (not (equal arg '(16)))
9483 (setq sfuns
9484 (delq
9485 nil (mapcar (lambda (f)
9486 (let (fs) (if (funcall f) (push f fs))))
9487 org-store-link-functions))
9488 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9489 (or (and (cdr sfuns)
9490 (funcall (intern
9491 (completing-read
9492 "Which function for creating the link? "
9493 sfunsn nil t (car sfunsn)))))
9494 (funcall (caar sfuns)))
9495 (setq link (plist-get org-store-link-plist :link)
9496 desc (or (plist-get org-store-link-plist
9497 :description) link))))
9499 ;; Store a link from a source code buffer
9500 ((org-src-edit-buffer-p)
9501 (let (label gc)
9502 (while (or (not label)
9503 (save-excursion
9504 (save-restriction
9505 (widen)
9506 (goto-char (point-min))
9507 (re-search-forward
9508 (regexp-quote (format org-coderef-label-format label))
9509 nil t))))
9510 (when label (message "Label exists already") (sit-for 2))
9511 (setq label (read-string "Code line label: " label)))
9512 (end-of-line 1)
9513 (setq link (format org-coderef-label-format label))
9514 (setq gc (- 79 (length link)))
9515 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9516 (insert link)
9517 (setq link (concat "(" label ")") desc nil)))
9519 ;; We are in the agenda, link to referenced location
9520 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9521 (let ((m (or (get-text-property (point) 'org-hd-marker)
9522 (get-text-property (point) 'org-marker))))
9523 (when m
9524 (org-with-point-at m
9525 (setq agenda-link
9526 (if (org-called-interactively-p 'any)
9527 (call-interactively 'org-store-link)
9528 (org-store-link nil)))))))
9530 ((eq major-mode 'calendar-mode)
9531 (let ((cd (calendar-cursor-to-date)))
9532 (setq link
9533 (format-time-string
9534 (car org-time-stamp-formats)
9535 (apply 'encode-time
9536 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9537 nil nil nil))))
9538 (org-store-link-props :type "calendar" :date cd)))
9540 ((eq major-mode 'help-mode)
9541 (setq link (concat "help:" (save-excursion
9542 (goto-char (point-min))
9543 (looking-at "^[^ ]+")
9544 (match-string 0))))
9545 (org-store-link-props :type "help"))
9547 ((eq major-mode 'w3-mode)
9548 (setq cpltxt (if (and (buffer-name)
9549 (not (string-match "Untitled" (buffer-name))))
9550 (buffer-name)
9551 (url-view-url t))
9552 link (url-view-url t))
9553 (org-store-link-props :type "w3" :url (url-view-url t)))
9555 ((eq major-mode 'image-mode)
9556 (setq cpltxt (concat "file:"
9557 (abbreviate-file-name buffer-file-name))
9558 link cpltxt)
9559 (org-store-link-props :type "image" :file buffer-file-name))
9561 ;; In dired, store a link to the file of the current line
9562 ((eq major-mode 'dired-mode)
9563 (let ((file (dired-get-filename nil t)))
9564 (setq file (if file
9565 (abbreviate-file-name
9566 (expand-file-name (dired-get-filename nil t)))
9567 ;; otherwise, no file so use current directory.
9568 default-directory))
9569 (setq cpltxt (concat "file:" file)
9570 link cpltxt)))
9572 ((setq search (run-hook-with-args-until-success
9573 'org-create-file-search-functions))
9574 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9575 "::" search))
9576 (setq cpltxt (or description link)))
9578 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9579 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9580 (cond
9581 ;; Store a link using the target at point
9582 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9583 (setq cpltxt
9584 (concat "file:"
9585 (abbreviate-file-name
9586 (buffer-file-name (buffer-base-buffer)))
9587 "::" (match-string 1))
9588 link cpltxt))
9589 ((and (featurep 'org-id)
9590 (or (eq org-id-link-to-org-use-id t)
9591 (and (org-called-interactively-p 'any)
9592 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9593 (and (eq org-id-link-to-org-use-id
9594 'create-if-interactive-and-no-custom-id)
9595 (not custom-id))))
9596 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9597 ;; Store a link using the ID at point
9598 (setq link (condition-case nil
9599 (prog1 (org-id-store-link)
9600 (setq desc (plist-get org-store-link-plist
9601 :description)))
9602 (error
9603 ;; Probably before first headline, link only to file
9604 (concat "file:"
9605 (abbreviate-file-name
9606 (buffer-file-name (buffer-base-buffer))))))))
9608 ;; Just link to current headline
9609 (setq cpltxt (concat "file:"
9610 (abbreviate-file-name
9611 (buffer-file-name (buffer-base-buffer)))))
9612 ;; Add a context search string
9613 (when (org-xor org-context-in-file-links arg)
9614 (let* ((ee (org-element-at-point))
9615 (et (org-element-type ee))
9616 (ev (plist-get (cadr ee) :value))
9617 (ek (plist-get (cadr ee) :key))
9618 (eok (and (stringp ek) (string-match "name" ek))))
9619 (setq txt (cond
9620 ((org-at-heading-p) nil)
9621 ((and (eq et 'keyword) eok) ev)
9622 ((org-region-active-p)
9623 (buffer-substring (region-beginning) (region-end)))))
9624 (when (or (null txt) (string-match "\\S-" txt))
9625 (setq cpltxt
9626 (concat cpltxt "::"
9627 (condition-case nil
9628 (org-make-org-heading-search-string txt)
9629 (error "")))
9630 desc (or (and (eq et 'keyword) eok ev)
9631 (nth 4 (ignore-errors (org-heading-components)))
9632 "NONE")))))
9633 (if (string-match "::\\'" cpltxt)
9634 (setq cpltxt (substring cpltxt 0 -2)))
9635 (setq link cpltxt))))
9637 ((buffer-file-name (buffer-base-buffer))
9638 ;; Just link to this file here.
9639 (setq cpltxt (concat "file:"
9640 (abbreviate-file-name
9641 (buffer-file-name (buffer-base-buffer)))))
9642 ;; Add a context string.
9643 (when (org-xor org-context-in-file-links arg)
9644 (setq txt (if (org-region-active-p)
9645 (buffer-substring (region-beginning) (region-end))
9646 (buffer-substring (point-at-bol) (point-at-eol))))
9647 ;; Only use search option if there is some text.
9648 (when (string-match "\\S-" txt)
9649 (setq cpltxt
9650 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9651 desc "NONE")))
9652 (setq link cpltxt))
9654 ((org-called-interactively-p 'interactive)
9655 (user-error "No method for storing a link from this buffer"))
9657 (t (setq link nil)))
9659 ;; We're done setting link and desc, clean up
9660 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9661 (setq link (or link cpltxt)
9662 desc (or desc cpltxt))
9663 (cond ((equal desc "NONE") (setq desc nil))
9664 ((string-match org-bracket-link-analytic-regexp desc)
9665 (let ((d0 (match-string 3 desc))
9666 (p0 (match-string 5 desc)))
9667 (setq desc
9668 (replace-regexp-in-string
9669 org-bracket-link-regexp
9670 (concat (or p0 d0)
9671 (if (equal (length (match-string 0 desc))
9672 (length desc)) "*" "")) desc)))))
9674 ;; Return the link
9675 (if (not (and (or (org-called-interactively-p 'any)
9676 executing-kbd-macro) link))
9677 (or agenda-link (and link (org-make-link-string link desc)))
9678 (push (list link desc) org-stored-links)
9679 (message "Stored: %s" (or desc link))
9680 (when custom-id
9681 (setq link (concat "file:" (abbreviate-file-name
9682 (buffer-file-name)) "::#" custom-id))
9683 (push (list link desc) org-stored-links))
9684 (car org-stored-links))))))
9686 (defun org-store-link-props (&rest plist)
9687 "Store link properties, extract names and addresses."
9688 (let (x adr)
9689 (when (setq x (plist-get plist :from))
9690 (setq adr (mail-extract-address-components x))
9691 (setq plist (plist-put plist :fromname (car adr)))
9692 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9693 (when (setq x (plist-get plist :to))
9694 (setq adr (mail-extract-address-components x))
9695 (setq plist (plist-put plist :toname (car adr)))
9696 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9697 (let ((from (plist-get plist :from))
9698 (to (plist-get plist :to)))
9699 (when (and from to org-from-is-user-regexp)
9700 (setq plist
9701 (plist-put plist :fromto
9702 (if (string-match org-from-is-user-regexp from)
9703 (concat "to %t")
9704 (concat "from %f"))))))
9705 (setq org-store-link-plist plist))
9707 (defun org-add-link-props (&rest plist)
9708 "Add these properties to the link property list."
9709 (let (key value)
9710 (while plist
9711 (setq key (pop plist) value (pop plist))
9712 (setq org-store-link-plist
9713 (plist-put org-store-link-plist key value)))))
9715 (defun org-email-link-description (&optional fmt)
9716 "Return the description part of an email link.
9717 This takes information from `org-store-link-plist' and formats it
9718 according to FMT (default from `org-email-link-description-format')."
9719 (setq fmt (or fmt org-email-link-description-format))
9720 (let* ((p org-store-link-plist)
9721 (to (plist-get p :toaddress))
9722 (from (plist-get p :fromaddress))
9723 (table
9724 (list
9725 (cons "%c" (plist-get p :fromto))
9726 (cons "%F" (plist-get p :from))
9727 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9728 (cons "%T" (plist-get p :to))
9729 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9730 (cons "%s" (plist-get p :subject))
9731 (cons "%d" (plist-get p :date))
9732 (cons "%m" (plist-get p :message-id)))))
9733 (when (string-match "%c" fmt)
9734 ;; Check if the user wrote this message
9735 (if (and org-from-is-user-regexp from to
9736 (save-match-data (string-match org-from-is-user-regexp from)))
9737 (setq fmt (replace-match "to %t" t t fmt))
9738 (setq fmt (replace-match "from %f" t t fmt))))
9739 (org-replace-escapes fmt table)))
9741 (defun org-make-org-heading-search-string (&optional string)
9742 "Make search string for the current headline or STRING."
9743 (let ((s (or string
9744 (and (derived-mode-p 'org-mode)
9745 (save-excursion
9746 (org-back-to-heading t)
9747 (org-element-property :raw-value (org-element-at-point))))))
9748 (lines org-context-in-file-links))
9749 (or string (setq s (concat "*" s))) ; Add * for headlines
9750 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9751 (when (and string (integerp lines) (> lines 0))
9752 (let ((slines (org-split-string s "\n")))
9753 (when (< lines (length slines))
9754 (setq s (mapconcat
9755 'identity
9756 (reverse (nthcdr (- (length slines) lines)
9757 (reverse slines))) "\n")))))
9758 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9760 (defun org-make-link-string (link &optional description)
9761 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9762 (unless (string-match "\\S-" link)
9763 (error "Empty link"))
9764 (when (and description
9765 (stringp description)
9766 (not (string-match "\\S-" description)))
9767 (setq description nil))
9768 (when (stringp description)
9769 ;; Remove brackets from the description, they are fatal.
9770 (while (string-match "\\[" description)
9771 (setq description (replace-match "{" t t description)))
9772 (while (string-match "\\]" description)
9773 (setq description (replace-match "}" t t description))))
9774 (when (equal link description)
9775 ;; No description needed, it is identical
9776 (setq description nil))
9777 (when (and (not description)
9778 (not (string-match (org-image-file-name-regexp) link))
9779 (not (equal link (org-link-escape link))))
9780 (setq description (org-extract-attributes link)))
9781 (setq link
9782 (cond ((string-match (org-image-file-name-regexp) link) link)
9783 ((string-match org-link-types-re link)
9784 (concat (match-string 1 link)
9785 (org-link-escape (substring link (match-end 1)))))
9786 (t (org-link-escape link))))
9787 (concat "[[" link "]"
9788 (if description (concat "[" description "]") "")
9789 "]"))
9791 (defconst org-link-escape-chars
9792 ;;%20 %2B %3B %3D %5B %5D
9793 '(?\ ?\+ ?\; ?\= ?\[ ?\])
9794 "List of characters that should be escaped in link.
9795 This is the list that is used for internal purposes.")
9797 (defconst org-link-escape-chars-browser
9798 ;;%20 %22
9799 '(?\ ?\")
9800 "List of escapes for characters that are problematic in links.
9801 This is the list that is used before handing over to the browser.")
9803 (defun org-link-escape (text &optional table merge)
9804 "Return percent escaped representation of TEXT.
9805 TEXT is a string with the text to escape.
9806 Optional argument TABLE is a list with characters that should be
9807 escaped. When nil, `org-link-escape-chars' is used.
9808 If optional argument MERGE is set, merge TABLE into
9809 `org-link-escape-chars'."
9810 (cond
9811 ((and table merge)
9812 (mapc (lambda (defchr)
9813 (unless (member defchr table)
9814 (setq table (cons defchr table)))) org-link-escape-chars))
9815 ((null table)
9816 (setq table org-link-escape-chars)))
9817 (mapconcat
9818 (lambda (char)
9819 (if (or (member char table)
9820 (and (or (< char 32) (= char ?\%) (> char 126))
9821 org-url-hexify-p))
9822 (mapconcat (lambda (sequence-element)
9823 (format "%%%.2X" sequence-element))
9824 (or (encode-coding-char char 'utf-8)
9825 (error "Unable to percent escape character: %s"
9826 (char-to-string char))) "")
9827 (char-to-string char))) text ""))
9829 (defun org-link-escape-browser (text)
9830 (if (org-string-match-p
9831 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
9832 text)
9833 (org-link-escape text org-link-escape-chars-browser)
9834 text))
9836 (defun org-link-unescape (str)
9837 "Unhex hexified Unicode strings as returned from the JavaScript function
9838 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9839 (unless (and (null str) (string= "" str))
9840 (let ((pos 0) (case-fold-search t) unhexed)
9841 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9842 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9843 (setq str (replace-match unhexed t t str))
9844 (setq pos (+ pos (length unhexed))))))
9845 str)
9847 (defun org-link-unescape-compound (hex)
9848 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9849 Note: this function also decodes single byte encodings like
9850 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9851 (save-match-data
9852 (let* ((bytes (cdr (split-string hex "%")))
9853 (ret "")
9854 (eat 0)
9855 (sum 0))
9856 (while bytes
9857 (let* ((val (string-to-number (pop bytes) 16))
9858 (shift-xor
9859 (if (= 0 eat)
9860 (cond
9861 ((>= val 252) (cons 6 252))
9862 ((>= val 248) (cons 5 248))
9863 ((>= val 240) (cons 4 240))
9864 ((>= val 224) (cons 3 224))
9865 ((>= val 192) (cons 2 192))
9866 (t (cons 0 0)))
9867 (cons 6 128))))
9868 (if (>= val 192) (setq eat (car shift-xor)))
9869 (setq val (logxor val (cdr shift-xor)))
9870 (setq sum (+ (lsh sum (car shift-xor)) val))
9871 (if (> eat 0) (setq eat (- eat 1)))
9872 (cond
9873 ((= 0 eat) ;multi byte
9874 (setq ret (concat ret (org-char-to-string sum)))
9875 (setq sum 0))
9876 ((not bytes) ; single byte(s)
9877 (setq ret (org-link-unescape-single-byte-sequence hex))))
9878 )) ;; end (while bytes
9879 ret )))
9881 (defun org-link-unescape-single-byte-sequence (hex)
9882 "Unhexify hex-encoded single byte character sequences."
9883 (mapconcat (lambda (byte)
9884 (char-to-string (string-to-number byte 16)))
9885 (cdr (split-string hex "%")) ""))
9887 (defun org-xor (a b)
9888 "Exclusive or."
9889 (if a (not b) b))
9891 (defun org-fixup-message-id-for-http (s)
9892 "Replace special characters in a message id, so it can be used in an http query."
9893 (when (string-match "%" s)
9894 (setq s (mapconcat (lambda (c)
9895 (if (eq c ?%)
9896 "%25"
9897 (char-to-string c)))
9898 s "")))
9899 (while (string-match "<" s)
9900 (setq s (replace-match "%3C" t t s)))
9901 (while (string-match ">" s)
9902 (setq s (replace-match "%3E" t t s)))
9903 (while (string-match "@" s)
9904 (setq s (replace-match "%40" t t s)))
9907 (defun org-link-prettify (link)
9908 "Return a human-readable representation of LINK.
9909 The car of LINK must be a raw link the cdr of LINK must be either
9910 a link description or nil."
9911 (let ((desc (or (cadr link) "<no description>")))
9912 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9913 "<" (car link) ">")))
9915 ;;;###autoload
9916 (defun org-insert-link-global ()
9917 "Insert a link like Org-mode does.
9918 This command can be called in any mode to insert a link in Org-mode syntax."
9919 (interactive)
9920 (org-load-modules-maybe)
9921 (org-run-like-in-org-mode 'org-insert-link))
9923 (defun org-insert-all-links (arg &optional pre post)
9924 "Insert all links in `org-stored-links'.
9925 When a universal prefix, do not delete the links from `org-stored-links'.
9926 When `ARG' is a number, insert the last N link(s).
9927 `PRE' and `POST' are optional arguments to define a string to
9928 prepend or to append."
9929 (interactive "P")
9930 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9931 (links (copy-seq org-stored-links))
9932 (pr (or pre "- "))
9933 (po (or post "\n"))
9934 (cnt 1) l)
9935 (if (null org-stored-links)
9936 (message "No link to insert")
9937 (while (and (or (listp arg) (>= arg cnt))
9938 (setq l (if (listp arg)
9939 (pop links)
9940 (pop org-stored-links))))
9941 (setq cnt (1+ cnt))
9942 (insert pr)
9943 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9944 (insert po)))))
9946 (defun org-insert-last-stored-link (arg)
9947 "Insert the last link stored in `org-stored-links'."
9948 (interactive "p")
9949 (org-insert-all-links arg "" "\n"))
9951 (defun org-link-fontify-links-to-this-file ()
9952 "Fontify links to the current file in `org-stored-links'."
9953 (let ((f (buffer-file-name)) a b)
9954 (setq a (mapcar (lambda(l)
9955 (let ((ll (car l)))
9956 (when (and (string-match "^file:\\(.+\\)::" ll)
9957 (equal f (expand-file-name (match-string 1 ll))))
9958 ll)))
9959 org-stored-links))
9960 (when (featurep 'org-id)
9961 (setq b (mapcar (lambda(l)
9962 (let ((ll (car l)))
9963 (when (and (string-match "^id:\\(.+\\)$" ll)
9964 (equal f (expand-file-name
9965 (or (org-id-find-id-file
9966 (match-string 1 ll)) ""))))
9967 ll)))
9968 org-stored-links)))
9969 (mapcar (lambda(l)
9970 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9971 (delq nil (append a b)))))
9973 (defvar org-link-links-in-this-file nil)
9974 (defun org-insert-link (&optional complete-file link-location default-description)
9975 "Insert a link. At the prompt, enter the link.
9977 Completion can be used to insert any of the link protocol prefixes like
9978 http or ftp in use.
9980 The history can be used to select a link previously stored with
9981 `org-store-link'. When the empty string is entered (i.e. if you just
9982 press RET at the prompt), the link defaults to the most recently
9983 stored link. As SPC triggers completion in the minibuffer, you need to
9984 use M-SPC or C-q SPC to force the insertion of a space character.
9986 You will also be prompted for a description, and if one is given, it will
9987 be displayed in the buffer instead of the link.
9989 If there is already a link at point, this command will allow you to edit link
9990 and description parts.
9992 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9993 be selected using completion. The path to the file will be relative to the
9994 current directory if the file is in the current directory or a subdirectory.
9995 Otherwise, the link will be the absolute path as completed in the minibuffer
9996 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9997 option `org-link-file-path-type'.
9999 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10000 the current directory or below.
10002 With three \\[universal-argument] prefixes, negate the meaning of
10003 `org-keep-stored-link-after-insertion'.
10005 If `org-make-link-description-function' is non-nil, this function will be
10006 called with the link target, and the result will be the default
10007 link description.
10009 If the LINK-LOCATION parameter is non-nil, this value will be
10010 used as the link location instead of reading one interactively.
10012 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10013 be used as the default description."
10014 (interactive "P")
10015 (let* ((wcf (current-window-configuration))
10016 (origbuf (current-buffer))
10017 (region (if (org-region-active-p)
10018 (buffer-substring (region-beginning) (region-end))))
10019 (remove (and region (list (region-beginning) (region-end))))
10020 (desc region)
10021 tmphist ; byte-compile incorrectly complains about this
10022 (link link-location)
10023 (abbrevs org-link-abbrev-alist-local)
10024 entry file all-prefixes auto-desc)
10025 (cond
10026 (link-location) ; specified by arg, just use it.
10027 ((org-in-regexp org-bracket-link-regexp 1)
10028 ;; We do have a link at point, and we are going to edit it.
10029 (setq remove (list (match-beginning 0) (match-end 0)))
10030 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10031 (setq link (read-string "Link: "
10032 (org-link-unescape
10033 (org-match-string-no-properties 1)))))
10034 ((or (org-in-regexp org-angle-link-re)
10035 (org-in-regexp org-plain-link-re))
10036 ;; Convert to bracket link
10037 (setq remove (list (match-beginning 0) (match-end 0))
10038 link (read-string "Link: "
10039 (org-remove-angle-brackets (match-string 0)))))
10040 ((member complete-file '((4) (16)))
10041 ;; Completing read for file names.
10042 (setq link (org-file-complete-link complete-file)))
10044 ;; Read link, with completion for stored links.
10045 (org-link-fontify-links-to-this-file)
10046 (org-switch-to-buffer-other-window "*Org Links*")
10047 (with-current-buffer "*Org Links*"
10048 (erase-buffer)
10049 (insert "Insert a link.
10050 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10051 (when org-stored-links
10052 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10053 (insert (mapconcat 'org-link-prettify
10054 (reverse org-stored-links) "\n")))
10055 (goto-char (point-min)))
10056 (let ((cw (selected-window)))
10057 (select-window (get-buffer-window "*Org Links*" 'visible))
10058 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10059 (unless (pos-visible-in-window-p (point-max))
10060 (org-fit-window-to-buffer))
10061 (and (window-live-p cw) (select-window cw)))
10062 ;; Fake a link history, containing the stored links.
10063 (setq tmphist (append (mapcar 'car org-stored-links)
10064 org-insert-link-history))
10065 (setq all-prefixes (append (mapcar 'car abbrevs)
10066 (mapcar 'car org-link-abbrev-alist)
10067 org-link-types))
10068 (unwind-protect
10069 (progn
10070 (setq link
10071 (org-completing-read
10072 "Link: "
10073 (append
10074 (mapcar (lambda (x) (concat x ":"))
10075 all-prefixes)
10076 (mapcar 'car org-stored-links))
10077 nil nil nil
10078 'tmphist
10079 (caar org-stored-links)))
10080 (if (not (string-match "\\S-" link))
10081 (user-error "No link selected"))
10082 (mapc (lambda(l)
10083 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10084 org-stored-links)
10085 (if (or (member link all-prefixes)
10086 (and (equal ":" (substring link -1))
10087 (member (substring link 0 -1) all-prefixes)
10088 (setq link (substring link 0 -1))))
10089 (setq link (with-current-buffer origbuf
10090 (org-link-try-special-completion link)))))
10091 (set-window-configuration wcf)
10092 (kill-buffer "*Org Links*"))
10093 (setq entry (assoc link org-stored-links))
10094 (or entry (push link org-insert-link-history))
10095 (setq desc (or desc (nth 1 entry)))))
10097 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10098 (not org-keep-stored-link-after-insertion))
10099 (setq org-stored-links (delq (assoc link org-stored-links)
10100 org-stored-links)))
10102 (if (and (string-match org-plain-link-re link)
10103 (not (string-match org-ts-regexp link)))
10104 ;; URL-like link, normalize the use of angular brackets.
10105 (setq link (org-remove-angle-brackets link)))
10107 ;; Check if we are linking to the current file with a search
10108 ;; option If yes, simplify the link by using only the search
10109 ;; option.
10110 (when (and buffer-file-name
10111 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10112 (let* ((path (match-string 1 link))
10113 (case-fold-search nil)
10114 (search (match-string 2 link)))
10115 (save-match-data
10116 (if (equal (file-truename buffer-file-name) (file-truename path))
10117 ;; We are linking to this same file, with a search option
10118 (setq link search)))))
10120 ;; Check if we can/should use a relative path. If yes, simplify the link
10121 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10122 (let* ((type (match-string 1 link))
10123 (path (match-string 2 link))
10124 (origpath path)
10125 (case-fold-search nil))
10126 (cond
10127 ((or (eq org-link-file-path-type 'absolute)
10128 (equal complete-file '(16)))
10129 (setq path (abbreviate-file-name (expand-file-name path))))
10130 ((eq org-link-file-path-type 'noabbrev)
10131 (setq path (expand-file-name path)))
10132 ((eq org-link-file-path-type 'relative)
10133 (setq path (file-relative-name path)))
10135 (save-match-data
10136 (if (string-match (concat "^" (regexp-quote
10137 (expand-file-name
10138 (file-name-as-directory
10139 default-directory))))
10140 (expand-file-name path))
10141 ;; We are linking a file with relative path name.
10142 (setq path (substring (expand-file-name path)
10143 (match-end 0)))
10144 (setq path (abbreviate-file-name (expand-file-name path)))))))
10145 (setq link (concat type path))
10146 (if (equal desc origpath)
10147 (setq desc path))))
10149 (if org-make-link-description-function
10150 (setq desc
10151 (or (condition-case nil
10152 (funcall org-make-link-description-function link desc)
10153 (error (progn (message "Can't get link description from `%s'"
10154 (symbol-name org-make-link-description-function))
10155 (sit-for 2) nil)))
10156 (read-string "Description: " default-description)))
10157 (if default-description (setq desc default-description)
10158 (setq desc (or (and auto-desc desc)
10159 (read-string "Description: " desc)))))
10161 (unless (string-match "\\S-" desc) (setq desc nil))
10162 (if remove (apply 'delete-region remove))
10163 (insert (org-make-link-string link desc))))
10165 (defun org-link-try-special-completion (type)
10166 "If there is completion support for link type TYPE, offer it."
10167 (let ((fun (intern (concat "org-" type "-complete-link"))))
10168 (if (functionp fun)
10169 (funcall fun)
10170 (read-string "Link (no completion support): " (concat type ":")))))
10172 (defun org-file-complete-link (&optional arg)
10173 "Create a file link using completion."
10174 (let (file link)
10175 (setq file (org-iread-file-name "File: "))
10176 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10177 (pwd1 (file-name-as-directory (abbreviate-file-name
10178 (expand-file-name ".")))))
10179 (cond
10180 ((equal arg '(16))
10181 (setq link (concat
10182 "file:"
10183 (abbreviate-file-name (expand-file-name file)))))
10184 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10185 (setq link (concat "file:" (match-string 1 file))))
10186 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10187 (expand-file-name file))
10188 (setq link (concat
10189 "file:" (match-string 1 (expand-file-name file)))))
10190 (t (setq link (concat "file:" file)))))
10191 link))
10193 (defun org-iread-file-name (&rest args)
10194 "Read-file-name using `ido-mode' speedup if available.
10195 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10196 See `read-file-name' for a description of parameters."
10197 (org-without-partial-completion
10198 (if (and org-completion-use-ido
10199 (fboundp 'ido-read-file-name)
10200 (boundp 'ido-mode) ido-mode
10201 (listp (second args)))
10202 (let ((ido-enter-matching-directory nil))
10203 (apply 'ido-read-file-name args))
10204 (apply 'read-file-name args))))
10206 (defun org-completing-read (&rest args)
10207 "Completing-read with SPACE being a normal character."
10208 (let ((enable-recursive-minibuffers t)
10209 (minibuffer-local-completion-map
10210 (copy-keymap minibuffer-local-completion-map)))
10211 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10212 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10213 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10214 (apply 'org-icompleting-read args)))
10216 (defun org-completing-read-no-i (&rest args)
10217 (let (org-completion-use-ido org-completion-use-iswitchb)
10218 (apply 'org-completing-read args)))
10220 (defun org-iswitchb-completing-read (prompt choices &rest args)
10221 "Use iswitch as a completing-read replacement to choose from choices.
10222 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10223 from."
10224 (let* ((iswitchb-use-virtual-buffers nil)
10225 (iswitchb-make-buflist-hook
10226 (lambda ()
10227 (setq iswitchb-temp-buflist choices))))
10228 (iswitchb-read-buffer prompt)))
10230 (defun org-icompleting-read (&rest args)
10231 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10232 (org-without-partial-completion
10233 (if (and org-completion-use-ido
10234 (fboundp 'ido-completing-read)
10235 (boundp 'ido-mode) ido-mode
10236 (listp (second args)))
10237 (let ((ido-enter-matching-directory nil))
10238 (apply 'ido-completing-read (concat (car args))
10239 (if (consp (car (nth 1 args)))
10240 (mapcar 'car (nth 1 args))
10241 (nth 1 args))
10242 (cddr args)))
10243 (if (and org-completion-use-iswitchb
10244 (boundp 'iswitchb-mode) iswitchb-mode
10245 (listp (second args)))
10246 (apply 'org-iswitchb-completing-read (concat (car args))
10247 (if (consp (car (nth 1 args)))
10248 (mapcar 'car (nth 1 args))
10249 (nth 1 args))
10250 (cddr args))
10251 (apply 'completing-read args)))))
10253 (defun org-extract-attributes (s)
10254 "Extract the attributes cookie from a string and set as text property."
10255 (let (a attr (start 0) key value)
10256 (save-match-data
10257 (when (string-match "{{\\([^}]+\\)}}$" s)
10258 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10259 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10260 (setq key (match-string 1 a) value (match-string 2 a)
10261 start (match-end 0)
10262 attr (plist-put attr (intern key) value))))
10263 (org-add-props s nil 'org-attr attr))
10266 ;;; Opening/following a link
10268 (defvar org-link-search-failed nil)
10270 (defvar org-open-link-functions nil
10271 "Hook for functions finding a plain text link.
10272 These functions must take a single argument, the link content.
10273 They will be called for links that look like [[link text][description]]
10274 when LINK TEXT does not have a protocol like \"http:\" and does not look
10275 like a filename (e.g. \"./blue.png\").
10277 These functions will be called *before* Org attempts to resolve the
10278 link by doing text searches in the current buffer - so if you want a
10279 link \"[[target]]\" to still find \"<<target>>\", your function should
10280 handle this as a special case.
10282 When the function does handle the link, it must return a non-nil value.
10283 If it decides that it is not responsible for this link, it must return
10284 nil to indicate that that Org-mode can continue with other options
10285 like exact and fuzzy text search.")
10287 (defun org-next-link (&optional search-backward)
10288 "Move forward to the next link.
10289 If the link is in hidden text, expose it."
10290 (interactive "P")
10291 (when (and org-link-search-failed (eq this-command last-command))
10292 (goto-char (point-min))
10293 (message "Link search wrapped back to beginning of buffer"))
10294 (setq org-link-search-failed nil)
10295 (let* ((pos (point))
10296 (ct (org-context))
10297 (a (assoc :link ct))
10298 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10299 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10300 ((looking-at org-any-link-re)
10301 ;; Don't stay stuck at link without an org-link face
10302 (forward-char (if search-backward -1 1))))
10303 (if (funcall srch-fun org-any-link-re nil t)
10304 (progn
10305 (goto-char (match-beginning 0))
10306 (if (outline-invisible-p) (org-show-context)))
10307 (goto-char pos)
10308 (setq org-link-search-failed t)
10309 (message "No further link found"))))
10311 (defun org-previous-link ()
10312 "Move backward to the previous link.
10313 If the link is in hidden text, expose it."
10314 (interactive)
10315 (funcall 'org-next-link t))
10317 (defun org-translate-link (s)
10318 "Translate a link string if a translation function has been defined."
10319 (if (and org-link-translation-function
10320 (fboundp org-link-translation-function)
10321 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10322 (progn
10323 (setq s (funcall org-link-translation-function
10324 (match-string 1 s) (match-string 2 s)))
10325 (concat (car s) ":" (cdr s)))
10328 (defun org-translate-link-from-planner (type path)
10329 "Translate a link from Emacs Planner syntax so that Org can follow it.
10330 This is still an experimental function, your mileage may vary."
10331 (cond
10332 ((member type '("http" "https" "news" "ftp"))
10333 ;; standard Internet links are the same.
10334 nil)
10335 ((and (equal type "irc") (string-match "^//" path))
10336 ;; Planner has two / at the beginning of an irc link, we have 1.
10337 ;; We should have zero, actually....
10338 (setq path (substring path 1)))
10339 ((and (equal type "lisp") (string-match "^/" path))
10340 ;; Planner has a slash, we do not.
10341 (setq type "elisp" path (substring path 1)))
10342 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10343 ;; A typical message link. Planner has the id after the final slash,
10344 ;; we separate it with a hash mark
10345 (setq path (concat (match-string 1 path) "#"
10346 (org-remove-angle-brackets (match-string 2 path))))))
10347 (cons type path))
10349 (defun org-find-file-at-mouse (ev)
10350 "Open file link or URL at mouse."
10351 (interactive "e")
10352 (mouse-set-point ev)
10353 (org-open-at-point 'in-emacs))
10355 (defun org-open-at-mouse (ev)
10356 "Open file link or URL at mouse.
10357 See the docstring of `org-open-file' for details."
10358 (interactive "e")
10359 (mouse-set-point ev)
10360 (if (eq major-mode 'org-agenda-mode)
10361 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10362 (org-open-at-point))
10364 (defvar org-window-config-before-follow-link nil
10365 "The window configuration before following a link.
10366 This is saved in case the need arises to restore it.")
10368 (defvar org-open-link-marker (make-marker)
10369 "Marker pointing to the location where `org-open-at-point; was called.")
10371 ;;;###autoload
10372 (defun org-open-at-point-global ()
10373 "Follow a link like Org-mode does.
10374 This command can be called in any mode to follow a link that has
10375 Org-mode syntax."
10376 (interactive)
10377 (org-run-like-in-org-mode 'org-open-at-point))
10379 ;;;###autoload
10380 (defun org-open-link-from-string (s &optional arg reference-buffer)
10381 "Open a link in the string S, as if it was in Org-mode."
10382 (interactive "sLink: \nP")
10383 (let ((reference-buffer (or reference-buffer (current-buffer))))
10384 (with-temp-buffer
10385 (let ((org-inhibit-startup (not reference-buffer)))
10386 (org-mode)
10387 (insert s)
10388 (goto-char (point-min))
10389 (when reference-buffer
10390 (setq org-link-abbrev-alist-local
10391 (with-current-buffer reference-buffer
10392 org-link-abbrev-alist-local)))
10393 (org-open-at-point arg reference-buffer)))))
10395 (defvar org-open-at-point-functions nil
10396 "Hook that is run when following a link at point.
10398 Functions in this hook must return t if they identify and follow
10399 a link at point. If they don't find anything interesting at point,
10400 they must return nil.")
10402 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10403 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10404 (defun org-open-at-point (&optional arg reference-buffer)
10405 "Open link at or after point.
10406 If there is no link at point, this function will search forward up to
10407 the end of the current line.
10408 Normally, files will be opened by an appropriate application. If the
10409 optional prefix argument ARG is non-nil, Emacs will visit the file.
10410 With a double prefix argument, try to open outside of Emacs, in the
10411 application the system uses for this file type."
10412 (interactive "P")
10413 ;; if in a code block, then open the block's results
10414 (unless (call-interactively #'org-babel-open-src-block-result)
10415 (org-load-modules-maybe)
10416 (move-marker org-open-link-marker (point))
10417 (setq org-window-config-before-follow-link (current-window-configuration))
10418 (org-remove-occur-highlights nil nil t)
10419 (cond
10420 ((and (org-at-heading-p)
10421 (not (org-at-timestamp-p t))
10422 (not (org-in-regexp
10423 (concat org-plain-link-re "\\|"
10424 org-bracket-link-regexp "\\|"
10425 org-angle-link-re "\\|"
10426 "[ \t]:[^ \t\n]+:[ \t]*$")))
10427 (not (get-text-property (point) 'org-linked-text)))
10428 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10429 (lk0 (car lkall))
10430 (lk (if (stringp lk0) (list lk0) lk0))
10431 (lkend (cdr lkall)))
10432 (mapcar (lambda(l)
10433 (search-forward l nil lkend)
10434 (goto-char (match-beginning 0))
10435 (org-open-at-point))
10436 lk))
10437 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10438 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10439 ((and (org-at-timestamp-p t)
10440 (not (org-in-regexp org-bracket-link-regexp)))
10441 (org-follow-timestamp-link))
10442 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10443 (not (org-in-regexp org-any-link-re)))
10444 (org-footnote-action))
10446 (let (type path link line search (pos (point)))
10447 (catch 'match
10448 (save-excursion
10449 (skip-chars-forward "^]\n\r")
10450 (when (org-in-regexp org-bracket-link-regexp 1)
10451 (setq link (org-extract-attributes
10452 (org-link-unescape (org-match-string-no-properties 1))))
10453 (while (string-match " *\n *" link)
10454 (setq link (replace-match " " t t link)))
10455 (setq link (org-link-expand-abbrev link))
10456 (cond
10457 ((or (file-name-absolute-p link)
10458 (string-match "^\\.\\.?/" link))
10459 (setq type "file" path link))
10460 ((string-match org-link-re-with-space3 link)
10461 (setq type (match-string 1 link) path (match-string 2 link)))
10462 ((string-match "^help:+\\(.+\\)" link)
10463 (setq type "help" path (match-string 1 link)))
10464 (t (setq type "thisfile" path link)))
10465 (throw 'match t)))
10467 (when (get-text-property (point) 'org-linked-text)
10468 (setq type "thisfile"
10469 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10470 (1+ (point)) (point))
10471 path (buffer-substring
10472 (or (previous-single-property-change pos 'org-linked-text)
10473 (point-min))
10474 (or (next-single-property-change pos 'org-linked-text)
10475 (point-max)))
10476 ;; Ensure we will search for a <<<radio>>> link, not
10477 ;; a simple reference like <<ref>>
10478 path (concat "<" path))
10479 (throw 'match t))
10481 (save-excursion
10482 (when (or (org-in-regexp org-angle-link-re)
10483 (let ((match (org-in-regexp org-plain-link-re)))
10484 ;; Check a plain link is not within a bracket link
10485 (and match
10486 (save-excursion
10487 (progn
10488 (goto-char (car match))
10489 (not (org-in-regexp org-bracket-link-regexp))))))
10490 (let ((line_ending (save-excursion (end-of-line) (point))))
10491 ;; We are in a line before a plain or bracket link
10492 (or (re-search-forward org-plain-link-re line_ending t)
10493 (re-search-forward org-bracket-link-regexp line_ending t))))
10494 (setq type (match-string 1)
10495 path (org-link-unescape (match-string 2)))
10496 (throw 'match t)))
10497 (save-excursion
10498 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10499 (setq type "tags"
10500 path (match-string 1))
10501 (while (string-match ":" path)
10502 (setq path (replace-match "+" t t path)))
10503 (throw 'match t)))
10504 (when (org-in-regexp "<\\([^><\n]+\\)>")
10505 (setq type "tree-match"
10506 path (match-string 1))
10507 (throw 'match t)))
10508 (unless path
10509 (user-error "No link found"))
10511 ;; switch back to reference buffer
10512 ;; needed when if called in a temporary buffer through
10513 ;; org-open-link-from-string
10514 (with-current-buffer (or reference-buffer (current-buffer))
10516 ;; Remove any trailing spaces in path
10517 (if (string-match " +\\'" path)
10518 (setq path (replace-match "" t t path)))
10519 (if (and org-link-translation-function
10520 (fboundp org-link-translation-function))
10521 ;; Check if we need to translate the link
10522 (let ((tmp (funcall org-link-translation-function type path)))
10523 (setq type (car tmp) path (cdr tmp))))
10525 (cond
10527 ((assoc type org-link-protocols)
10528 (funcall (nth 1 (assoc type org-link-protocols)) path))
10530 ((equal type "help")
10531 (let ((f-or-v (intern path)))
10532 (cond ((fboundp f-or-v)
10533 (describe-function f-or-v))
10534 ((boundp f-or-v)
10535 (describe-variable f-or-v))
10536 (t (error "Not a known function or variable")))))
10538 ((equal type "mailto")
10539 (let ((cmd (car org-link-mailto-program))
10540 (args (cdr org-link-mailto-program)) args1
10541 (address path) (subject "") a)
10542 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10543 (setq address (match-string 1 path)
10544 subject (org-link-escape (match-string 2 path))))
10545 (while args
10546 (cond
10547 ((not (stringp (car args))) (push (pop args) args1))
10548 (t (setq a (pop args))
10549 (if (string-match "%a" a)
10550 (setq a (replace-match address t t a)))
10551 (if (string-match "%s" a)
10552 (setq a (replace-match subject t t a)))
10553 (push a args1))))
10554 (apply cmd (nreverse args1))))
10556 ((member type '("http" "https" "ftp" "news"))
10557 ;; In the example of the http Org link
10558 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10559 ;; to open a browser with +subject:"Release 8.2" in the
10560 ;; query field the variable `path' contains
10561 ;; [...]=%2Bsubject:"Release+8.2", `url-encode-url'
10562 ;; converts correct to [...]=%2Bsubject:%22Release+8.2%22
10563 ;; and `org-link-escape-browser' converts wrong to
10564 ;; [...]=%252Bsubject:%22Release+8.2%22.
10566 ;; `url-encode-url' is available since Emacs 24.3.1 and
10567 ;; `org-link-escape-browser' can be removed altogether
10568 ;; once Org drops support for Emacs 24.1 and 24.2.
10569 (browse-url (funcall (if (fboundp 'url-encode-url)
10570 #'url-encode-url
10571 #'org-link-escape-browser)
10572 (concat type ":" path))))
10574 ((string= type "doi")
10575 ;; See comments for type http above
10576 (browse-url (funcall (if (fboundp 'url-encode-url)
10577 #'url-encode-url
10578 #'org-link-escape-browser)
10579 (concat org-doi-server-url path))))
10581 ((member type '("message"))
10582 (browse-url (concat type ":" path)))
10584 ((string= type "tags")
10585 (org-tags-view arg path))
10587 ((string= type "tree-match")
10588 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10590 ((string= type "file")
10591 (if (string-match "::\\([0-9]+\\)\\'" path)
10592 (setq line (string-to-number (match-string 1 path))
10593 path (substring path 0 (match-beginning 0)))
10594 (if (string-match "::\\(.+\\)\\'" path)
10595 (setq search (match-string 1 path)
10596 path (substring path 0 (match-beginning 0)))))
10597 (if (string-match "[*?{]" (file-name-nondirectory path))
10598 (dired path)
10599 (org-open-file path arg line search)))
10601 ((string= type "shell")
10602 (let ((buf (generate-new-buffer "*Org Shell Output"))
10603 (cmd path))
10604 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10605 (string-match org-confirm-shell-link-not-regexp cmd))
10606 (not org-confirm-shell-link-function)
10607 (funcall org-confirm-shell-link-function
10608 (format "Execute \"%s\" in shell? "
10609 (org-add-props cmd nil
10610 'face 'org-warning))))
10611 (progn
10612 (message "Executing %s" cmd)
10613 (shell-command cmd buf)
10614 (if (featurep 'midnight)
10615 (setq clean-buffer-list-kill-buffer-names
10616 (cons buf clean-buffer-list-kill-buffer-names))))
10617 (error "Abort"))))
10619 ((string= type "elisp")
10620 (let ((cmd path))
10621 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10622 (string-match org-confirm-elisp-link-not-regexp cmd))
10623 (not org-confirm-elisp-link-function)
10624 (funcall org-confirm-elisp-link-function
10625 (format "Execute \"%s\" as elisp? "
10626 (org-add-props cmd nil
10627 'face 'org-warning))))
10628 (message "%s => %s" cmd
10629 (if (equal (string-to-char cmd) ?\()
10630 (eval (read cmd))
10631 (call-interactively (read cmd))))
10632 (error "Abort"))))
10634 ((and (string= type "thisfile")
10635 (or (run-hook-with-args-until-success
10636 'org-open-link-functions path)
10637 (and link
10638 (string-match "^id:" link)
10639 (or (featurep 'org-id) (require 'org-id))
10640 (progn
10641 (funcall (nth 1 (assoc "id" org-link-protocols))
10642 (substring path 3))
10643 t)))))
10645 ((string= type "thisfile")
10646 (if arg
10647 (switch-to-buffer-other-window
10648 (org-get-buffer-for-internal-link (current-buffer)))
10649 (org-mark-ring-push))
10650 (let ((cmd `(org-link-search
10651 ,path
10652 ,(cond ((equal arg '(4)) ''occur)
10653 ((equal arg '(16)) ''org-occur))
10654 ,pos)))
10655 (condition-case nil (let ((org-link-search-inhibit-query t))
10656 (eval cmd))
10657 (error (progn (widen) (eval cmd))))))
10659 (t (browse-url-at-point)))))))
10660 (move-marker org-open-link-marker nil)
10661 (run-hook-with-args 'org-follow-link-hook)))
10663 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10664 "Offer links in the current entry and return the selected link.
10665 If there is only one link, return it.
10666 If NTH is an integer, return the NTH link found.
10667 If ZERO is a string, check also this string for a link, and if
10668 there is one, return it."
10669 (with-current-buffer buffer
10670 (save-excursion
10671 (save-restriction
10672 (widen)
10673 (goto-char marker)
10674 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10675 "\\(" org-angle-link-re "\\)\\|"
10676 "\\(" org-plain-link-re "\\)"))
10677 (cnt ?0)
10678 (in-emacs (if (integerp nth) nil nth))
10679 have-zero end links link c)
10680 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10681 (push (match-string 0 zero) links)
10682 (setq cnt (1- cnt) have-zero t))
10683 (save-excursion
10684 (org-back-to-heading t)
10685 (setq end (save-excursion (outline-next-heading) (point)))
10686 (while (re-search-forward re end t)
10687 (push (match-string 0) links))
10688 (setq links (org-uniquify (reverse links))))
10689 (cond
10690 ((null links)
10691 (message "No links"))
10692 ((equal (length links) 1)
10693 (setq link (car links)))
10694 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10695 (setq link (nth (if have-zero nth (1- nth)) links)))
10696 (t ; we have to select a link
10697 (save-excursion
10698 (save-window-excursion
10699 (delete-other-windows)
10700 (with-output-to-temp-buffer "*Select Link*"
10701 (mapc (lambda (l)
10702 (if (not (string-match org-bracket-link-regexp l))
10703 (princ (format "[%c] %s\n" (incf cnt)
10704 (org-remove-angle-brackets l)))
10705 (if (match-end 3)
10706 (princ (format "[%c] %s (%s)\n" (incf cnt)
10707 (match-string 3 l) (match-string 1 l)))
10708 (princ (format "[%c] %s\n" (incf cnt)
10709 (match-string 1 l))))))
10710 links))
10711 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10712 (message "Select link to open, RET to open all:")
10713 (setq c (read-char-exclusive))
10714 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10715 (when (equal c ?q) (error "Abort"))
10716 (if (equal c ?\C-m)
10717 (setq link links)
10718 (setq nth (- c ?0))
10719 (if have-zero (setq nth (1+ nth)))
10720 (unless (and (integerp nth) (>= (length links) nth))
10721 (user-error "Invalid link selection"))
10722 (setq link (nth (1- nth) links)))))
10723 (cons link end))))))
10725 ;; Add special file links that specify the way of opening
10727 (org-add-link-type "file+sys" 'org-open-file-with-system)
10728 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10729 (defun org-open-file-with-system (path)
10730 "Open file at PATH using the system way of opening it."
10731 (org-open-file path 'system))
10732 (defun org-open-file-with-emacs (path)
10733 "Open file at PATH in Emacs."
10734 (org-open-file path 'emacs))
10737 ;;; File search
10739 (defvar org-create-file-search-functions nil
10740 "List of functions to construct the right search string for a file link.
10741 These functions are called in turn with point at the location to
10742 which the link should point.
10744 A function in the hook should first test if it would like to
10745 handle this file type, for example by checking the `major-mode'
10746 or the file extension. If it decides not to handle this file, it
10747 should just return nil to give other functions a chance. If it
10748 does handle the file, it must return the search string to be used
10749 when following the link. The search string will be part of the
10750 file link, given after a double colon, and `org-open-at-point'
10751 will automatically search for it. If special measures must be
10752 taken to make the search successful, another function should be
10753 added to the companion hook `org-execute-file-search-functions',
10754 which see.
10756 A function in this hook may also use `setq' to set the variable
10757 `description' to provide a suggestion for the descriptive text to
10758 be used for this link when it gets inserted into an Org-mode
10759 buffer with \\[org-insert-link].")
10761 (defvar org-execute-file-search-functions nil
10762 "List of functions to execute a file search triggered by a link.
10764 Functions added to this hook must accept a single argument, the
10765 search string that was part of the file link, the part after the
10766 double colon. The function must first check if it would like to
10767 handle this search, for example by checking the `major-mode' or
10768 the file extension. If it decides not to handle this search, it
10769 should just return nil to give other functions a chance. If it
10770 does handle the search, it must return a non-nil value to keep
10771 other functions from trying.
10773 Each function can access the current prefix argument through the
10774 variable `current-prefix-arg'. Note that a single prefix is used
10775 to force opening a link in Emacs, so it may be good to only use a
10776 numeric or double prefix to guide the search function.
10778 In case this is needed, a function in this hook can also restore
10779 the window configuration before `org-open-at-point' was called using:
10781 (set-window-configuration org-window-config-before-follow-link)")
10783 (defun org-link-search (s &optional type avoid-pos stealth)
10784 "Search for a link search option.
10785 If S is surrounded by forward slashes, it is interpreted as a
10786 regular expression. In org-mode files, this will create an `org-occur'
10787 sparse tree. In ordinary files, `occur' will be used to list matches.
10788 If the current buffer is in `dired-mode', grep will be used to search
10789 in all files. If AVOID-POS is given, ignore matches near that position.
10791 When optional argument STEALTH is non-nil, do not modify
10792 visibility around point, thus ignoring
10793 `org-show-hierarchy-above', `org-show-following-heading' and
10794 `org-show-siblings' variables."
10795 (let ((case-fold-search t)
10796 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10797 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10798 (append '(("") (" ") ("\t") ("\n"))
10799 org-emphasis-alist)
10800 "\\|") "\\)"))
10801 (pos (point))
10802 (pre nil) (post nil)
10803 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10804 (cond
10805 ;; First check if there are any special search functions
10806 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10807 ;; Now try the builtin stuff
10808 ((and (equal (string-to-char s0) ?#)
10809 (> (length s0) 1)
10810 (save-excursion
10811 (goto-char (point-min))
10812 (and
10813 (re-search-forward
10814 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10815 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10816 (setq type 'dedicated
10817 pos (match-beginning 0))))
10818 ;; There is an exact target for this
10819 (goto-char pos)
10820 (org-back-to-heading t)))
10821 ((save-excursion
10822 (goto-char (point-min))
10823 (and
10824 (re-search-forward
10825 (concat "<<" (regexp-quote s0) ">>") nil t)
10826 (setq type 'dedicated
10827 pos (match-beginning 0))))
10828 ;; There is an exact target for this
10829 (goto-char pos))
10830 ((save-excursion
10831 (goto-char (point-min))
10832 (and
10833 (re-search-forward
10834 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10835 (setq type 'dedicated pos (match-beginning 0))))
10836 ;; Found an element with a matching #+name affiliated keyword.
10837 (goto-char pos))
10838 ((and (string-match "^(\\(.*\\))$" s0)
10839 (save-excursion
10840 (goto-char (point-min))
10841 (and
10842 (re-search-forward
10843 (concat "[^[]" (regexp-quote
10844 (format org-coderef-label-format
10845 (match-string 1 s0))))
10846 nil t)
10847 (setq type 'dedicated
10848 pos (1+ (match-beginning 0))))))
10849 ;; There is a coderef target for this
10850 (goto-char pos))
10851 ((string-match "^/\\(.*\\)/$" s)
10852 ;; A regular expression
10853 (cond
10854 ((derived-mode-p 'org-mode)
10855 (org-occur (match-string 1 s)))
10856 (t (org-do-occur (match-string 1 s)))))
10857 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10858 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10859 (goto-char (point-min))
10860 (cond
10861 ((let (case-fold-search)
10862 (re-search-forward (format org-complex-heading-regexp-format
10863 (regexp-quote s))
10864 nil t))
10865 ;; OK, found a match
10866 (setq type 'dedicated)
10867 (goto-char (match-beginning 0)))
10868 ((and (not org-link-search-inhibit-query)
10869 (eq org-link-search-must-match-exact-headline 'query-to-create)
10870 (y-or-n-p "No match - create this as a new heading? "))
10871 (goto-char (point-max))
10872 (or (bolp) (newline))
10873 (insert "* " s "\n")
10874 (beginning-of-line 0))
10876 (goto-char pos)
10877 (error "No match"))))
10879 ;; A normal search string
10880 (when (equal (string-to-char s) ?*)
10881 ;; Anchor on headlines, post may include tags.
10882 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10883 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10884 s (substring s 1)))
10885 (remove-text-properties
10886 0 (length s)
10887 '(face nil mouse-face nil keymap nil fontified nil) s)
10888 ;; Make a series of regular expressions to find a match
10889 (setq words (org-split-string s "[ \n\r\t]+")
10891 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10892 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10893 "\\)" markers)
10894 re2a_ (concat "\\(" (mapconcat 'downcase words
10895 "[ \t\r\n]+") "\\)[ \t\r\n]")
10896 re2a (concat "[ \t\r\n]" re2a_)
10897 re4_ (concat "\\(" (mapconcat 'downcase words
10898 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10899 re4 (concat "[^a-zA-Z_]" re4_)
10901 re1 (concat pre re2 post)
10902 re3 (concat pre (if pre re4_ re4) post)
10903 re5 (concat pre ".*" re4)
10904 re2 (concat pre re2)
10905 re2a (concat pre (if pre re2a_ re2a))
10906 re4 (concat pre (if pre re4_ re4))
10907 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10908 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10909 re5 "\\)"))
10910 (cond
10911 ((eq type 'org-occur) (org-occur reall))
10912 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10913 (t (goto-char (point-min))
10914 (setq type 'fuzzy)
10915 (if (or (and (org-search-not-self 1 re0 nil t)
10916 (setq type 'dedicated))
10917 (org-search-not-self 1 re1 nil t)
10918 (org-search-not-self 1 re2 nil t)
10919 (org-search-not-self 1 re2a nil t)
10920 (org-search-not-self 1 re3 nil t)
10921 (org-search-not-self 1 re4 nil t)
10922 (org-search-not-self 1 re5 nil t))
10923 (goto-char (match-beginning 1))
10924 (goto-char pos)
10925 (error "No match"))))))
10926 (and (derived-mode-p 'org-mode)
10927 (not stealth)
10928 (org-show-context 'link-search))
10929 type))
10931 (defun org-search-not-self (group &rest args)
10932 "Execute `re-search-forward', but only accept matches that do not
10933 enclose the position of `org-open-link-marker'."
10934 (let ((m org-open-link-marker))
10935 (catch 'exit
10936 (while (apply 're-search-forward args)
10937 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10938 (goto-char (match-end group))
10939 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10940 (> (match-beginning 0) (marker-position m))
10941 (< (match-end 0) (marker-position m)))
10942 (save-match-data
10943 (or (not (org-in-regexp
10944 org-bracket-link-analytic-regexp 1))
10945 (not (match-end 4)) ; no description
10946 (and (<= (match-beginning 4) (point))
10947 (>= (match-end 4) (point))))))
10948 (throw 'exit (point))))))))
10950 (defun org-get-buffer-for-internal-link (buffer)
10951 "Return a buffer to be used for displaying the link target of internal links."
10952 (cond
10953 ((not org-display-internal-link-with-indirect-buffer)
10954 buffer)
10955 ((string-match "(Clone)$" (buffer-name buffer))
10956 (message "Buffer is already a clone, not making another one")
10957 ;; we also do not modify visibility in this case
10958 buffer)
10959 (t ; make a new indirect buffer for displaying the link
10960 (let* ((bn (buffer-name buffer))
10961 (ibn (concat bn "(Clone)"))
10962 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10963 (with-current-buffer ib (org-overview))
10964 ib))))
10966 (defun org-do-occur (regexp &optional cleanup)
10967 "Call the Emacs command `occur'.
10968 If CLEANUP is non-nil, remove the printout of the regular expression
10969 in the *Occur* buffer. This is useful if the regex is long and not useful
10970 to read."
10971 (occur regexp)
10972 (when cleanup
10973 (let ((cwin (selected-window)) win beg end)
10974 (when (setq win (get-buffer-window "*Occur*"))
10975 (select-window win))
10976 (goto-char (point-min))
10977 (when (re-search-forward "match[a-z]+" nil t)
10978 (setq beg (match-end 0))
10979 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10980 (setq end (1- (match-beginning 0)))))
10981 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10982 (goto-char (point-min))
10983 (select-window cwin))))
10985 ;;; The mark ring for links jumps
10987 (defvar org-mark-ring nil
10988 "Mark ring for positions before jumps in Org-mode.")
10989 (defvar org-mark-ring-last-goto nil
10990 "Last position in the mark ring used to go back.")
10991 ;; Fill and close the ring
10992 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10993 (loop for i from 1 to org-mark-ring-length do
10994 (push (make-marker) org-mark-ring))
10995 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10996 org-mark-ring)
10998 (defun org-mark-ring-push (&optional pos buffer)
10999 "Put the current position or POS into the mark ring and rotate it."
11000 (interactive)
11001 (setq pos (or pos (point)))
11002 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11003 (move-marker (car org-mark-ring)
11004 (or pos (point))
11005 (or buffer (current-buffer)))
11006 (message "%s"
11007 (substitute-command-keys
11008 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11010 (defun org-mark-ring-goto (&optional n)
11011 "Jump to the previous position in the mark ring.
11012 With prefix arg N, jump back that many stored positions. When
11013 called several times in succession, walk through the entire ring.
11014 Org-mode commands jumping to a different position in the current file,
11015 or to another Org-mode file, automatically push the old position
11016 onto the ring."
11017 (interactive "p")
11018 (let (p m)
11019 (if (eq last-command this-command)
11020 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11021 (setq p org-mark-ring))
11022 (setq org-mark-ring-last-goto p)
11023 (setq m (car p))
11024 (org-pop-to-buffer-same-window (marker-buffer m))
11025 (goto-char m)
11026 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11028 (defun org-remove-angle-brackets (s)
11029 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11030 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11032 (defun org-add-angle-brackets (s)
11033 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11034 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11036 (defun org-remove-double-quotes (s)
11037 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11038 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11041 ;;; Following specific links
11043 (defun org-follow-timestamp-link ()
11044 "Open an agenda view for the time-stamp date/range at point."
11045 (cond
11046 ((org-at-date-range-p t)
11047 (let ((org-agenda-start-on-weekday)
11048 (t1 (match-string 1))
11049 (t2 (match-string 2)) tt1 tt2)
11050 (setq tt1 (time-to-days (org-time-string-to-time t1))
11051 tt2 (time-to-days (org-time-string-to-time t2)))
11052 (let ((org-agenda-buffer-tmp-name
11053 (format "*Org Agenda(a:%s)"
11054 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11055 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11056 ((org-at-timestamp-p t)
11057 (let ((org-agenda-buffer-tmp-name
11058 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11059 (org-agenda-list nil (time-to-days (org-time-string-to-time
11060 (substring (match-string 1) 0 10)))
11061 1)))
11062 (t (error "This should not happen"))))
11065 ;;; Following file links
11066 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11067 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11068 (declare-function mailcap-mime-info
11069 "mailcap" (string &optional request no-decode))
11070 (defvar org-wait nil)
11071 (defun org-open-file (path &optional in-emacs line search)
11072 "Open the file at PATH.
11073 First, this expands any special file name abbreviations. Then the
11074 configuration variable `org-file-apps' is checked if it contains an
11075 entry for this file type, and if yes, the corresponding command is launched.
11077 If no application is found, Emacs simply visits the file.
11079 With optional prefix argument IN-EMACS, Emacs will visit the file.
11080 With a double \\[universal-argument] \\[universal-argument] \
11081 prefix arg, Org tries to avoid opening in Emacs
11082 and to use an external application to visit the file.
11084 Optional LINE specifies a line to go to, optional SEARCH a string
11085 to search for. If LINE or SEARCH is given, the file will be
11086 opened in Emacs, unless an entry from org-file-apps that makes
11087 use of groups in a regexp matches.
11089 If you want to change the way frames are used when following a
11090 link, please customize `org-link-frame-setup'.
11092 If the file does not exist, an error is thrown."
11093 (let* ((file (if (equal path "")
11094 buffer-file-name
11095 (substitute-in-file-name (expand-file-name path))))
11096 (file-apps (append org-file-apps (org-default-apps)))
11097 (apps (org-remove-if
11098 'org-file-apps-entry-match-against-dlink-p file-apps))
11099 (apps-dlink (org-remove-if-not
11100 'org-file-apps-entry-match-against-dlink-p file-apps))
11101 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11102 (dirp (if remp nil (file-directory-p file)))
11103 (file (if (and dirp org-open-directory-means-index-dot-org)
11104 (concat (file-name-as-directory file) "index.org")
11105 file))
11106 (a-m-a-p (assq 'auto-mode apps))
11107 (dfile (downcase file))
11108 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11109 (link (cond ((and (eq line nil)
11110 (eq search nil))
11111 file)
11112 (line
11113 (concat file "::" (number-to-string line)))
11114 (search
11115 (concat file "::" search))))
11116 (dlink (downcase link))
11117 (old-buffer (current-buffer))
11118 (old-pos (point))
11119 (old-mode major-mode)
11120 ext cmd link-match-data)
11121 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11122 (setq ext (match-string 1 dfile))
11123 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11124 (setq ext (match-string 1 dfile))))
11125 (cond
11126 ((member in-emacs '((16) system))
11127 (setq cmd (cdr (assoc 'system apps))))
11128 (in-emacs (setq cmd 'emacs))
11130 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11131 (and dirp (cdr (assoc 'directory apps)))
11132 ; first, try matching against apps-dlink
11133 ; if we get a match here, store the match data for later
11134 (let ((match (assoc-default dlink apps-dlink
11135 'string-match)))
11136 (if match
11137 (progn (setq link-match-data (match-data))
11138 match)
11139 (progn (setq in-emacs (or in-emacs line search))
11140 nil))) ; if we have no match in apps-dlink,
11141 ; always open the file in emacs if line or search
11142 ; is given (for backwards compatibility)
11143 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11144 'string-match)
11145 (cdr (assoc ext apps))
11146 (cdr (assoc t apps))))))
11147 (when (eq cmd 'system)
11148 (setq cmd (cdr (assoc 'system apps))))
11149 (when (eq cmd 'default)
11150 (setq cmd (cdr (assoc t apps))))
11151 (when (eq cmd 'mailcap)
11152 (require 'mailcap)
11153 (mailcap-parse-mailcaps)
11154 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11155 (command (mailcap-mime-info mime-type)))
11156 (if (stringp command)
11157 (setq cmd command)
11158 (setq cmd 'emacs))))
11159 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11160 (not (file-exists-p file))
11161 (not org-open-non-existing-files))
11162 (user-error "No such file: %s" file))
11163 (cond
11164 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11165 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11166 (while (string-match "['\"]%s['\"]" cmd)
11167 (setq cmd (replace-match "%s" t t cmd)))
11168 (while (string-match "%s" cmd)
11169 (setq cmd (replace-match
11170 (save-match-data
11171 (shell-quote-argument
11172 (convert-standard-filename file)))
11173 t t cmd)))
11175 ;; Replace "%1", "%2" etc. in command with group matches from regex
11176 (save-match-data
11177 (let ((match-index 1)
11178 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11179 (set-match-data link-match-data)
11180 (while (<= match-index number-of-groups)
11181 (let ((regex (concat "%" (number-to-string match-index)))
11182 (replace-with (match-string match-index dlink)))
11183 (while (string-match regex cmd)
11184 (setq cmd (replace-match replace-with t t cmd))))
11185 (setq match-index (+ match-index 1)))))
11187 (save-window-excursion
11188 (message "Running %s...done" cmd)
11189 (start-process-shell-command cmd nil cmd)
11190 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11191 ((or (stringp cmd)
11192 (eq cmd 'emacs))
11193 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11194 (widen)
11195 (if line (progn (org-goto-line line)
11196 (if (derived-mode-p 'org-mode)
11197 (org-reveal)))
11198 (if search (org-link-search search))))
11199 ((consp cmd)
11200 (let ((file (convert-standard-filename file)))
11201 (save-match-data
11202 (set-match-data link-match-data)
11203 (eval cmd))))
11204 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11205 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11206 (or (not (equal old-buffer (current-buffer)))
11207 (not (equal old-pos (point))))
11208 (org-mark-ring-push old-pos old-buffer))))
11210 (defun org-file-apps-entry-match-against-dlink-p (entry)
11211 "This function returns non-nil if `entry' uses a regular
11212 expression which should be matched against the whole link by
11213 org-open-file.
11215 It assumes that is the case when the entry uses a regular
11216 expression which has at least one grouping construct and the
11217 action is either a lisp form or a command string containing
11218 '%1', i.e. using at least one subexpression match as a
11219 parameter."
11220 (let ((selector (car entry))
11221 (action (cdr entry)))
11222 (if (stringp selector)
11223 (and (> (regexp-opt-depth selector) 0)
11224 (or (and (stringp action)
11225 (string-match "%[0-9]" action))
11226 (consp action)))
11227 nil)))
11229 (defun org-default-apps ()
11230 "Return the default applications for this operating system."
11231 (cond
11232 ((eq system-type 'darwin)
11233 org-file-apps-defaults-macosx)
11234 ((eq system-type 'windows-nt)
11235 org-file-apps-defaults-windowsnt)
11236 (t org-file-apps-defaults-gnu)))
11238 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11239 "Convert extensions to regular expressions in the cars of LIST.
11240 Also, weed out any non-string entries, because the return value is used
11241 only for regexp matching.
11242 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11243 point to the symbol `emacs', indicating that the file should
11244 be opened in Emacs."
11245 (append
11246 (delq nil
11247 (mapcar (lambda (x)
11248 (if (not (stringp (car x)))
11250 (if (string-match "\\W" (car x))
11252 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11253 list))
11254 (if add-auto-mode
11255 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11257 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11258 (defun org-file-remote-p (file)
11259 "Test whether FILE specifies a location on a remote system.
11260 Return non-nil if the location is indeed remote.
11262 For example, the filename \"/user@host:/foo\" specifies a location
11263 on the system \"/user@host:\"."
11264 (cond ((fboundp 'file-remote-p)
11265 (file-remote-p file))
11266 ((fboundp 'tramp-handle-file-remote-p)
11267 (tramp-handle-file-remote-p file))
11268 ((and (boundp 'ange-ftp-name-format)
11269 (string-match (car ange-ftp-name-format) file))
11270 t)))
11273 ;;;; Refiling
11275 (defun org-get-org-file ()
11276 "Read a filename, with default directory `org-directory'."
11277 (let ((default (or org-default-notes-file remember-data-file)))
11278 (read-file-name (format "File name [%s]: " default)
11279 (file-name-as-directory org-directory)
11280 default)))
11282 (defun org-notes-order-reversed-p ()
11283 "Check if the current file should receive notes in reversed order."
11284 (cond
11285 ((not org-reverse-note-order) nil)
11286 ((eq t org-reverse-note-order) t)
11287 ((not (listp org-reverse-note-order)) nil)
11288 (t (catch 'exit
11289 (let ((all org-reverse-note-order)
11290 entry)
11291 (while (setq entry (pop all))
11292 (if (string-match (car entry) buffer-file-name)
11293 (throw 'exit (cdr entry))))
11294 nil)))))
11296 (defvar org-refile-target-table nil
11297 "The list of refile targets, created by `org-refile'.")
11299 (defvar org-agenda-new-buffers nil
11300 "Buffers created to visit agenda files.")
11302 (defvar org-refile-cache nil
11303 "Cache for refile targets.")
11305 (defvar org-refile-markers nil
11306 "All the markers used for caching refile locations.")
11308 (defun org-refile-marker (pos)
11309 "Get a new refile marker, but only if caching is in use."
11310 (if (not org-refile-use-cache)
11312 (let ((m (make-marker)))
11313 (move-marker m pos)
11314 (push m org-refile-markers)
11315 m)))
11317 (defun org-refile-cache-clear ()
11318 "Clear the refile cache and disable all the markers."
11319 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11320 (setq org-refile-markers nil)
11321 (setq org-refile-cache nil)
11322 (message "Refile cache has been cleared"))
11324 (defun org-refile-cache-check-set (set)
11325 "Check if all the markers in the cache still have live buffers."
11326 (let (marker)
11327 (catch 'exit
11328 (while (and set (setq marker (nth 3 (pop set))))
11329 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11330 (when (and marker (null (marker-buffer marker)))
11331 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11332 (sit-for 3)
11333 (throw 'exit nil)))
11334 t)))
11336 (defun org-refile-cache-put (set &rest identifiers)
11337 "Push the refile targets SET into the cache, under IDENTIFIERS."
11338 (let* ((key (sha1 (prin1-to-string identifiers)))
11339 (entry (assoc key org-refile-cache)))
11340 (if entry
11341 (setcdr entry set)
11342 (push (cons key set) org-refile-cache))))
11344 (defun org-refile-cache-get (&rest identifiers)
11345 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11346 (cond
11347 ((not org-refile-cache) nil)
11348 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11350 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11351 org-refile-cache))))
11352 (and set (org-refile-cache-check-set set) set)))))
11354 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11355 "Produce a table with refile targets."
11356 (let ((case-fold-search nil)
11357 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11358 (entries (or org-refile-targets '((nil . (:level . 1)))))
11359 targets tgs txt re files f desc descre fast-path-p level pos0)
11360 (message "Getting targets...")
11361 (with-current-buffer (or default-buffer (current-buffer))
11362 (while (setq entry (pop entries))
11363 (setq files (car entry) desc (cdr entry))
11364 (setq fast-path-p nil)
11365 (cond
11366 ((null files) (setq files (list (current-buffer))))
11367 ((eq files 'org-agenda-files)
11368 (setq files (org-agenda-files 'unrestricted)))
11369 ((and (symbolp files) (fboundp files))
11370 (setq files (funcall files)))
11371 ((and (symbolp files) (boundp files))
11372 (setq files (symbol-value files))))
11373 (if (stringp files) (setq files (list files)))
11374 (cond
11375 ((eq (car desc) :tag)
11376 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11377 ((eq (car desc) :todo)
11378 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11379 ((eq (car desc) :regexp)
11380 (setq descre (cdr desc)))
11381 ((eq (car desc) :level)
11382 (setq descre (concat "^\\*\\{" (number-to-string
11383 (if org-odd-levels-only
11384 (1- (* 2 (cdr desc)))
11385 (cdr desc)))
11386 "\\}[ \t]")))
11387 ((eq (car desc) :maxlevel)
11388 (setq fast-path-p t)
11389 (setq descre (concat "^\\*\\{1," (number-to-string
11390 (if org-odd-levels-only
11391 (1- (* 2 (cdr desc)))
11392 (cdr desc)))
11393 "\\}[ \t]")))
11394 (t (error "Bad refiling target description %s" desc)))
11395 (while (setq f (pop files))
11396 (with-current-buffer
11397 (if (bufferp f) f (org-get-agenda-file-buffer f))
11399 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11400 (progn
11401 (if (bufferp f) (setq f (buffer-file-name
11402 (buffer-base-buffer f))))
11403 (setq f (and f (expand-file-name f)))
11404 (if (eq org-refile-use-outline-path 'file)
11405 (push (list (file-name-nondirectory f) f nil nil) tgs))
11406 (save-excursion
11407 (save-restriction
11408 (widen)
11409 (goto-char (point-min))
11410 (while (re-search-forward descre nil t)
11411 (goto-char (setq pos0 (point-at-bol)))
11412 (catch 'next
11413 (when org-refile-target-verify-function
11414 (save-match-data
11415 (or (funcall org-refile-target-verify-function)
11416 (throw 'next t))))
11417 (when (and (looking-at org-complex-heading-regexp)
11418 (not (member (match-string 4) excluded-entries))
11419 (match-string 4))
11420 (setq level (org-reduced-level
11421 (- (match-end 1) (match-beginning 1)))
11422 txt (org-link-display-format (match-string 4))
11423 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11424 re (format org-complex-heading-regexp-format
11425 (regexp-quote (match-string 4))))
11426 (when org-refile-use-outline-path
11427 (setq txt (mapconcat
11428 'org-protect-slash
11429 (append
11430 (if (eq org-refile-use-outline-path
11431 'file)
11432 (list (file-name-nondirectory
11433 (buffer-file-name
11434 (buffer-base-buffer))))
11435 (if (eq org-refile-use-outline-path
11436 'full-file-path)
11437 (list (buffer-file-name
11438 (buffer-base-buffer)))))
11439 (org-get-outline-path fast-path-p
11440 level txt)
11441 (list txt))
11442 "/")))
11443 (push (list txt f re (org-refile-marker (point)))
11444 tgs)))
11445 (when (= (point) pos0)
11446 ;; verification function has not moved point
11447 (goto-char (point-at-eol))))))))
11448 (when org-refile-use-cache
11449 (org-refile-cache-put tgs (buffer-file-name) descre))
11450 (setq targets (append tgs targets))))))
11451 (message "Getting targets...done")
11452 (nreverse targets)))
11454 (defun org-protect-slash (s)
11455 (while (string-match "/" s)
11456 (setq s (replace-match "\\" t t s)))
11459 (defvar org-olpa (make-vector 20 nil))
11461 (defun org-get-outline-path (&optional fastp level heading)
11462 "Return the outline path to the current entry, as a list.
11464 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11465 routine which makes outline path derivations for an entire file,
11466 avoiding backtracing. Refile target collection makes use of that."
11467 (if fastp
11468 (progn
11469 (if (> level 19)
11470 (error "Outline path failure, more than 19 levels"))
11471 (loop for i from level upto 19 do
11472 (aset org-olpa i nil))
11473 (prog1
11474 (delq nil (append org-olpa nil))
11475 (aset org-olpa level heading)))
11476 (let (rtn case-fold-search)
11477 (save-excursion
11478 (save-restriction
11479 (widen)
11480 (while (org-up-heading-safe)
11481 (when (looking-at org-complex-heading-regexp)
11482 (push (org-trim
11483 (replace-regexp-in-string
11484 ;; Remove statistical/checkboxes cookies
11485 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11486 (org-match-string-no-properties 4)))
11487 rtn)))
11488 rtn)))))
11490 (defun org-format-outline-path (path &optional width prefix separator)
11491 "Format the outline path PATH for display.
11492 WIDTH is the maximum number of characters that is available.
11493 PREFIX is a prefix to be included in the returned string,
11494 such as the file name.
11495 SEPARATOR is inserted between the different parts of the path,
11496 the default is \"/\"."
11497 (setq width (or width 79))
11498 (if prefix (setq width (- width (length prefix))))
11499 (if (not path)
11500 (or prefix "")
11501 (let* ((nsteps (length path))
11502 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11503 (maxwidth (if (<= total-width width)
11504 10000 ;; everything fits
11505 ;; we need to shorten the level headings
11506 (/ (- width nsteps) nsteps)))
11507 (org-odd-levels-only nil)
11508 (n 0)
11509 (total (1+ (length prefix))))
11510 (setq maxwidth (max maxwidth 10))
11511 (concat prefix
11512 (if prefix (or separator "/"))
11513 (mapconcat
11514 (lambda (h)
11515 (setq n (1+ n))
11516 (if (and (= n nsteps) (< maxwidth 10000))
11517 (setq maxwidth (- total-width total)))
11518 (if (< (length h) maxwidth)
11519 (progn (setq total (+ total (length h) 1)) h)
11520 (setq h (substring h 0 (- maxwidth 2))
11521 total (+ total maxwidth 1))
11522 (if (string-match "[ \t]+\\'" h)
11523 (setq h (substring h 0 (match-beginning 0))))
11524 (setq h (concat h "..")))
11525 (org-add-props h nil 'face
11526 (nth (% (1- n) org-n-level-faces)
11527 org-level-faces))
11529 path (or separator "/"))))))
11531 (defun org-display-outline-path (&optional file current separator just-return-string)
11532 "Display the current outline path in the echo area.
11534 If FILE is non-nil, prepend the output with the file name.
11535 If CURRENT is non-nil, append the current heading to the output.
11536 SEPARATOR is passed through to `org-format-outline-path'. It separates
11537 the different parts of the path and defaults to \"/\".
11538 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11539 (interactive "P")
11540 (let* (case-fold-search
11541 (bfn (buffer-file-name (buffer-base-buffer)))
11542 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11543 res)
11544 (if current (setq path (append path
11545 (save-excursion
11546 (org-back-to-heading t)
11547 (if (looking-at org-complex-heading-regexp)
11548 (list (match-string 4)))))))
11549 (setq res
11550 (org-format-outline-path
11551 path
11552 (1- (frame-width))
11553 (and file bfn (concat (file-name-nondirectory bfn) separator))
11554 separator))
11555 (if just-return-string
11556 (org-no-properties res)
11557 (org-unlogged-message "%s" res))))
11559 (defvar org-refile-history nil
11560 "History for refiling operations.")
11562 (defvar org-after-refile-insert-hook nil
11563 "Hook run after `org-refile' has inserted its stuff at the new location.
11564 Note that this is still *before* the stuff will be removed from
11565 the *old* location.")
11567 (defvar org-capture-last-stored-marker)
11568 (defvar org-refile-keep nil
11569 "Non-nil means `org-refile' will copy instead of refile.")
11571 (defun org-copy ()
11572 "Like `org-refile', but copy."
11573 (interactive)
11574 (let ((org-refile-keep t))
11575 (funcall 'org-refile nil nil nil "Copy")))
11577 (defun org-refile (&optional goto default-buffer rfloc msg)
11578 "Move the entry or entries at point to another heading.
11579 The list of target headings is compiled using the information in
11580 `org-refile-targets', which see.
11582 At the target location, the entry is filed as a subitem of the target
11583 heading. Depending on `org-reverse-note-order', the new subitem will
11584 either be the first or the last subitem.
11586 If there is an active region, all entries in that region will be moved.
11587 However, the region must fulfill the requirement that the first heading
11588 is the first one sets the top-level of the moved text - at most siblings
11589 below it are allowed.
11591 With prefix arg GOTO, the command will only visit the target location
11592 and not actually move anything.
11594 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11595 go to the location where the last refiling operation has put the subtree.
11597 With a numeric prefix argument of `2', refile to the running clock.
11599 With a numeric prefix argument of `3', emulate `org-refile-keep'
11600 being set to `t' and copy to the target location, don't move it.
11601 Beware that keeping refiled entries may result in duplicated ID
11602 properties.
11604 RFLOC can be a refile location obtained in a different way.
11606 MSG is a string to replace \"Refile\" in the default prompt with
11607 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11609 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11611 If you are using target caching (see `org-refile-use-cache'),
11612 you have to clear the target cache in order to find new targets.
11613 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11614 prefix argument (`C-u C-u C-u C-c C-w')."
11616 (interactive "P")
11617 (if (member goto '(0 (64)))
11618 (org-refile-cache-clear)
11619 (let* ((actionmsg (or msg "Refile"))
11620 (cbuf (current-buffer))
11621 (regionp (org-region-active-p))
11622 (region-start (and regionp (region-beginning)))
11623 (region-end (and regionp (region-end)))
11624 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11625 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11626 pos it nbuf file re level reversed)
11627 (setq last-command nil)
11628 (when regionp
11629 (goto-char region-start)
11630 (or (bolp) (goto-char (point-at-bol)))
11631 (setq region-start (point))
11632 (unless (or (org-kill-is-subtree-p
11633 (buffer-substring region-start region-end))
11634 (prog1 org-refile-active-region-within-subtree
11635 (let ((s (point-at-eol)))
11636 (org-toggle-heading)
11637 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11638 (user-error "The region is not a (sequence of) subtree(s)")))
11639 (if (equal goto '(16))
11640 (org-refile-goto-last-stored)
11641 (when (or
11642 (and (equal goto 2)
11643 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11644 (prog1
11645 (setq it (list (or org-clock-heading "running clock")
11646 (buffer-file-name
11647 (marker-buffer org-clock-hd-marker))
11649 (marker-position org-clock-hd-marker)))
11650 (setq goto nil)))
11651 (setq it (or rfloc
11652 (let (heading-text)
11653 (save-excursion
11654 (unless goto
11655 (org-back-to-heading t)
11656 (setq heading-text
11657 (nth 4 (org-heading-components))))
11659 (org-refile-get-location
11660 (cond (goto "Goto")
11661 (regionp (concat actionmsg " region to"))
11662 (t (concat actionmsg " subtree \""
11663 heading-text "\" to")))
11664 default-buffer
11665 (and (not (equal '(4) goto))
11666 org-refile-allow-creating-parent-nodes)
11667 goto))))))
11668 (setq file (nth 1 it)
11669 re (nth 2 it)
11670 pos (nth 3 it))
11671 (if (and (not goto)
11673 (equal (buffer-file-name) file)
11674 (if regionp
11675 (and (>= pos region-start)
11676 (<= pos region-end))
11677 (and (>= pos (point))
11678 (< pos (save-excursion
11679 (org-end-of-subtree t t))))))
11680 (error "Cannot refile to position inside the tree or region"))
11682 (setq nbuf (or (find-buffer-visiting file)
11683 (find-file-noselect file)))
11684 (if (and goto (not (equal goto 3)))
11685 (progn
11686 (org-pop-to-buffer-same-window nbuf)
11687 (goto-char pos)
11688 (org-show-context 'org-goto))
11689 (if regionp
11690 (progn
11691 (org-kill-new (buffer-substring region-start region-end))
11692 (org-save-markers-in-region region-start region-end))
11693 (org-copy-subtree 1 nil t))
11694 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11695 (find-file-noselect file)))
11696 (setq reversed (org-notes-order-reversed-p))
11697 (save-excursion
11698 (save-restriction
11699 (widen)
11700 (if pos
11701 (progn
11702 (goto-char pos)
11703 (looking-at org-outline-regexp)
11704 (setq level (org-get-valid-level (funcall outline-level) 1))
11705 (goto-char
11706 (if reversed
11707 (or (outline-next-heading) (point-max))
11708 (or (save-excursion (org-get-next-sibling))
11709 (org-end-of-subtree t t)
11710 (point-max)))))
11711 (setq level 1)
11712 (if (not reversed)
11713 (goto-char (point-max))
11714 (goto-char (point-min))
11715 (or (outline-next-heading) (goto-char (point-max)))))
11716 (if (not (bolp)) (newline))
11717 (org-paste-subtree level)
11718 (when org-log-refile
11719 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11720 (unless (eq org-log-refile 'note)
11721 (save-excursion (org-add-log-note))))
11722 (and org-auto-align-tags
11723 (let ((org-loop-over-headlines-in-active-region nil))
11724 (org-set-tags nil t)))
11725 (let ((bookmark-name (plist-get org-bookmark-names-plist
11726 :last-refile)))
11727 (when bookmark-name
11728 (with-demoted-errors
11729 (bookmark-set bookmark-name))))
11730 ;; If we are refiling for capture, make sure that the
11731 ;; last-capture pointers point here
11732 (when (org-bound-and-true-p org-refile-for-capture)
11733 (let ((bookmark-name (plist-get org-bookmark-names-plist
11734 :last-capture-marker)))
11735 (when bookmark-name
11736 (with-demoted-errors
11737 (bookmark-set bookmark-name))))
11738 (move-marker org-capture-last-stored-marker (point)))
11739 (if (fboundp 'deactivate-mark) (deactivate-mark))
11740 (run-hooks 'org-after-refile-insert-hook))))
11741 (unless org-refile-keep
11742 (if regionp
11743 (delete-region (point) (+ (point) (- region-end region-start)))
11744 (delete-region
11745 (and (org-back-to-heading t) (point))
11746 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11747 (when (featurep 'org-inlinetask)
11748 (org-inlinetask-remove-END-maybe))
11749 (setq org-markers-to-move nil)
11750 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11752 (defun org-refile-goto-last-stored ()
11753 "Go to the location where the last refile was stored."
11754 (interactive)
11755 (bookmark-jump "org-refile-last-stored")
11756 (message "This is the location of the last refile"))
11758 (defun org-refile--get-location (refloc tbl)
11759 "When user refile to REFLOC, find the associated target in TBL.
11760 Also check `org-refile-target-table'."
11761 (car (delq
11763 (mapcar
11764 (lambda (r) (or (assoc r tbl)
11765 (assoc r org-refile-target-table)))
11766 (list (replace-regexp-in-string "/$" "" refloc)
11767 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11769 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11770 no-exclude)
11771 "Prompt the user for a refile location, using PROMPT.
11772 PROMPT should not be suffixed with a colon and a space, because
11773 this function appends the default value from
11774 `org-refile-history' automatically, if that is not empty.
11775 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11776 this is used for the GOTO interface."
11777 (let ((org-refile-targets org-refile-targets)
11778 (org-refile-use-outline-path org-refile-use-outline-path)
11779 excluded-entries)
11780 (when (and (derived-mode-p 'org-mode)
11781 (not org-refile-use-cache)
11782 (not no-exclude))
11783 (org-map-tree
11784 (lambda()
11785 (setq excluded-entries
11786 (append excluded-entries (list (org-get-heading t t)))))))
11787 (setq org-refile-target-table
11788 (org-refile-get-targets default-buffer excluded-entries)))
11789 (unless org-refile-target-table
11790 (user-error "No refile targets"))
11791 (let* ((cbuf (current-buffer))
11792 (partial-completion-mode nil)
11793 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11794 (cfunc (if (and org-refile-use-outline-path
11795 org-outline-path-complete-in-steps)
11796 'org-olpath-completing-read
11797 'org-icompleting-read))
11798 (extra (if org-refile-use-outline-path "/" ""))
11799 (cbnex (concat (buffer-name) extra))
11800 (filename (and cfn (expand-file-name cfn)))
11801 (tbl (mapcar
11802 (lambda (x)
11803 (if (and (not (member org-refile-use-outline-path
11804 '(file full-file-path)))
11805 (not (equal filename (nth 1 x))))
11806 (cons (concat (car x) extra " ("
11807 (file-name-nondirectory (nth 1 x)) ")")
11808 (cdr x))
11809 (cons (concat (car x) extra) (cdr x))))
11810 org-refile-target-table))
11811 (completion-ignore-case t)
11812 cdef
11813 (prompt (concat prompt
11814 (or (and (car org-refile-history)
11815 (concat " (default " (car org-refile-history) ")"))
11816 (and (assoc cbnex tbl) (setq cdef cbnex)
11817 (concat " (default " cbnex ")"))) ": "))
11818 pa answ parent-target child parent old-hist)
11819 (setq old-hist org-refile-history)
11820 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11821 nil 'org-refile-history (or cdef (car org-refile-history))))
11822 (if (setq pa (org-refile--get-location answ tbl))
11823 (progn
11824 (org-refile-check-position pa)
11825 (when (or (not org-refile-history)
11826 (not (eq old-hist org-refile-history))
11827 (not (equal (car pa) (car org-refile-history))))
11828 (setq org-refile-history
11829 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11830 org-refile-history
11831 (cdr org-refile-history))))
11832 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11833 (pop org-refile-history)))
11835 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11836 (progn
11837 (setq parent (match-string 1 answ)
11838 child (match-string 2 answ))
11839 (setq parent-target (org-refile--get-location 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 (eq org-provide-todo-statistics t)
12719 (or (member kwd org-done-keywords)))
12720 (and (listp org-provide-todo-statistics)
12721 (stringp (car org-provide-todo-statistics))
12722 (or (member kwd org-provide-todo-statistics)
12723 (member kwd org-done-keywords)))
12724 (and (listp org-provide-todo-statistics)
12725 (listp (car org-provide-todo-statistics))
12726 (or (member kwd (car org-provide-todo-statistics))
12727 (and (member kwd org-done-keywords)
12728 (member kwd (cadr org-provide-todo-statistics))))))
12729 (setq cnt-all (1+ cnt-all))
12730 (if (eq org-provide-todo-statistics t)
12731 (and kwd (setq cnt-all (1+ cnt-all)))))
12732 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12733 (member kwd org-done-keywords))
12734 (and (listp org-provide-todo-statistics)
12735 (listp (car org-provide-todo-statistics))
12736 (member kwd org-done-keywords)
12737 (member kwd (cadr org-provide-todo-statistics)))
12738 (and (listp org-provide-todo-statistics)
12739 (stringp (car org-provide-todo-statistics))
12740 (member kwd org-done-keywords)))
12741 (setq cnt-done (1+ cnt-done)))
12742 (outline-next-heading)))
12743 (setq new
12744 (if is-percent
12745 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12746 (format "[%d/%d]" cnt-done cnt-all))
12747 ndel (- (match-end 0) checkbox-beg))
12748 ;; handle overlays when updating cookie from column view
12749 (when (setq ov (car (overlays-at checkbox-beg)))
12750 (setq ovs (overlay-start ov) ove (overlay-end ov))
12751 (delete-overlay ov))
12752 (goto-char checkbox-beg)
12753 (insert new)
12754 (delete-region (point) (+ (point) ndel))
12755 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12756 (when ov (move-overlay ov ovs ove)))
12757 (when cookie-present
12758 (run-hook-with-args 'org-after-todo-statistics-hook
12759 cnt-done (- cnt-all cnt-done))))))
12760 (run-hooks 'org-todo-statistics-hook)))
12762 (defvar org-after-todo-statistics-hook nil
12763 "Hook that is called after a TODO statistics cookie has been updated.
12764 Each function is called with two arguments: the number of not-done entries
12765 and the number of done entries.
12767 For example, the following function, when added to this hook, will switch
12768 an entry to DONE when all children are done, and back to TODO when new
12769 entries are set to a TODO status. Note that this hook is only called
12770 when there is a statistics cookie in the headline!
12772 (defun org-summary-todo (n-done n-not-done)
12773 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12774 (let (org-log-done org-log-states) ; turn off logging
12775 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12778 (defvar org-todo-statistics-hook nil
12779 "Hook that is run whenever Org thinks TODO statistics should be updated.
12780 This hook runs even if there is no statistics cookie present, in which case
12781 `org-after-todo-statistics-hook' would not run.")
12783 (defun org-todo-trigger-tag-changes (state)
12784 "Apply the changes defined in `org-todo-state-tags-triggers'."
12785 (let ((l org-todo-state-tags-triggers)
12786 changes)
12787 (when (or (not state) (equal state ""))
12788 (setq changes (append changes (cdr (assoc "" l)))))
12789 (when (and (stringp state) (> (length state) 0))
12790 (setq changes (append changes (cdr (assoc state l)))))
12791 (when (member state org-not-done-keywords)
12792 (setq changes (append changes (cdr (assoc 'todo l)))))
12793 (when (member state org-done-keywords)
12794 (setq changes (append changes (cdr (assoc 'done l)))))
12795 (dolist (c changes)
12796 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12798 (defun org-local-logging (value)
12799 "Get logging settings from a property VALUE."
12800 (let* (words w a)
12801 ;; directly set the variables, they are already local.
12802 (setq org-log-done nil
12803 org-log-repeat nil
12804 org-todo-log-states nil)
12805 (setq words (org-split-string value))
12806 (while (setq w (pop words))
12807 (cond
12808 ((setq a (assoc w org-startup-options))
12809 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12810 (set (nth 1 a) (nth 2 a))))
12811 ((setq a (org-extract-log-state-settings w))
12812 (and (member (car a) org-todo-keywords-1)
12813 (push a org-todo-log-states)))))))
12815 (defun org-get-todo-sequence-head (kwd)
12816 "Return the head of the TODO sequence to which KWD belongs.
12817 If KWD is not set, check if there is a text property remembering the
12818 right sequence."
12819 (let (p)
12820 (cond
12821 ((not kwd)
12822 (or (get-text-property (point-at-bol) 'org-todo-head)
12823 (progn
12824 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12825 nil (point-at-eol)))
12826 (get-text-property p 'org-todo-head))))
12827 ((not (member kwd org-todo-keywords-1))
12828 (car org-todo-keywords-1))
12829 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12831 (defun org-fast-todo-selection ()
12832 "Fast TODO keyword selection with single keys.
12833 Returns the new TODO keyword, or nil if no state change should occur."
12834 (let* ((fulltable org-todo-key-alist)
12835 (done-keywords org-done-keywords) ;; needed for the faces.
12836 (maxlen (apply 'max (mapcar
12837 (lambda (x)
12838 (if (stringp (car x)) (string-width (car x)) 0))
12839 fulltable)))
12840 (expert nil)
12841 (fwidth (+ maxlen 3 1 3))
12842 (ncol (/ (- (window-width) 4) fwidth))
12843 tg cnt e c tbl
12844 groups ingroup)
12845 (save-excursion
12846 (save-window-excursion
12847 (if expert
12848 (set-buffer (get-buffer-create " *Org todo*"))
12849 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12850 (erase-buffer)
12851 (org-set-local 'org-done-keywords done-keywords)
12852 (setq tbl fulltable cnt 0)
12853 (while (setq e (pop tbl))
12854 (cond
12855 ((equal e '(:startgroup))
12856 (push '() groups) (setq ingroup t)
12857 (when (not (= cnt 0))
12858 (setq cnt 0)
12859 (insert "\n"))
12860 (insert "{ "))
12861 ((equal e '(:endgroup))
12862 (setq ingroup nil cnt 0)
12863 (insert "}\n"))
12864 ((equal e '(:newline))
12865 (when (not (= cnt 0))
12866 (setq cnt 0)
12867 (insert "\n")
12868 (setq e (car tbl))
12869 (while (equal (car tbl) '(:newline))
12870 (insert "\n")
12871 (setq tbl (cdr tbl)))))
12873 (setq tg (car e) c (cdr e))
12874 (if ingroup (push tg (car groups)))
12875 (setq tg (org-add-props tg nil 'face
12876 (org-get-todo-face tg)))
12877 (if (and (= cnt 0) (not ingroup)) (insert " "))
12878 (insert "[" c "] " tg (make-string
12879 (- fwidth 4 (length tg)) ?\ ))
12880 (when (= (setq cnt (1+ cnt)) ncol)
12881 (insert "\n")
12882 (if ingroup (insert " "))
12883 (setq cnt 0)))))
12884 (insert "\n")
12885 (goto-char (point-min))
12886 (if (not expert) (org-fit-window-to-buffer))
12887 (message "[a-z..]:Set [SPC]:clear")
12888 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12889 (cond
12890 ((or (= c ?\C-g)
12891 (and (= c ?q) (not (rassoc c fulltable))))
12892 (setq quit-flag t))
12893 ((= c ?\ ) nil)
12894 ((setq e (rassoc c fulltable) tg (car e))
12896 (t (setq quit-flag t)))))))
12898 (defun org-entry-is-todo-p ()
12899 (member (org-get-todo-state) org-not-done-keywords))
12901 (defun org-entry-is-done-p ()
12902 (member (org-get-todo-state) org-done-keywords))
12904 (defun org-get-todo-state ()
12905 "Return the TODO keyword of the current subtree."
12906 (save-excursion
12907 (org-back-to-heading t)
12908 (and (looking-at org-todo-line-regexp)
12909 (match-end 2)
12910 (match-string 2))))
12912 (defun org-at-date-range-p (&optional inactive-ok)
12913 "Is the cursor inside a date range?"
12914 (interactive)
12915 (save-excursion
12916 (catch 'exit
12917 (let ((pos (point)))
12918 (skip-chars-backward "^[<\r\n")
12919 (skip-chars-backward "<[")
12920 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12921 (>= (match-end 0) pos)
12922 (throw 'exit t))
12923 (skip-chars-backward "^<[\r\n")
12924 (skip-chars-backward "<[")
12925 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12926 (>= (match-end 0) pos)
12927 (throw 'exit t)))
12928 nil)))
12930 (defun org-get-repeat (&optional tagline)
12931 "Check if there is a deadline/schedule with repeater in this entry."
12932 (save-match-data
12933 (save-excursion
12934 (org-back-to-heading t)
12935 (and (re-search-forward (if tagline
12936 (concat tagline "\\s-*" org-repeat-re)
12937 org-repeat-re)
12938 (org-entry-end-position) t)
12939 (match-string-no-properties 1)))))
12941 (defvar org-last-changed-timestamp)
12942 (defvar org-last-inserted-timestamp)
12943 (defvar org-log-post-message)
12944 (defvar org-log-note-purpose)
12945 (defvar org-log-note-how)
12946 (defvar org-log-note-extra)
12947 (defun org-auto-repeat-maybe (done-word)
12948 "Check if the current headline contains a repeated deadline/schedule.
12949 If yes, set TODO state back to what it was and change the base date
12950 of repeating deadline/scheduled time stamps to new date.
12951 This function is run automatically after each state change to a DONE state."
12952 ;; last-state is dynamically scoped into this function
12953 (let* ((repeat (org-get-repeat))
12954 (aa (assoc org-last-state org-todo-kwd-alist))
12955 (interpret (nth 1 aa))
12956 (head (nth 2 aa))
12957 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12958 (msg "Entry repeats: ")
12959 (org-log-done nil)
12960 (org-todo-log-states nil)
12961 re type n what ts time to-state)
12962 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12963 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12964 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12965 org-todo-repeat-to-state))
12966 (unless (and to-state (member to-state org-todo-keywords-1))
12967 (setq to-state (if (eq interpret 'type) org-last-state head)))
12968 (org-todo to-state)
12969 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12970 (org-entry-put nil "LAST_REPEAT" (format-time-string
12971 (org-time-stamp-format t t))))
12972 (when org-log-repeat
12973 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12974 (memq 'org-add-log-note post-command-hook))
12975 ;; OK, we are already setup for some record
12976 (if (eq org-log-repeat 'note)
12977 ;; make sure we take a note, not only a time stamp
12978 (setq org-log-note-how 'note))
12979 ;; Set up for taking a record
12980 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12981 org-last-state
12982 'findpos org-log-repeat)))
12983 (org-back-to-heading t)
12984 (org-add-planning-info nil nil 'closed)
12985 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12986 org-deadline-time-regexp "\\)\\|\\("
12987 org-ts-regexp "\\)"))
12988 (while (re-search-forward
12989 re (save-excursion (outline-next-heading) (point)) t)
12990 (setq type (if (match-end 1) org-scheduled-string
12991 (if (match-end 3) org-deadline-string "Plain:"))
12992 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12993 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12994 (setq n (string-to-number (match-string 2 ts))
12995 what (match-string 3 ts))
12996 (if (equal what "w") (setq n (* n 7) what "d"))
12997 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12998 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12999 ;; Preparation, see if we need to modify the start date for the change
13000 (when (match-end 1)
13001 (setq time (save-match-data (org-time-string-to-time ts)))
13002 (cond
13003 ((equal (match-string 1 ts) ".")
13004 ;; Shift starting date to today
13005 (org-timestamp-change
13006 (- (org-today) (time-to-days time))
13007 'day))
13008 ((equal (match-string 1 ts) "+")
13009 (let ((nshiftmax 10) (nshift 0))
13010 (while (or (= nshift 0)
13011 (<= (time-to-days time)
13012 (time-to-days (current-time))))
13013 (when (= (incf nshift) nshiftmax)
13014 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13015 (error "Abort")))
13016 (org-timestamp-change n (cdr (assoc what whata)))
13017 (org-at-timestamp-p t)
13018 (setq ts (match-string 1))
13019 (setq time (save-match-data (org-time-string-to-time ts)))))
13020 (org-timestamp-change (- n) (cdr (assoc what whata)))
13021 ;; rematch, so that we have everything in place for the real shift
13022 (org-at-timestamp-p t)
13023 (setq ts (match-string 1))
13024 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13025 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13026 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13027 (setq org-log-post-message msg)
13028 (message "%s" msg))))
13030 (defun org-show-todo-tree (arg)
13031 "Make a compact tree which shows all headlines marked with TODO.
13032 The tree will show the lines where the regexp matches, and all higher
13033 headlines above the match.
13034 With a \\[universal-argument] prefix, prompt for a regexp to match.
13035 With a numeric prefix N, construct a sparse tree for the Nth element
13036 of `org-todo-keywords-1'."
13037 (interactive "P")
13038 (let ((case-fold-search nil)
13039 (kwd-re
13040 (cond ((null arg) org-not-done-regexp)
13041 ((equal arg '(4))
13042 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13043 (mapcar 'list org-todo-keywords-1))))
13044 (concat "\\("
13045 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13046 "\\)\\>")))
13047 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13048 (regexp-quote (nth (1- (prefix-numeric-value arg))
13049 org-todo-keywords-1)))
13050 (t (user-error "Invalid prefix argument: %s" arg)))))
13051 (message "%d TODO entries found"
13052 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13054 (defun org-deadline (arg &optional time)
13055 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13056 With one universal prefix argument, remove any deadline from the item.
13057 With two universal prefix arguments, prompt for a warning delay.
13058 With argument TIME, set the deadline at the corresponding date. TIME
13059 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13060 (interactive "P")
13061 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13062 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13063 'region-start-level 'region))
13064 org-loop-over-headlines-in-active-region)
13065 (org-map-entries
13066 `(org-deadline ',arg ,time)
13067 org-loop-over-headlines-in-active-region
13068 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13069 (let* ((old-date (org-entry-get nil "DEADLINE"))
13070 (old-date-time (if old-date (org-time-string-to-time old-date)))
13071 (repeater (and old-date
13072 (string-match
13073 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13074 old-date)
13075 (match-string 1 old-date))))
13076 (cond
13077 ((equal arg '(4))
13078 (when (and old-date org-log-redeadline)
13079 (org-add-log-setup 'deldeadline nil old-date 'findpos
13080 org-log-redeadline))
13081 (org-remove-timestamp-with-keyword org-deadline-string)
13082 (message "Item no longer has a deadline."))
13083 ((equal arg '(16))
13084 (save-excursion
13085 (org-back-to-heading t)
13086 (if (re-search-forward
13087 org-deadline-time-regexp
13088 (save-excursion (outline-next-heading) (point)) t)
13089 (let* ((rpl0 (match-string 1))
13090 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13091 (replace-match
13092 (concat org-deadline-string
13093 " <" rpl
13094 (format " -%dd"
13095 (abs
13096 (- (time-to-days
13097 (save-match-data
13098 (org-read-date nil t nil "Warn starting from" old-date-time)))
13099 (time-to-days old-date-time))))
13100 ">") t t))
13101 (user-error "No deadline information to update"))))
13103 (org-add-planning-info 'deadline time 'closed)
13104 (when (and old-date org-log-redeadline
13105 (not (equal old-date
13106 (substring org-last-inserted-timestamp 1 -1))))
13107 (org-add-log-setup 'redeadline nil old-date 'findpos
13108 org-log-redeadline))
13109 (when repeater
13110 (save-excursion
13111 (org-back-to-heading t)
13112 (when (re-search-forward (concat org-deadline-string " "
13113 org-last-inserted-timestamp)
13114 (save-excursion
13115 (outline-next-heading) (point)) t)
13116 (goto-char (1- (match-end 0)))
13117 (insert " " repeater)
13118 (setq org-last-inserted-timestamp
13119 (concat (substring org-last-inserted-timestamp 0 -1)
13120 " " repeater
13121 (substring org-last-inserted-timestamp -1))))))
13122 (message "Deadline on %s" org-last-inserted-timestamp))))))
13124 (defun org-schedule (arg &optional time)
13125 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13126 With one universal prefix argument, remove any scheduling date from the item.
13127 With two universal prefix arguments, prompt for a delay cookie.
13128 With argument TIME, scheduled at the corresponding date. TIME can
13129 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13130 (interactive "P")
13131 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13132 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13133 'region-start-level 'region))
13134 org-loop-over-headlines-in-active-region)
13135 (org-map-entries
13136 `(org-schedule ',arg ,time)
13137 org-loop-over-headlines-in-active-region
13138 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13139 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13140 (old-date-time (if old-date (org-time-string-to-time old-date)))
13141 (repeater (and old-date
13142 (string-match
13143 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13144 old-date)
13145 (match-string 1 old-date))))
13146 (cond
13147 ((equal arg '(4))
13148 (progn
13149 (when (and old-date org-log-reschedule)
13150 (org-add-log-setup 'delschedule nil old-date 'findpos
13151 org-log-reschedule))
13152 (org-remove-timestamp-with-keyword org-scheduled-string)
13153 (message "Item is no longer scheduled.")))
13154 ((equal arg '(16))
13155 (save-excursion
13156 (org-back-to-heading t)
13157 (if (re-search-forward
13158 org-scheduled-time-regexp
13159 (save-excursion (outline-next-heading) (point)) t)
13160 (let* ((rpl0 (match-string 1))
13161 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13162 (replace-match
13163 (concat org-scheduled-string
13164 " <" rpl
13165 (format " -%dd"
13166 (abs
13167 (- (time-to-days
13168 (save-match-data
13169 (org-read-date nil t nil "Delay until" old-date-time)))
13170 (time-to-days old-date-time))))
13171 ">") t t))
13172 (user-error "No scheduled information to update"))))
13174 (org-add-planning-info 'scheduled time 'closed)
13175 (when (and old-date org-log-reschedule
13176 (not (equal old-date
13177 (substring org-last-inserted-timestamp 1 -1))))
13178 (org-add-log-setup 'reschedule nil old-date 'findpos
13179 org-log-reschedule))
13180 (when repeater
13181 (save-excursion
13182 (org-back-to-heading t)
13183 (when (re-search-forward (concat org-scheduled-string " "
13184 org-last-inserted-timestamp)
13185 (save-excursion
13186 (outline-next-heading) (point)) t)
13187 (goto-char (1- (match-end 0)))
13188 (insert " " repeater)
13189 (setq org-last-inserted-timestamp
13190 (concat (substring org-last-inserted-timestamp 0 -1)
13191 " " repeater
13192 (substring org-last-inserted-timestamp -1))))))
13193 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13195 (defun org-get-scheduled-time (pom &optional inherit)
13196 "Get the scheduled time as a time tuple, of a format suitable
13197 for calling org-schedule with, or if there is no scheduling,
13198 returns nil."
13199 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13200 (when time
13201 (apply 'encode-time (org-parse-time-string time)))))
13203 (defun org-get-deadline-time (pom &optional inherit)
13204 "Get the deadline as a time tuple, of a format suitable for
13205 calling org-deadline with, or if there is no scheduling, returns
13206 nil."
13207 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13208 (when time
13209 (apply 'encode-time (org-parse-time-string time)))))
13211 (defun org-remove-timestamp-with-keyword (keyword)
13212 "Remove all time stamps with KEYWORD in the current entry."
13213 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13214 beg)
13215 (save-excursion
13216 (org-back-to-heading t)
13217 (setq beg (point))
13218 (outline-next-heading)
13219 (while (re-search-backward re beg t)
13220 (replace-match "")
13221 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13222 (equal (char-before) ?\ ))
13223 (backward-delete-char 1)
13224 (if (string-match "^[ \t]*$" (buffer-substring
13225 (point-at-bol) (point-at-eol)))
13226 (delete-region (point-at-bol)
13227 (min (point-max) (1+ (point-at-eol))))))))))
13229 (defvar org-time-was-given) ; dynamically scoped parameter
13230 (defvar org-end-time-was-given) ; dynamically scoped parameter
13232 (defun org-add-planning-info (what &optional time &rest remove)
13233 "Insert new timestamp with keyword in the line directly after the headline.
13234 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13235 If non is given, the user is prompted for a date.
13236 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13237 be removed."
13238 (interactive)
13239 (let (org-time-was-given org-end-time-was-given ts
13240 end default-time default-input)
13242 (catch 'exit
13243 (when (and (memq what '(scheduled deadline))
13244 (or (not time)
13245 (and (stringp time)
13246 (string-match "^[-+]+[0-9]" time))))
13247 ;; Try to get a default date/time from existing timestamp
13248 (save-excursion
13249 (org-back-to-heading t)
13250 (setq end (save-excursion (outline-next-heading) (point)))
13251 (when (re-search-forward (if (eq what 'scheduled)
13252 org-scheduled-time-regexp
13253 org-deadline-time-regexp)
13254 end t)
13255 (setq ts (match-string 1)
13256 default-time
13257 (apply 'encode-time (org-parse-time-string ts))
13258 default-input (and ts (org-get-compact-tod ts))))))
13259 (when what
13260 (setq time
13261 (if (stringp time)
13262 ;; This is a string (relative or absolute), set proper date
13263 (apply 'encode-time
13264 (org-read-date-analyze
13265 time default-time (decode-time default-time)))
13266 ;; If necessary, get the time from the user
13267 (or time (org-read-date nil 'to-time nil nil
13268 default-time default-input)))))
13270 (when (and org-insert-labeled-timestamps-at-point
13271 (member what '(scheduled deadline)))
13272 (insert
13273 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13274 (org-insert-time-stamp time org-time-was-given
13275 nil nil nil (list org-end-time-was-given))
13276 (setq what nil))
13277 (save-excursion
13278 (save-restriction
13279 (let (col list elt ts buffer-invisibility-spec)
13280 (org-back-to-heading t)
13281 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13282 (goto-char (match-end 1))
13283 (setq col (current-column))
13284 (goto-char (match-end 0))
13285 (if (eobp) (insert "\n") (forward-char 1))
13286 (when (and (not what)
13287 (not (looking-at
13288 (concat "[ \t]*"
13289 org-keyword-time-not-clock-regexp))))
13290 ;; Nothing to add, nothing to remove...... :-)
13291 (throw 'exit nil))
13292 (if (and (not (looking-at org-outline-regexp))
13293 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13294 "[^\r\n]*"))
13295 (not (equal (match-string 1) org-clock-string)))
13296 (narrow-to-region (match-beginning 0) (match-end 0))
13297 (insert-before-markers "\n")
13298 (backward-char 1)
13299 (narrow-to-region (point) (point))
13300 (and org-adapt-indentation (org-indent-to-column col)))
13301 ;; Check if we have to remove something.
13302 (setq list (cons what remove))
13303 (while list
13304 (setq elt (pop list))
13305 (when (or (and (eq elt 'scheduled)
13306 (re-search-forward org-scheduled-time-regexp nil t))
13307 (and (eq elt 'deadline)
13308 (re-search-forward org-deadline-time-regexp nil t))
13309 (and (eq elt 'closed)
13310 (re-search-forward org-closed-time-regexp nil t)))
13311 (replace-match "")
13312 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13313 (and (looking-at "[ \t]+") (replace-match ""))
13314 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13315 (when what
13316 (insert
13317 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13318 (cond ((eq what 'scheduled) org-scheduled-string)
13319 ((eq what 'deadline) org-deadline-string)
13320 ((eq what 'closed) org-closed-string))
13321 " ")
13322 (setq ts (org-insert-time-stamp
13323 time
13324 (or org-time-was-given
13325 (and (eq what 'closed) org-log-done-with-time))
13326 (eq what 'closed)
13327 nil nil (list org-end-time-was-given)))
13328 (insert
13329 (if (not (or (bolp) (eq (char-before) ?\ )
13330 (memq (char-after) '(32 10))
13331 (eobp))) " " ""))
13332 (end-of-line 1))
13333 (goto-char (point-min))
13334 (widen)
13335 (if (and (looking-at "[ \t]*\n")
13336 (equal (char-before) ?\n))
13337 (delete-region (1- (point)) (point-at-eol)))
13338 ts))))))
13340 (defvar org-log-note-marker (make-marker))
13341 (defvar org-log-note-purpose nil)
13342 (defvar org-log-note-state nil)
13343 (defvar org-log-note-previous-state nil)
13344 (defvar org-log-note-how nil)
13345 (defvar org-log-note-extra nil)
13346 (defvar org-log-note-window-configuration nil)
13347 (defvar org-log-note-return-to (make-marker))
13348 (defvar org-log-note-effective-time nil
13349 "Remembered current time so that dynamically scoped
13350 `org-extend-today-until' affects tha timestamps in state change
13351 log")
13353 (defvar org-log-post-message nil
13354 "Message to be displayed after a log note has been stored.
13355 The auto-repeater uses this.")
13357 (defun org-add-note ()
13358 "Add a note to the current entry.
13359 This is done in the same way as adding a state change note."
13360 (interactive)
13361 (org-add-log-setup 'note nil nil 'findpos nil))
13363 (defvar org-property-end-re)
13364 (defun org-add-log-setup (&optional purpose state prev-state
13365 findpos how extra)
13366 "Set up the post command hook to take a note.
13367 If this is about to TODO state change, the new state is expected in STATE.
13368 When FINDPOS is non-nil, find the correct position for the note in
13369 the current entry. If not, assume that it can be inserted at point.
13370 HOW is an indicator what kind of note should be created.
13371 EXTRA is additional text that will be inserted into the notes buffer."
13372 (let* ((org-log-into-drawer (org-log-into-drawer))
13373 (drawer (cond ((stringp org-log-into-drawer)
13374 org-log-into-drawer)
13375 (org-log-into-drawer "LOGBOOK"))))
13376 (save-restriction
13377 (save-excursion
13378 (when findpos
13379 (org-back-to-heading t)
13380 (narrow-to-region (point) (save-excursion
13381 (outline-next-heading) (point)))
13382 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13383 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13384 "[^\r\n]*\\)?"))
13385 (goto-char (match-end 0))
13386 (cond
13387 (drawer
13388 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13389 nil t)
13390 (progn
13391 (goto-char (match-end 0))
13392 (or org-log-states-order-reversed
13393 (and (re-search-forward org-property-end-re nil t)
13394 (goto-char (1- (match-beginning 0))))))
13395 (insert "\n:" drawer ":\n:END:")
13396 (beginning-of-line 0)
13397 (org-indent-line)
13398 (beginning-of-line 2)
13399 (org-indent-line)
13400 (end-of-line 0)))
13401 ((and org-log-state-notes-insert-after-drawers
13402 (save-excursion
13403 (forward-line) (looking-at org-drawer-regexp)))
13404 (forward-line)
13405 (while (looking-at org-drawer-regexp)
13406 (goto-char (match-end 0))
13407 (re-search-forward org-property-end-re (point-max) t)
13408 (forward-line))
13409 (forward-line -1)))
13410 (unless org-log-states-order-reversed
13411 (and (= (char-after) ?\n) (forward-char 1))
13412 (org-skip-over-state-notes)
13413 (skip-chars-backward " \t\n\r")))
13414 (move-marker org-log-note-marker (point))
13415 (setq org-log-note-purpose purpose
13416 org-log-note-state state
13417 org-log-note-previous-state prev-state
13418 org-log-note-how how
13419 org-log-note-extra extra
13420 org-log-note-effective-time (org-current-effective-time))
13421 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13423 (defun org-skip-over-state-notes ()
13424 "Skip past the list of State notes in an entry."
13425 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13426 (when (ignore-errors (goto-char (org-in-item-p)))
13427 (let* ((struct (org-list-struct))
13428 (prevs (org-list-prevs-alist struct)))
13429 (while (looking-at "[ \t]*- State")
13430 (goto-char (or (org-list-get-next-item (point) struct prevs)
13431 (org-list-get-item-end (point) struct)))))))
13433 (defun org-add-log-note (&optional purpose)
13434 "Pop up a window for taking a note, and add this note later at point."
13435 (remove-hook 'post-command-hook 'org-add-log-note)
13436 (setq org-log-note-window-configuration (current-window-configuration))
13437 (delete-other-windows)
13438 (move-marker org-log-note-return-to (point))
13439 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13440 (goto-char org-log-note-marker)
13441 (org-switch-to-buffer-other-window "*Org Note*")
13442 (erase-buffer)
13443 (if (memq org-log-note-how '(time state))
13444 (let (current-prefix-arg) (org-store-log-note))
13445 (let ((org-inhibit-startup t)) (org-mode))
13446 (insert (format "# Insert note for %s.
13447 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13448 (cond
13449 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13450 ((eq org-log-note-purpose 'done) "closed todo item")
13451 ((eq org-log-note-purpose 'state)
13452 (format "state change from \"%s\" to \"%s\""
13453 (or org-log-note-previous-state "")
13454 (or org-log-note-state "")))
13455 ((eq org-log-note-purpose 'reschedule)
13456 "rescheduling")
13457 ((eq org-log-note-purpose 'delschedule)
13458 "no longer scheduled")
13459 ((eq org-log-note-purpose 'redeadline)
13460 "changing deadline")
13461 ((eq org-log-note-purpose 'deldeadline)
13462 "removing deadline")
13463 ((eq org-log-note-purpose 'refile)
13464 "refiling")
13465 ((eq org-log-note-purpose 'note)
13466 "this entry")
13467 (t (error "This should not happen")))))
13468 (if org-log-note-extra (insert org-log-note-extra))
13469 (org-set-local 'org-finish-function 'org-store-log-note)
13470 (run-hooks 'org-log-buffer-setup-hook)))
13472 (defvar org-note-abort nil) ; dynamically scoped
13473 (defun org-store-log-note ()
13474 "Finish taking a log note, and insert it to where it belongs."
13475 (let ((txt (buffer-string)))
13476 (kill-buffer (current-buffer))
13477 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13478 lines ind bul)
13479 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13480 (setq txt (replace-match "" t t txt)))
13481 (if (string-match "\\s-+\\'" txt)
13482 (setq txt (replace-match "" t t txt)))
13483 (setq lines (org-split-string txt "\n"))
13484 (when (and note (string-match "\\S-" note))
13485 (setq note
13486 (org-replace-escapes
13487 note
13488 (list (cons "%u" (user-login-name))
13489 (cons "%U" user-full-name)
13490 (cons "%t" (format-time-string
13491 (org-time-stamp-format 'long 'inactive)
13492 org-log-note-effective-time))
13493 (cons "%T" (format-time-string
13494 (org-time-stamp-format 'long nil)
13495 org-log-note-effective-time))
13496 (cons "%d" (format-time-string
13497 (org-time-stamp-format nil 'inactive)
13498 org-log-note-effective-time))
13499 (cons "%D" (format-time-string
13500 (org-time-stamp-format nil nil)
13501 org-log-note-effective-time))
13502 (cons "%s" (if org-log-note-state
13503 (concat "\"" org-log-note-state "\"")
13504 ""))
13505 (cons "%S" (if org-log-note-previous-state
13506 (concat "\"" org-log-note-previous-state "\"")
13507 "\"\"")))))
13508 (if lines (setq note (concat note " \\\\")))
13509 (push note lines))
13510 (when (or current-prefix-arg org-note-abort)
13511 (when org-log-into-drawer
13512 (org-remove-empty-drawer-at org-log-note-marker))
13513 (setq lines nil))
13514 (when lines
13515 (with-current-buffer (marker-buffer org-log-note-marker)
13516 (save-excursion
13517 (goto-char org-log-note-marker)
13518 (move-marker org-log-note-marker nil)
13519 (end-of-line 1)
13520 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13521 (setq ind (save-excursion
13522 (if (ignore-errors (goto-char (org-in-item-p)))
13523 (let ((struct (org-list-struct)))
13524 (org-list-get-ind
13525 (org-list-get-top-point struct) struct))
13526 (skip-chars-backward " \r\t\n")
13527 (cond
13528 ((and (org-at-heading-p)
13529 org-adapt-indentation)
13530 (1+ (org-current-level)))
13531 ((org-at-heading-p) 0)
13532 (t (org-get-indentation))))))
13533 (setq bul (org-list-bullet-string "-"))
13534 (org-indent-line-to ind)
13535 (insert bul (pop lines))
13536 (let ((ind-body (+ (length bul) ind)))
13537 (while lines
13538 (insert "\n")
13539 (org-indent-line-to ind-body)
13540 (insert (pop lines))))
13541 (message "Note stored")
13542 (org-back-to-heading t)
13543 (org-cycle-hide-drawers 'children))
13544 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13545 ;; from within `org-add-log-note' because `buffer-undo-list'
13546 ;; is then modified outside of `org-with-remote-undo'.
13547 (when (eq this-command 'org-agenda-todo)
13548 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13549 ;; Don't add undo information when called from `org-agenda-todo'
13550 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13551 (set-window-configuration org-log-note-window-configuration)
13552 (with-current-buffer (marker-buffer org-log-note-return-to)
13553 (goto-char org-log-note-return-to))
13554 (move-marker org-log-note-return-to nil)
13555 (and org-log-post-message (message "%s" org-log-post-message))))
13557 (defun org-remove-empty-drawer-at (pos)
13558 "Remove an empty drawer at position POS.
13559 POS may also be a marker."
13560 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13561 (org-with-wide-buffer
13562 (goto-char pos)
13563 (let ((drawer (org-element-at-point)))
13564 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13565 (not (org-element-property :contents-begin drawer)))
13566 (delete-region (org-element-property :begin drawer)
13567 (progn (goto-char (org-element-property :end drawer))
13568 (skip-chars-backward " \r\t\n")
13569 (forward-line)
13570 (point))))))))
13572 (defvar org-ts-type nil)
13573 (defun org-sparse-tree (&optional arg type)
13574 "Create a sparse tree, prompt for the details.
13575 This command can create sparse trees. You first need to select the type
13576 of match used to create the tree:
13578 t Show all TODO entries.
13579 T Show entries with a specific TODO keyword.
13580 m Show entries selected by a tags/property match.
13581 p Enter a property name and its value (both with completion on existing
13582 names/values) and show entries with that property.
13583 r Show entries matching a regular expression (`/' can be used as well).
13584 b Show deadlines and scheduled items before a date.
13585 a Show deadlines and scheduled items after a date.
13586 d Show deadlines due within `org-deadline-warning-days'.
13587 D Show deadlines and scheduled items between a date range."
13588 (interactive "P")
13589 (let (ans kwd value ts-type)
13590 (setq type (or type org-sparse-tree-default-date-type))
13591 (setq org-ts-type type)
13592 (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"
13593 (cond ((eq type 'all) "all timestamps")
13594 ((eq type 'scheduled) "only scheduled")
13595 ((eq type 'deadline) "only deadline")
13596 ((eq type 'active) "only active timestamps")
13597 ((eq type 'inactive) "only inactive timestamps")
13598 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13599 ((eq type 'closed) "with a closed time-stamp")
13600 (t "scheduled/deadline")))
13601 (setq ans (read-char-exclusive))
13602 (cond
13603 ((equal ans ?c)
13604 (org-sparse-tree
13605 arg (cadr (member type '(scheduled-or-deadline
13606 all scheduled deadline active inactive closed)))))
13607 ((equal ans ?d)
13608 (call-interactively 'org-check-deadlines))
13609 ((equal ans ?b)
13610 (call-interactively 'org-check-before-date))
13611 ((equal ans ?a)
13612 (call-interactively 'org-check-after-date))
13613 ((equal ans ?D)
13614 (call-interactively 'org-check-dates-range))
13615 ((equal ans ?t)
13616 (call-interactively 'org-show-todo-tree))
13617 ((equal ans ?T)
13618 (org-show-todo-tree '(4)))
13619 ((member ans '(?T ?m))
13620 (call-interactively 'org-match-sparse-tree))
13621 ((member ans '(?p ?P))
13622 (setq kwd (org-icompleting-read "Property: "
13623 (mapcar 'list (org-buffer-property-keys))))
13624 (setq value (org-icompleting-read "Value: "
13625 (mapcar 'list (org-property-values kwd))))
13626 (unless (string-match "\\`{.*}\\'" value)
13627 (setq value (concat "\"" value "\"")))
13628 (org-match-sparse-tree arg (concat kwd "=" value)))
13629 ((member ans '(?r ?R ?/))
13630 (call-interactively 'org-occur))
13631 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13633 (defvar org-occur-highlights nil
13634 "List of overlays used for occur matches.")
13635 (make-variable-buffer-local 'org-occur-highlights)
13636 (defvar org-occur-parameters nil
13637 "Parameters of the active org-occur calls.
13638 This is a list, each call to org-occur pushes as cons cell,
13639 containing the regular expression and the callback, onto the list.
13640 The list can contain several entries if `org-occur' has been called
13641 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13642 will only contain one set of parameters. When the highlights are
13643 removed (for example with `C-c C-c', or with the next edit (depending
13644 on `org-remove-highlights-with-change'), this variable is emptied
13645 as well.")
13646 (make-variable-buffer-local 'org-occur-parameters)
13648 (defun org-occur (regexp &optional keep-previous callback)
13649 "Make a compact tree which shows all matches of REGEXP.
13650 The tree will show the lines where the regexp matches, and all higher
13651 headlines above the match. It will also show the heading after the match,
13652 to make sure editing the matching entry is easy.
13653 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13654 call to `org-occur' will be kept, to allow stacking of calls to this
13655 command.
13656 If CALLBACK is non-nil, it is a function which is called to confirm
13657 that the match should indeed be shown."
13658 (interactive "sRegexp: \nP")
13659 (when (equal regexp "")
13660 (user-error "Regexp cannot be empty"))
13661 (unless keep-previous
13662 (org-remove-occur-highlights nil nil t))
13663 (push (cons regexp callback) org-occur-parameters)
13664 (let ((cnt 0))
13665 (save-excursion
13666 (goto-char (point-min))
13667 (if (or (not keep-previous) ; do not want to keep
13668 (not org-occur-highlights)) ; no previous matches
13669 ;; hide everything
13670 (org-overview))
13671 (while (re-search-forward regexp nil t)
13672 (when (or (not callback)
13673 (save-match-data (funcall callback)))
13674 (setq cnt (1+ cnt))
13675 (when org-highlight-sparse-tree-matches
13676 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13677 (org-show-context 'occur-tree))))
13678 (when org-remove-highlights-with-change
13679 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13680 nil 'local))
13681 (unless org-sparse-tree-open-archived-trees
13682 (org-hide-archived-subtrees (point-min) (point-max)))
13683 (run-hooks 'org-occur-hook)
13684 (if (org-called-interactively-p 'interactive)
13685 (message "%d match(es) for regexp %s" cnt regexp))
13686 cnt))
13688 (defun org-occur-next-match (&optional n reset)
13689 "Function for `next-error-function' to find sparse tree matches.
13690 N is the number of matches to move, when negative move backwards.
13691 RESET is entirely ignored - this function always goes back to the
13692 starting point when no match is found."
13693 (let* ((limit (if (< n 0) (point-min) (point-max)))
13694 (search-func (if (< n 0)
13695 'previous-single-char-property-change
13696 'next-single-char-property-change))
13697 (n (abs n))
13698 (pos (point))
13700 (catch 'exit
13701 (while (setq p1 (funcall search-func (point) 'org-type))
13702 (when (equal p1 limit)
13703 (goto-char pos)
13704 (error "No more matches"))
13705 (when (equal (get-char-property p1 'org-type) 'org-occur)
13706 (setq n (1- n))
13707 (when (= n 0)
13708 (goto-char p1)
13709 (throw 'exit (point))))
13710 (goto-char p1))
13711 (goto-char p1)
13712 (error "No more matches"))))
13714 (defun org-show-context (&optional key)
13715 "Make sure point and context are visible.
13716 How much context is shown depends upon the variables
13717 `org-show-hierarchy-above', `org-show-following-heading',
13718 `org-show-entry-below' and `org-show-siblings'."
13719 (let ((heading-p (org-at-heading-p t))
13720 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13721 (following-p (org-get-alist-option org-show-following-heading key))
13722 (entry-p (org-get-alist-option org-show-entry-below key))
13723 (siblings-p (org-get-alist-option org-show-siblings key)))
13724 ;; Show heading or entry text
13725 (if (and heading-p (not entry-p))
13726 (org-flag-heading nil) ; only show the heading
13727 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13728 (org-show-hidden-entry))) ; show entire entry
13729 (when following-p
13730 ;; Show next sibling, or heading below text
13731 (save-excursion
13732 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13733 (org-flag-heading nil))))
13734 (when siblings-p (org-show-siblings))
13735 (when hierarchy-p
13736 ;; show all higher headings, possibly with siblings
13737 (save-excursion
13738 (while (and (condition-case nil
13739 (progn (org-up-heading-all 1) t)
13740 (error nil))
13741 (not (bobp)))
13742 (org-flag-heading nil)
13743 (when siblings-p (org-show-siblings)))))
13744 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13746 (defvar org-reveal-start-hook nil
13747 "Hook run before revealing a location.")
13749 (defun org-reveal (&optional siblings)
13750 "Show current entry, hierarchy above it, and the following headline.
13751 This can be used to show a consistent set of context around locations
13752 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13753 not t for the search context.
13755 With optional argument SIBLINGS, on each level of the hierarchy all
13756 siblings are shown. This repairs the tree structure to what it would
13757 look like when opened with hierarchical calls to `org-cycle'.
13758 With double optional argument \\[universal-argument] \\[universal-argument], \
13759 go to the parent and show the
13760 entire tree."
13761 (interactive "P")
13762 (run-hooks 'org-reveal-start-hook)
13763 (let ((org-show-hierarchy-above t)
13764 (org-show-following-heading t)
13765 (org-show-siblings (if siblings t org-show-siblings)))
13766 (org-show-context nil))
13767 (when (equal siblings '(16))
13768 (save-excursion
13769 (when (org-up-heading-safe)
13770 (org-show-subtree)
13771 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13773 (defun org-highlight-new-match (beg end)
13774 "Highlight from BEG to END and mark the highlight is an occur headline."
13775 (let ((ov (make-overlay beg end)))
13776 (overlay-put ov 'face 'secondary-selection)
13777 (overlay-put ov 'org-type 'org-occur)
13778 (push ov org-occur-highlights)))
13780 (defun org-remove-occur-highlights (&optional beg end noremove)
13781 "Remove the occur highlights from the buffer.
13782 BEG and END are ignored. If NOREMOVE is nil, remove this function
13783 from the `before-change-functions' in the current buffer."
13784 (interactive)
13785 (unless org-inhibit-highlight-removal
13786 (mapc 'delete-overlay org-occur-highlights)
13787 (setq org-occur-highlights nil)
13788 (setq org-occur-parameters nil)
13789 (unless noremove
13790 (remove-hook 'before-change-functions
13791 'org-remove-occur-highlights 'local))))
13793 ;;;; Priorities
13795 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13796 "Regular expression matching the priority indicator.")
13798 (defvar org-remove-priority-next-time nil)
13800 (defun org-priority-up ()
13801 "Increase the priority of the current item."
13802 (interactive)
13803 (org-priority 'up))
13805 (defun org-priority-down ()
13806 "Decrease the priority of the current item."
13807 (interactive)
13808 (org-priority 'down))
13810 (defun org-priority (&optional action show)
13811 "Change the priority of an item.
13812 ACTION can be `set', `up', `down', or a character."
13813 (interactive "P")
13814 (if (equal action '(4))
13815 (org-show-priority)
13816 (unless org-enable-priority-commands
13817 (user-error "Priority commands are disabled"))
13818 (setq action (or action 'set))
13819 (let (current new news have remove)
13820 (save-excursion
13821 (org-back-to-heading t)
13822 (if (looking-at org-priority-regexp)
13823 (setq current (string-to-char (match-string 2))
13824 have t))
13825 (cond
13826 ((eq action 'remove)
13827 (setq remove t new ?\ ))
13828 ((or (eq action 'set)
13829 (if (featurep 'xemacs) (characterp action) (integerp action)))
13830 (if (not (eq action 'set))
13831 (setq new action)
13832 (message "Priority %c-%c, SPC to remove: "
13833 org-highest-priority org-lowest-priority)
13834 (save-match-data
13835 (setq new (read-char-exclusive))))
13836 (if (and (= (upcase org-highest-priority) org-highest-priority)
13837 (= (upcase org-lowest-priority) org-lowest-priority))
13838 (setq new (upcase new)))
13839 (cond ((equal new ?\ ) (setq remove t))
13840 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13841 (user-error "Priority must be between `%c' and `%c'"
13842 org-highest-priority org-lowest-priority))))
13843 ((eq action 'up)
13844 (setq new (if have
13845 (1- current) ; normal cycling
13846 ;; last priority was empty
13847 (if (eq last-command this-command)
13848 org-lowest-priority ; wrap around empty to lowest
13849 ;; default
13850 (if org-priority-start-cycle-with-default
13851 org-default-priority
13852 (1- org-default-priority))))))
13853 ((eq action 'down)
13854 (setq new (if have
13855 (1+ current) ; normal cycling
13856 ;; last priority was empty
13857 (if (eq last-command this-command)
13858 org-highest-priority ; wrap around empty to highest
13859 ;; default
13860 (if org-priority-start-cycle-with-default
13861 org-default-priority
13862 (1+ org-default-priority))))))
13863 (t (user-error "Invalid action")))
13864 (if (or (< (upcase new) org-highest-priority)
13865 (> (upcase new) org-lowest-priority))
13866 (if (and (memq action '(up down))
13867 (not have) (not (eq last-command this-command)))
13868 ;; `new' is from default priority
13869 (error
13870 "The default can not be set, see `org-default-priority' why")
13871 ;; normal cycling: `new' is beyond highest/lowest priority
13872 ;; and is wrapped around to the empty priority
13873 (setq remove t)))
13874 (setq news (format "%c" new))
13875 (if have
13876 (if remove
13877 (replace-match "" t t nil 1)
13878 (replace-match news t t nil 2))
13879 (if remove
13880 (user-error "No priority cookie found in line")
13881 (let ((case-fold-search nil))
13882 (looking-at org-todo-line-regexp))
13883 (if (match-end 2)
13884 (progn
13885 (goto-char (match-end 2))
13886 (insert " [#" news "]"))
13887 (goto-char (match-beginning 3))
13888 (insert "[#" news "] "))))
13889 (org-set-tags nil 'align))
13890 (if remove
13891 (message "Priority removed")
13892 (message "Priority of current item set to %s" news)))))
13894 (defun org-show-priority ()
13895 "Show the priority of the current item.
13896 This priority is composed of the main priority given with the [#A] cookies,
13897 and by additional input from the age of a schedules or deadline entry."
13898 (interactive)
13899 (let ((pri (if (eq major-mode 'org-agenda-mode)
13900 (org-get-at-bol 'priority)
13901 (save-excursion
13902 (save-match-data
13903 (beginning-of-line)
13904 (and (looking-at org-heading-regexp)
13905 (org-get-priority (match-string 0))))))))
13906 (message "Priority is %d" (if pri pri -1000))))
13908 (defun org-get-priority (s)
13909 "Find priority cookie and return priority."
13910 (save-match-data
13911 (if (functionp org-get-priority-function)
13912 (funcall org-get-priority-function)
13913 (if (not (string-match org-priority-regexp s))
13914 (* 1000 (- org-lowest-priority org-default-priority))
13915 (* 1000 (- org-lowest-priority
13916 (string-to-char (match-string 2 s))))))))
13918 ;;;; Tags
13920 (defvar org-agenda-archives-mode)
13921 (defvar org-map-continue-from nil
13922 "Position from where mapping should continue.
13923 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13925 (defvar org-scanner-tags nil
13926 "The current tag list while the tags scanner is running.")
13927 (defvar org-trust-scanner-tags nil
13928 "Should `org-get-tags-at' use the tags for the scanner.
13929 This is for internal dynamical scoping only.
13930 When this is non-nil, the function `org-get-tags-at' will return the value
13931 of `org-scanner-tags' instead of building the list by itself. This
13932 can lead to large speed-ups when the tags scanner is used in a file with
13933 many entries, and when the list of tags is retrieved, for example to
13934 obtain a list of properties. Building the tags list for each entry in such
13935 a file becomes an N^2 operation - but with this variable set, it scales
13936 as N.")
13938 (defun org-scan-tags (action matcher todo-only &optional start-level)
13939 "Sca headline tags with inheritance and produce output ACTION.
13941 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13942 or `agenda' to produce an entry list for an agenda view. It can also be
13943 a Lisp form or a function that should be called at each matched headline, in
13944 this case the return value is a list of all return values from these calls.
13946 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13947 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13948 only lines with a not-done TODO keyword are included in the output.
13949 This should be the same variable that was scoped into
13950 and set by `org-make-tags-matcher' when it constructed MATCHER.
13952 START-LEVEL can be a string with asterisks, reducing the scope to
13953 headlines matching this string."
13954 (require 'org-agenda)
13955 (let* ((re (concat "^"
13956 (if start-level
13957 ;; Get the correct level to match
13958 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13959 org-outline-regexp)
13960 " *\\(\\<\\("
13961 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13962 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13963 (props (list 'face 'default
13964 'done-face 'org-agenda-done
13965 'undone-face 'default
13966 'mouse-face 'highlight
13967 'org-not-done-regexp org-not-done-regexp
13968 'org-todo-regexp org-todo-regexp
13969 'org-complex-heading-regexp org-complex-heading-regexp
13970 'help-echo
13971 (format "mouse-2 or RET jump to org file %s"
13972 (abbreviate-file-name
13973 (or (buffer-file-name (buffer-base-buffer))
13974 (buffer-name (buffer-base-buffer)))))))
13975 (org-map-continue-from nil)
13976 lspos tags tags-list
13977 (tags-alist (list (cons 0 org-file-tags)))
13978 (llast 0) rtn rtn1 level category i txt
13979 todo marker entry priority)
13980 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13981 (setq action (list 'lambda nil action)))
13982 (save-excursion
13983 (goto-char (point-min))
13984 (when (eq action 'sparse-tree)
13985 (org-overview)
13986 (org-remove-occur-highlights))
13987 (while (let (case-fold-search)
13988 (re-search-forward re nil t))
13989 (setq org-map-continue-from nil)
13990 (catch :skip
13991 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13992 tags (if (match-end 4) (org-match-string-no-properties 4)))
13993 (goto-char (setq lspos (match-beginning 0)))
13994 (setq level (org-reduced-level (org-outline-level))
13995 category (org-get-category))
13996 (setq i llast llast level)
13997 ;; remove tag lists from same and sublevels
13998 (while (>= i level)
13999 (when (setq entry (assoc i tags-alist))
14000 (setq tags-alist (delete entry tags-alist)))
14001 (setq i (1- i)))
14002 ;; add the next tags
14003 (when tags
14004 (setq tags (org-split-string tags ":")
14005 tags-alist
14006 (cons (cons level tags) tags-alist)))
14007 ;; compile tags for current headline
14008 (setq tags-list
14009 (if org-use-tag-inheritance
14010 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14011 tags)
14012 org-scanner-tags tags-list)
14013 (when org-use-tag-inheritance
14014 (setcdr (car tags-alist)
14015 (mapcar (lambda (x)
14016 (setq x (copy-sequence x))
14017 (org-add-prop-inherited x))
14018 (cdar tags-alist))))
14019 (when (and tags org-use-tag-inheritance
14020 (or (not (eq t org-use-tag-inheritance))
14021 org-tags-exclude-from-inheritance))
14022 ;; selective inheritance, remove uninherited ones
14023 (setcdr (car tags-alist)
14024 (org-remove-uninherited-tags (cdar tags-alist))))
14025 (when (and
14027 ;; eval matcher only when the todo condition is OK
14028 (and (or (not todo-only) (member todo org-not-done-keywords))
14029 (let ((case-fold-search t) (org-trust-scanner-tags t))
14030 (eval matcher)))
14032 ;; Call the skipper, but return t if it does not skip,
14033 ;; so that the `and' form continues evaluating
14034 (progn
14035 (unless (eq action 'sparse-tree) (org-agenda-skip))
14038 ;; Check if timestamps are deselecting this entry
14039 (or (not todo-only)
14040 (and (member todo org-not-done-keywords)
14041 (or (not org-agenda-tags-todo-honor-ignore-options)
14042 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14044 ;; select this headline
14045 (cond
14046 ((eq action 'sparse-tree)
14047 (and org-highlight-sparse-tree-matches
14048 (org-get-heading) (match-end 0)
14049 (org-highlight-new-match
14050 (match-beginning 1) (match-end 1)))
14051 (org-show-context 'tags-tree))
14052 ((eq action 'agenda)
14053 (setq txt (org-agenda-format-item
14055 (concat
14056 (if (eq org-tags-match-list-sublevels 'indented)
14057 (make-string (1- level) ?.) "")
14058 (org-get-heading))
14059 level category
14060 tags-list)
14061 priority (org-get-priority txt))
14062 (goto-char lspos)
14063 (setq marker (org-agenda-new-marker))
14064 (org-add-props txt props
14065 'org-marker marker 'org-hd-marker marker 'org-category category
14066 'todo-state todo
14067 'priority priority 'type "tagsmatch")
14068 (push txt rtn))
14069 ((functionp action)
14070 (setq org-map-continue-from nil)
14071 (save-excursion
14072 (setq rtn1 (funcall action))
14073 (push rtn1 rtn)))
14074 (t (user-error "Invalid action")))
14076 ;; if we are to skip sublevels, jump to end of subtree
14077 (unless org-tags-match-list-sublevels
14078 (org-end-of-subtree t)
14079 (backward-char 1))))
14080 ;; Get the correct position from where to continue
14081 (if org-map-continue-from
14082 (goto-char org-map-continue-from)
14083 (and (= (point) lspos) (end-of-line 1)))))
14084 (when (and (eq action 'sparse-tree)
14085 (not org-sparse-tree-open-archived-trees))
14086 (org-hide-archived-subtrees (point-min) (point-max)))
14087 (nreverse rtn)))
14089 (defun org-remove-uninherited-tags (tags)
14090 "Remove all tags that are not inherited from the list TAGS."
14091 (cond
14092 ((eq org-use-tag-inheritance t)
14093 (if org-tags-exclude-from-inheritance
14094 (org-delete-all org-tags-exclude-from-inheritance tags)
14095 tags))
14096 ((not org-use-tag-inheritance) nil)
14097 ((stringp org-use-tag-inheritance)
14098 (delq nil (mapcar
14099 (lambda (x)
14100 (if (and (string-match org-use-tag-inheritance x)
14101 (not (member x org-tags-exclude-from-inheritance)))
14102 x nil))
14103 tags)))
14104 ((listp org-use-tag-inheritance)
14105 (delq nil (mapcar
14106 (lambda (x)
14107 (if (member x org-use-tag-inheritance) x nil))
14108 tags)))))
14110 (defun org-match-sparse-tree (&optional todo-only match)
14111 "Create a sparse tree according to tags string MATCH.
14112 MATCH can contain positive and negative selection of tags, like
14113 \"+WORK+URGENT-WITHBOSS\".
14114 If optional argument TODO-ONLY is non-nil, only select lines that are
14115 also TODO lines."
14116 (interactive "P")
14117 (org-agenda-prepare-buffers (list (current-buffer)))
14118 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14120 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14122 (defvar org-cached-props nil)
14123 (defun org-cached-entry-get (pom property)
14124 (if (or (eq t org-use-property-inheritance)
14125 (and (stringp org-use-property-inheritance)
14126 (string-match org-use-property-inheritance property))
14127 (and (listp org-use-property-inheritance)
14128 (member property org-use-property-inheritance)))
14129 ;; Caching is not possible, check it directly
14130 (org-entry-get pom property 'inherit)
14131 ;; Get all properties, so that we can do complicated checks easily
14132 (cdr (assoc property (or org-cached-props
14133 (setq org-cached-props
14134 (org-entry-properties pom)))))))
14136 (defun org-global-tags-completion-table (&optional files)
14137 "Return the list of all tags in all agenda buffer/files.
14138 Optional FILES argument is a list of files which can be used
14139 instead of the agenda files."
14140 (save-excursion
14141 (org-uniquify
14142 (delq nil
14143 (apply 'append
14144 (mapcar
14145 (lambda (file)
14146 (set-buffer (find-file-noselect file))
14147 (append (org-get-buffer-tags)
14148 (mapcar (lambda (x) (if (stringp (car-safe x))
14149 (list (car-safe x)) nil))
14150 org-tag-alist)))
14151 (if (and files (car files))
14152 files
14153 (org-agenda-files))))))))
14155 (defun org-make-tags-matcher (match)
14156 "Create the TAGS/TODO matcher form for the selection string MATCH.
14158 The variable `todo-only' is scoped dynamically into this function.
14159 It will be set to t if the matcher restricts matching to TODO entries,
14160 otherwise will not be touched.
14162 Returns a cons of the selection string MATCH and the constructed
14163 lisp form implementing the matcher. The matcher is to be evaluated
14164 at an Org entry, with point on the headline, and returns t if the
14165 entry matches the selection string MATCH. The returned lisp form
14166 references two variables with information about the entry, which
14167 must be bound around the form's evaluation: todo, the TODO keyword
14168 at the entry (or nil of none); and tags-list, the list of all tags
14169 at the entry including inherited ones. Additionally, the category
14170 of the entry (if any) must be specified as the text property
14171 'org-category on the headline.
14173 See also `org-scan-tags'.
14175 (declare (special todo-only))
14176 (unless (boundp 'todo-only)
14177 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14178 (unless match
14179 ;; Get a new match request, with completion against the global
14180 ;; tags table and the local tags in current buffer
14181 (let ((org-last-tags-completion-table
14182 (org-uniquify
14183 (delq nil (append (org-get-buffer-tags)
14184 (org-global-tags-completion-table))))))
14185 (setq match (org-completing-read-no-i
14186 "Match: " 'org-tags-completion-function nil nil nil
14187 'org-tags-history))))
14189 ;; Parse the string and create a lisp form
14190 (let ((match0 match)
14191 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14192 minus tag mm
14193 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14194 orterms term orlist re-p str-p level-p level-op time-p
14195 prop-p pn pv po gv rest (start 0) (ss 0))
14196 ;; Expand group tags
14197 (setq match (org-tags-expand match))
14199 ;; Check if there is a TODO part of this match, which would be the
14200 ;; part after a "/". TO make sure that this slash is not part of
14201 ;; a property value to be matched against, we also check that there
14202 ;; is no " after that slash.
14203 ;; First, find the last slash
14204 (while (string-match "/+" match ss)
14205 (setq start (match-beginning 0) ss (match-end 0)))
14206 (if (and (string-match "/+" match start)
14207 (not (save-match-data (string-match "\"" match start))))
14208 ;; match contains also a todo-matching request
14209 (progn
14210 (setq tagsmatch (substring match 0 (match-beginning 0))
14211 todomatch (substring match (match-end 0)))
14212 (if (string-match "^!" todomatch)
14213 (setq todo-only t todomatch (substring todomatch 1)))
14214 (if (string-match "^\\s-*$" todomatch)
14215 (setq todomatch nil)))
14216 ;; only matching tags
14217 (setq tagsmatch match todomatch nil))
14219 ;; Make the tags matcher
14220 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14221 (setq tagsmatcher t)
14222 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14223 (while (setq term (pop orterms))
14224 (while (and (equal (substring term -1) "\\") orterms)
14225 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14226 (while (string-match re term)
14227 (setq rest (substring term (match-end 0))
14228 minus (and (match-end 1)
14229 (equal (match-string 1 term) "-"))
14230 tag (save-match-data (replace-regexp-in-string
14231 "\\\\-" "-"
14232 (match-string 2 term)))
14233 re-p (equal (string-to-char tag) ?{)
14234 level-p (match-end 4)
14235 prop-p (match-end 5)
14236 mm (cond
14237 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14238 (level-p
14239 (setq level-op (org-op-to-function (match-string 3 term)))
14240 `(,level-op level ,(string-to-number
14241 (match-string 4 term))))
14242 (prop-p
14243 (setq pn (match-string 5 term)
14244 po (match-string 6 term)
14245 pv (match-string 7 term)
14246 re-p (equal (string-to-char pv) ?{)
14247 str-p (equal (string-to-char pv) ?\")
14248 time-p (save-match-data
14249 (string-match "^\"[[<].*[]>]\"$" pv))
14250 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14251 (if time-p (setq pv (org-matcher-time pv)))
14252 (setq po (org-op-to-function po (if time-p 'time str-p)))
14253 (cond
14254 ((equal pn "CATEGORY")
14255 (setq gv '(get-text-property (point) 'org-category)))
14256 ((equal pn "TODO")
14257 (setq gv 'todo))
14259 (setq gv `(org-cached-entry-get nil ,pn))))
14260 (if re-p
14261 (if (eq po 'org<>)
14262 `(not (string-match ,pv (or ,gv "")))
14263 `(string-match ,pv (or ,gv "")))
14264 (if str-p
14265 `(,po (or ,gv "") ,pv)
14266 `(,po (string-to-number (or ,gv ""))
14267 ,(string-to-number pv) ))))
14268 (t `(member ,tag tags-list)))
14269 mm (if minus (list 'not mm) mm)
14270 term rest)
14271 (push mm tagsmatcher))
14272 (push (if (> (length tagsmatcher) 1)
14273 (cons 'and tagsmatcher)
14274 (car tagsmatcher))
14275 orlist)
14276 (setq tagsmatcher nil))
14277 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14278 (setq tagsmatcher
14279 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14280 ;; Make the todo matcher
14281 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14282 (setq todomatcher t)
14283 (setq orterms (org-split-string todomatch "|") orlist nil)
14284 (while (setq term (pop orterms))
14285 (while (string-match re term)
14286 (setq minus (and (match-end 1)
14287 (equal (match-string 1 term) "-"))
14288 kwd (match-string 2 term)
14289 re-p (equal (string-to-char kwd) ?{)
14290 term (substring term (match-end 0))
14291 mm (if re-p
14292 `(string-match ,(substring kwd 1 -1) todo)
14293 (list 'equal 'todo kwd))
14294 mm (if minus (list 'not mm) mm))
14295 (push mm todomatcher))
14296 (push (if (> (length todomatcher) 1)
14297 (cons 'and todomatcher)
14298 (car todomatcher))
14299 orlist)
14300 (setq todomatcher nil))
14301 (setq todomatcher (if (> (length orlist) 1)
14302 (cons 'or orlist) (car orlist))))
14304 ;; Return the string and lisp forms of the matcher
14305 (setq matcher (if todomatcher
14306 (list 'and tagsmatcher todomatcher)
14307 tagsmatcher))
14308 (when todo-only
14309 (setq matcher (list 'and '(member todo org-not-done-keywords)
14310 matcher)))
14311 (cons match0 matcher)))
14313 (defun org-tags-expand (match &optional single-as-list downcased)
14314 "Expand group tags in MATCH.
14316 This replaces every group tag in MATCH with a regexp tag search.
14317 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14318 will be replaced like this:
14320 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14321 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14322 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14324 Replacing by a regexp preserves the structure of the match.
14325 E.g., this expansion
14327 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14329 will match anything tagged with \"Lab\" and \"Home\", or tagged
14330 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14332 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14333 assumed to be a single group tag, and the function will return
14334 the list of tags in this group.
14336 When DOWNCASE is non-nil, expand downcased TAGS."
14337 (if org-group-tags
14338 (let* ((case-fold-search t)
14339 (stable org-mode-syntax-table)
14340 (tal (or org-tag-groups-alist-for-agenda
14341 org-tag-groups-alist))
14342 (tal (if downcased
14343 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14344 (tml (mapcar 'car tal))
14345 (rtnmatch match) rpl)
14346 ;; @ and _ are allowed as word-components in tags
14347 (modify-syntax-entry ?@ "w" stable)
14348 (modify-syntax-entry ?_ "w" stable)
14349 (while (and tml
14350 (with-syntax-table stable
14351 (string-match
14352 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14353 (regexp-opt tml) "\\>\\)") rtnmatch)))
14354 (let* ((dir (match-string 1 rtnmatch))
14355 (tag (match-string 2 rtnmatch))
14356 (tag (if downcased (downcase tag) tag)))
14357 (setq tml (delete tag tml))
14358 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14359 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14360 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14361 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14362 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14363 (if single-as-list
14364 (or (reverse rpl) (list rtnmatch))
14365 rtnmatch))
14366 (if single-as-list (list (if downcased (downcase match) match))
14367 match)))
14369 (defun org-op-to-function (op &optional stringp)
14370 "Turn an operator into the appropriate function."
14371 (setq op
14372 (cond
14373 ((equal op "<" ) '(< string< org-time<))
14374 ((equal op ">" ) '(> org-string> org-time>))
14375 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14376 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14377 ((member op '("=" "==")) '(= string= org-time=))
14378 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14379 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14381 (defun org<> (a b) (not (= a b)))
14382 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14383 (defun org-string>= (a b) (not (string< a b)))
14384 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14385 (defun org-string<> (a b) (not (string= 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) (< a b)))
14388 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14389 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14390 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14391 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14392 (defun org-2ft (s)
14393 "Convert S to a floating point time.
14394 If S is already a number, just return it. If it is a string, parse
14395 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14396 (cond
14397 ((numberp s) s)
14398 ((stringp s)
14399 (condition-case nil
14400 (float-time (apply 'encode-time (org-parse-time-string s)))
14401 (error 0.)))
14402 (t 0.)))
14404 (defun org-time-today ()
14405 "Time in seconds today at 0:00.
14406 Returns the float number of seconds since the beginning of the
14407 epoch to the beginning of today (00:00)."
14408 (float-time (apply 'encode-time
14409 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14411 (defun org-matcher-time (s)
14412 "Interpret a time comparison value."
14413 (save-match-data
14414 (cond
14415 ((string= s "<now>") (float-time))
14416 ((string= s "<today>") (org-time-today))
14417 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14418 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14419 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14420 (+ (org-time-today)
14421 (* (string-to-number (match-string 1 s))
14422 (cdr (assoc (match-string 2 s)
14423 '(("d" . 86400.0) ("w" . 604800.0)
14424 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14425 (t (org-2ft s)))))
14427 (defun org-match-any-p (re list)
14428 "Does re match any element of list?"
14429 (setq list (mapcar (lambda (x) (string-match re x)) list))
14430 (delq nil list))
14432 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14433 (defvar org-tags-overlay (make-overlay 1 1))
14434 (org-detach-overlay org-tags-overlay)
14436 (defun org-get-local-tags-at (&optional pos)
14437 "Get a list of tags defined in the current headline."
14438 (org-get-tags-at pos 'local))
14440 (defun org-get-local-tags ()
14441 "Get a list of tags defined in the current headline."
14442 (org-get-tags-at nil 'local))
14444 (defun org-get-tags-at (&optional pos local)
14445 "Get a list of all headline tags applicable at POS.
14446 POS defaults to point. If tags are inherited, the list contains
14447 the targets in the same sequence as the headlines appear, i.e.
14448 the tags of the current headline come last.
14449 When LOCAL is non-nil, only return tags from the current headline,
14450 ignore inherited ones."
14451 (interactive)
14452 (if (and org-trust-scanner-tags
14453 (or (not pos) (equal pos (point)))
14454 (not local))
14455 org-scanner-tags
14456 (let (tags ltags lastpos parent)
14457 (save-excursion
14458 (save-restriction
14459 (widen)
14460 (goto-char (or pos (point)))
14461 (save-match-data
14462 (catch 'done
14463 (condition-case nil
14464 (progn
14465 (org-back-to-heading t)
14466 (while (not (equal lastpos (point)))
14467 (setq lastpos (point))
14468 (when (looking-at
14469 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14470 (setq ltags (org-split-string
14471 (org-match-string-no-properties 1) ":"))
14472 (when parent
14473 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14474 (setq tags (append
14475 (if parent
14476 (org-remove-uninherited-tags ltags)
14477 ltags)
14478 tags)))
14479 (or org-use-tag-inheritance (throw 'done t))
14480 (if local (throw 'done t))
14481 (or (org-up-heading-safe) (error nil))
14482 (setq parent t)))
14483 (error nil)))))
14484 (if local
14485 tags
14486 (reverse (delete-dups
14487 (reverse (append
14488 (org-remove-uninherited-tags
14489 org-file-tags) tags)))))))))
14491 (defun org-add-prop-inherited (s)
14492 (add-text-properties 0 (length s) '(inherited t) s)
14495 (defun org-toggle-tag (tag &optional onoff)
14496 "Toggle the tag TAG for the current line.
14497 If ONOFF is `on' or `off', don't toggle but set to this state."
14498 (let (res current)
14499 (save-excursion
14500 (org-back-to-heading t)
14501 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14502 (point-at-eol) t)
14503 (progn
14504 (setq current (match-string 1))
14505 (replace-match ""))
14506 (setq current ""))
14507 (setq current (nreverse (org-split-string current ":")))
14508 (cond
14509 ((eq onoff 'on)
14510 (setq res t)
14511 (or (member tag current) (push tag current)))
14512 ((eq onoff 'off)
14513 (or (not (member tag current)) (setq current (delete tag current))))
14514 (t (if (member tag current)
14515 (setq current (delete tag current))
14516 (setq res t)
14517 (push tag current))))
14518 (end-of-line 1)
14519 (if current
14520 (progn
14521 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14522 (org-set-tags nil t))
14523 (delete-horizontal-space))
14524 (run-hooks 'org-after-tags-change-hook))
14525 res))
14527 (defun org-align-tags-here (to-col)
14528 ;; Assumes that this is a headline
14529 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14530 (beginning-of-line 1)
14531 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14532 (< pos (match-beginning 2)))
14533 (progn
14534 (setq tags-l (- (match-end 2) (match-beginning 2)))
14535 (goto-char (match-beginning 1))
14536 (insert " ")
14537 (delete-region (point) (1+ (match-beginning 2)))
14538 (setq ncol (max (current-column)
14539 (1+ col)
14540 (if (> to-col 0)
14541 to-col
14542 (- (abs to-col) tags-l))))
14543 (setq p (point))
14544 (insert (make-string (- ncol (current-column)) ?\ ))
14545 (setq ncol (current-column))
14546 (when indent-tabs-mode (tabify p (point-at-eol)))
14547 (org-move-to-column (min ncol col) t nil t))
14548 (goto-char pos))))
14550 (defun org-set-tags-command (&optional arg just-align)
14551 "Call the set-tags command for the current entry."
14552 (interactive "P")
14553 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14554 (org-set-tags arg just-align)
14555 (save-excursion
14556 (unless (and (org-region-active-p)
14557 org-loop-over-headlines-in-active-region)
14558 (org-back-to-heading t))
14559 (org-set-tags arg just-align))))
14561 (defun org-set-tags-to (data)
14562 "Set the tags of the current entry to DATA, replacing the current tags.
14563 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14564 If DATA is nil or the empty string, any tags will be removed."
14565 (interactive "sTags: ")
14566 (setq data
14567 (cond
14568 ((eq data nil) "")
14569 ((equal data "") "")
14570 ((stringp data)
14571 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14572 ":"))
14573 ((listp data)
14574 (concat ":" (mapconcat 'identity data ":") ":"))))
14575 (when data
14576 (save-excursion
14577 (org-back-to-heading t)
14578 (when (looking-at org-complex-heading-regexp)
14579 (if (match-end 5)
14580 (progn
14581 (goto-char (match-beginning 5))
14582 (insert data)
14583 (delete-region (point) (point-at-eol))
14584 (org-set-tags nil 'align))
14585 (goto-char (point-at-eol))
14586 (insert " " data)
14587 (org-set-tags nil 'align)))
14588 (beginning-of-line 1)
14589 (if (looking-at ".*?\\([ \t]+\\)$")
14590 (delete-region (match-beginning 1) (match-end 1))))))
14592 (defun org-align-all-tags ()
14593 "Align the tags i all headings."
14594 (interactive)
14595 (save-excursion
14596 (or (ignore-errors (org-back-to-heading t))
14597 (outline-next-heading))
14598 (if (org-at-heading-p)
14599 (org-set-tags t)
14600 (message "No headings"))))
14602 (defvar org-indent-indentation-per-level)
14603 (defun org-set-tags (&optional arg just-align)
14604 "Set the tags for the current headline.
14605 With prefix ARG, realign all tags in headings in the current buffer.
14606 When JUST-ALIGN is non-nil, only align tags.
14607 When JUST-ALIGN is 'ignore-column, align tags without trying to set
14608 the column by ignoring invisible text."
14609 (interactive "P")
14610 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14611 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14612 'region-start-level 'region))
14613 org-loop-over-headlines-in-active-region)
14614 (org-map-entries
14615 ;; We don't use ARG and JUST-ALIGN here because these args
14616 ;; are not useful when looping over headlines.
14617 `(org-set-tags)
14618 org-loop-over-headlines-in-active-region
14619 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14620 (let* ((re org-outline-regexp-bol)
14621 (current (unless arg (org-get-tags-string)))
14622 (col (current-column))
14623 (org-setting-tags t)
14624 table current-tags inherited-tags ; computed below when needed
14625 tags p0 c0 c1 rpl di tc level)
14626 (if arg
14627 (save-excursion
14628 (goto-char (point-min))
14629 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14630 (while (re-search-forward re nil t)
14631 (org-set-tags nil t)
14632 (end-of-line 1)))
14633 (message "All tags realigned to column %d" org-tags-column))
14634 (if just-align
14635 (setq tags current)
14636 ;; Get a new set of tags from the user
14637 (save-excursion
14638 (setq table (append org-tag-persistent-alist
14639 (or org-tag-alist (org-get-buffer-tags))
14640 (and
14641 org-complete-tags-always-offer-all-agenda-tags
14642 (org-global-tags-completion-table
14643 (org-agenda-files))))
14644 org-last-tags-completion-table table
14645 current-tags (org-split-string current ":")
14646 inherited-tags (nreverse
14647 (nthcdr (length current-tags)
14648 (nreverse (org-get-tags-at))))
14649 tags
14650 (if (or (eq t org-use-fast-tag-selection)
14651 (and org-use-fast-tag-selection
14652 (delq nil (mapcar 'cdr table))))
14653 (org-fast-tag-selection
14654 current-tags inherited-tags table
14655 (if org-fast-tag-selection-include-todo
14656 org-todo-key-alist))
14657 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14658 (org-trim
14659 (org-icompleting-read "Tags: "
14660 'org-tags-completion-function
14661 nil nil current 'org-tags-history))))))
14662 (while (string-match "[-+&]+" tags)
14663 ;; No boolean logic, just a list
14664 (setq tags (replace-match ":" t t tags))))
14666 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14668 (if org-tags-sort-function
14669 (setq tags (mapconcat 'identity
14670 (sort (org-split-string
14671 tags (org-re "[^[:alnum:]_@#%]+"))
14672 org-tags-sort-function) ":")))
14674 (if (string-match "\\`[\t ]*\\'" tags)
14675 (setq tags "")
14676 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14677 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14679 ;; Insert new tags at the correct column
14680 (beginning-of-line 1)
14681 (setq level (or (and (looking-at org-outline-regexp)
14682 (- (match-end 0) (point) 1))
14684 (cond
14685 ((and (equal current "") (equal tags "")))
14686 ((re-search-forward
14687 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14688 (point-at-eol) t)
14689 (if (equal tags "")
14690 (setq rpl "")
14691 (goto-char (match-beginning 0))
14692 (setq c0 (current-column)
14693 ;; compute offset for the case of org-indent-mode active
14694 di (if (org-bound-and-true-p org-indent-mode)
14695 (* (1- org-indent-indentation-per-level) (1- level))
14697 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14698 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14699 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14700 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14701 (replace-match rpl t t)
14702 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14703 tags)
14704 (t (error "Tags alignment failed")))
14705 (org-move-to-column col nil nil (not (eq just-align 'ignore-column)))
14706 (unless just-align
14707 (run-hooks 'org-after-tags-change-hook))))))
14709 (defun org-change-tag-in-region (beg end tag off)
14710 "Add or remove TAG for each entry in the region.
14711 This works in the agenda, and also in an org-mode buffer."
14712 (interactive
14713 (list (region-beginning) (region-end)
14714 (let ((org-last-tags-completion-table
14715 (if (derived-mode-p 'org-mode)
14716 (org-uniquify
14717 (delq nil (append (org-get-buffer-tags)
14718 (org-global-tags-completion-table))))
14719 (org-global-tags-completion-table))))
14720 (org-icompleting-read
14721 "Tag: " 'org-tags-completion-function nil nil nil
14722 'org-tags-history))
14723 (progn
14724 (message "[s]et or [r]emove? ")
14725 (equal (read-char-exclusive) ?r))))
14726 (if (fboundp 'deactivate-mark) (deactivate-mark))
14727 (let ((agendap (equal major-mode 'org-agenda-mode))
14728 l1 l2 m buf pos newhead (cnt 0))
14729 (goto-char end)
14730 (setq l2 (1- (org-current-line)))
14731 (goto-char beg)
14732 (setq l1 (org-current-line))
14733 (loop for l from l1 to l2 do
14734 (org-goto-line l)
14735 (setq m (get-text-property (point) 'org-hd-marker))
14736 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14737 (and agendap m))
14738 (setq buf (if agendap (marker-buffer m) (current-buffer))
14739 pos (if agendap m (point)))
14740 (with-current-buffer buf
14741 (save-excursion
14742 (save-restriction
14743 (goto-char pos)
14744 (setq cnt (1+ cnt))
14745 (org-toggle-tag tag (if off 'off 'on))
14746 (setq newhead (org-get-heading)))))
14747 (and agendap (org-agenda-change-all-lines newhead m))))
14748 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14750 (defun org-tags-completion-function (string predicate &optional flag)
14751 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14752 (confirm (lambda (x) (stringp (car x)))))
14753 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14754 (setq s1 (match-string 1 string)
14755 s2 (match-string 2 string))
14756 (setq s1 "" s2 string))
14757 (cond
14758 ((eq flag nil)
14759 ;; try completion
14760 (setq rtn (try-completion s2 ctable confirm))
14761 (if (stringp rtn)
14762 (setq rtn
14763 (concat s1 s2 (substring rtn (length s2))
14764 (if (and org-add-colon-after-tag-completion
14765 (assoc rtn ctable))
14766 ":" ""))))
14767 rtn)
14768 ((eq flag t)
14769 ;; all-completions
14770 (all-completions s2 ctable confirm))
14771 ((eq flag 'lambda)
14772 ;; exact match?
14773 (assoc s2 ctable)))))
14775 (defun org-fast-tag-insert (kwd tags face &optional end)
14776 "Insert KDW, and the TAGS, the latter with face FACE.
14777 Also insert END."
14778 (insert (format "%-12s" (concat kwd ":"))
14779 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14780 (or end "")))
14782 (defun org-fast-tag-show-exit (flag)
14783 (save-excursion
14784 (org-goto-line 3)
14785 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14786 (replace-match ""))
14787 (when flag
14788 (end-of-line 1)
14789 (org-move-to-column (- (window-width) 19) t)
14790 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14792 (defun org-set-current-tags-overlay (current prefix)
14793 "Add an overlay to CURRENT tag with PREFIX."
14794 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14795 (if (featurep 'xemacs)
14796 (org-overlay-display org-tags-overlay (concat prefix s)
14797 'secondary-selection)
14798 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14799 (org-overlay-display org-tags-overlay (concat prefix s)))))
14801 (defvar org-last-tag-selection-key nil)
14802 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14803 "Fast tag selection with single keys.
14804 CURRENT is the current list of tags in the headline, INHERITED is the
14805 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14806 possibly with grouping information. TODO-TABLE is a similar table with
14807 TODO keywords, should these have keys assigned to them.
14808 If the keys are nil, a-z are automatically assigned.
14809 Returns the new tags string, or nil to not change the current settings."
14810 (let* ((fulltable (append table todo-table))
14811 (maxlen (apply 'max (mapcar
14812 (lambda (x)
14813 (if (stringp (car x)) (string-width (car x)) 0))
14814 fulltable)))
14815 (buf (current-buffer))
14816 (expert (eq org-fast-tag-selection-single-key 'expert))
14817 (buffer-tags nil)
14818 (fwidth (+ maxlen 3 1 3))
14819 (ncol (/ (- (window-width) 4) fwidth))
14820 (i-face 'org-done)
14821 (c-face 'org-todo)
14822 tg cnt e c char c1 c2 ntable tbl rtn
14823 ov-start ov-end ov-prefix
14824 (exit-after-next org-fast-tag-selection-single-key)
14825 (done-keywords org-done-keywords)
14826 groups ingroup)
14827 (save-excursion
14828 (beginning-of-line 1)
14829 (if (looking-at
14830 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14831 (setq ov-start (match-beginning 1)
14832 ov-end (match-end 1)
14833 ov-prefix "")
14834 (setq ov-start (1- (point-at-eol))
14835 ov-end (1+ ov-start))
14836 (skip-chars-forward "^\n\r")
14837 (setq ov-prefix
14838 (concat
14839 (buffer-substring (1- (point)) (point))
14840 (if (> (current-column) org-tags-column)
14842 (make-string (- org-tags-column (current-column)) ?\ ))))))
14843 (move-overlay org-tags-overlay ov-start ov-end)
14844 (save-window-excursion
14845 (if expert
14846 (set-buffer (get-buffer-create " *Org tags*"))
14847 (delete-other-windows)
14848 (split-window-vertically)
14849 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14850 (erase-buffer)
14851 (org-set-local 'org-done-keywords done-keywords)
14852 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14853 (org-fast-tag-insert "Current" current c-face "\n\n")
14854 (org-fast-tag-show-exit exit-after-next)
14855 (org-set-current-tags-overlay current ov-prefix)
14856 (setq tbl fulltable char ?a cnt 0)
14857 (while (setq e (pop tbl))
14858 (cond
14859 ((equal (car e) :startgroup)
14860 (push '() groups) (setq ingroup t)
14861 (when (not (= cnt 0))
14862 (setq cnt 0)
14863 (insert "\n"))
14864 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14865 ((equal (car e) :endgroup)
14866 (setq ingroup nil cnt 0)
14867 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14868 ((equal e '(:newline))
14869 (when (not (= cnt 0))
14870 (setq cnt 0)
14871 (insert "\n")
14872 (setq e (car tbl))
14873 (while (equal (car tbl) '(:newline))
14874 (insert "\n")
14875 (setq tbl (cdr tbl)))))
14876 ((equal e '(:grouptags)) nil)
14878 (setq tg (copy-sequence (car e)) c2 nil)
14879 (if (cdr e)
14880 (setq c (cdr e))
14881 ;; automatically assign a character.
14882 (setq c1 (string-to-char
14883 (downcase (substring
14884 tg (if (= (string-to-char tg) ?@) 1 0)))))
14885 (if (or (rassoc c1 ntable) (rassoc c1 table))
14886 (while (or (rassoc char ntable) (rassoc char table))
14887 (setq char (1+ char)))
14888 (setq c2 c1))
14889 (setq c (or c2 char)))
14890 (if ingroup (push tg (car groups)))
14891 (setq tg (org-add-props tg nil 'face
14892 (cond
14893 ((not (assoc tg table))
14894 (org-get-todo-face tg))
14895 ((member tg current) c-face)
14896 ((member tg inherited) i-face))))
14897 (if (equal (caar tbl) :grouptags)
14898 (org-add-props tg nil 'face 'org-tag-group))
14899 (if (and (= cnt 0) (not ingroup)) (insert " "))
14900 (insert "[" c "] " tg (make-string
14901 (- fwidth 4 (length tg)) ?\ ))
14902 (push (cons tg c) ntable)
14903 (when (= (setq cnt (1+ cnt)) ncol)
14904 (insert "\n")
14905 (if ingroup (insert " "))
14906 (setq cnt 0)))))
14907 (setq ntable (nreverse ntable))
14908 (insert "\n")
14909 (goto-char (point-min))
14910 (if (not expert) (org-fit-window-to-buffer))
14911 (setq rtn
14912 (catch 'exit
14913 (while t
14914 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14915 (if (not groups) "no " "")
14916 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14917 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14918 (setq org-last-tag-selection-key c)
14919 (cond
14920 ((= c ?\r) (throw 'exit t))
14921 ((= c ?!)
14922 (setq groups (not groups))
14923 (goto-char (point-min))
14924 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14925 ((= c ?\C-c)
14926 (if (not expert)
14927 (org-fast-tag-show-exit
14928 (setq exit-after-next (not exit-after-next)))
14929 (setq expert nil)
14930 (delete-other-windows)
14931 (set-window-buffer (split-window-vertically) " *Org tags*")
14932 (org-switch-to-buffer-other-window " *Org tags*")
14933 (org-fit-window-to-buffer)))
14934 ((or (= c ?\C-g)
14935 (and (= c ?q) (not (rassoc c ntable))))
14936 (org-detach-overlay org-tags-overlay)
14937 (setq quit-flag t))
14938 ((= c ?\ )
14939 (setq current nil)
14940 (if exit-after-next (setq exit-after-next 'now)))
14941 ((= c ?\t)
14942 (condition-case nil
14943 (setq tg (org-icompleting-read
14944 "Tag: "
14945 (or buffer-tags
14946 (with-current-buffer buf
14947 (org-get-buffer-tags)))))
14948 (quit (setq tg "")))
14949 (when (string-match "\\S-" tg)
14950 (add-to-list 'buffer-tags (list tg))
14951 (if (member tg current)
14952 (setq current (delete tg current))
14953 (push tg current)))
14954 (if exit-after-next (setq exit-after-next 'now)))
14955 ((setq e (rassoc c todo-table) tg (car e))
14956 (with-current-buffer buf
14957 (save-excursion (org-todo tg)))
14958 (if exit-after-next (setq exit-after-next 'now)))
14959 ((setq e (rassoc c ntable) tg (car e))
14960 (if (member tg current)
14961 (setq current (delete tg current))
14962 (loop for g in groups do
14963 (if (member tg g)
14964 (mapc (lambda (x)
14965 (setq current (delete x current)))
14966 g)))
14967 (push tg current))
14968 (if exit-after-next (setq exit-after-next 'now))))
14970 ;; Create a sorted list
14971 (setq current
14972 (sort current
14973 (lambda (a b)
14974 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14975 (if (eq exit-after-next 'now) (throw 'exit t))
14976 (goto-char (point-min))
14977 (beginning-of-line 2)
14978 (delete-region (point) (point-at-eol))
14979 (org-fast-tag-insert "Current" current c-face)
14980 (org-set-current-tags-overlay current ov-prefix)
14981 (while (re-search-forward
14982 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14983 (setq tg (match-string 1))
14984 (add-text-properties
14985 (match-beginning 1) (match-end 1)
14986 (list 'face
14987 (cond
14988 ((member tg current) c-face)
14989 ((member tg inherited) i-face)
14990 (t (get-text-property (match-beginning 1) 'face))))))
14991 (goto-char (point-min)))))
14992 (org-detach-overlay org-tags-overlay)
14993 (if rtn
14994 (mapconcat 'identity current ":")
14995 nil))))
14997 (defun org-get-tags-string ()
14998 "Get the TAGS string in the current headline."
14999 (unless (org-at-heading-p t)
15000 (user-error "Not on a heading"))
15001 (save-excursion
15002 (beginning-of-line 1)
15003 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15004 (org-match-string-no-properties 1)
15005 "")))
15007 (defun org-get-tags ()
15008 "Get the list of tags specified in the current headline."
15009 (org-split-string (org-get-tags-string) ":"))
15011 (defun org-get-buffer-tags ()
15012 "Get a table of all tags used in the buffer, for completion."
15013 (let (tags)
15014 (save-excursion
15015 (goto-char (point-min))
15016 (while (re-search-forward
15017 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
15018 (when (equal (char-after (point-at-bol 0)) ?*)
15019 (mapc (lambda (x) (add-to-list 'tags x))
15020 (org-split-string (org-match-string-no-properties 1) ":")))))
15021 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
15022 (mapcar 'list tags)))
15024 ;;;; The mapping API
15026 (defun org-map-entries (func &optional match scope &rest skip)
15027 "Call FUNC at each headline selected by MATCH in SCOPE.
15029 FUNC is a function or a lisp form. The function will be called without
15030 arguments, with the cursor positioned at the beginning of the headline.
15031 The return values of all calls to the function will be collected and
15032 returned as a list.
15034 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15035 does not need to preserve point. After evaluation, the cursor will be
15036 moved to the end of the line (presumably of the headline of the
15037 processed entry) and search continues from there. Under some
15038 circumstances, this may not produce the wanted results. For example,
15039 if you have removed (e.g. archived) the current (sub)tree it could
15040 mean that the next entry will be skipped entirely. In such cases, you
15041 can specify the position from where search should continue by making
15042 FUNC set the variable `org-map-continue-from' to the desired buffer
15043 position.
15045 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15046 Only headlines that are matched by this query will be considered during
15047 the iteration. When MATCH is nil or t, all headlines will be
15048 visited by the iteration.
15050 SCOPE determines the scope of this command. It can be any of:
15052 nil The current buffer, respecting the restriction if any
15053 tree The subtree started with the entry at point
15054 region The entries within the active region, if any
15055 region-start-level
15056 The entries within the active region, but only those at
15057 the same level than the first one.
15058 file The current buffer, without restriction
15059 file-with-archives
15060 The current buffer, and any archives associated with it
15061 agenda All agenda files
15062 agenda-with-archives
15063 All agenda files with any archive files associated with them
15064 \(file1 file2 ...)
15065 If this is a list, all files in the list will be scanned
15067 The remaining args are treated as settings for the skipping facilities of
15068 the scanner. The following items can be given here:
15070 archive skip trees with the archive tag
15071 comment skip trees with the COMMENT keyword
15072 function or Emacs Lisp form:
15073 will be used as value for `org-agenda-skip-function', so
15074 whenever the function returns a position, FUNC will not be
15075 called for that entry and search will continue from the
15076 position returned
15078 If your function needs to retrieve the tags including inherited tags
15079 at the *current* entry, you can use the value of the variable
15080 `org-scanner-tags' which will be much faster than getting the value
15081 with `org-get-tags-at'. If your function gets properties with
15082 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15083 to t around the call to `org-entry-properties' to get the same speedup.
15084 Note that if your function moves around to retrieve tags and properties at
15085 a *different* entry, you cannot use these techniques."
15086 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15087 (not (org-region-active-p)))
15088 (let* ((org-agenda-archives-mode nil) ; just to make sure
15089 (org-agenda-skip-archived-trees (memq 'archive skip))
15090 (org-agenda-skip-comment-trees (memq 'comment skip))
15091 (org-agenda-skip-function
15092 (car (org-delete-all '(comment archive) skip)))
15093 (org-tags-match-list-sublevels t)
15094 (start-level (eq scope 'region-start-level))
15095 matcher file res
15096 org-todo-keywords-for-agenda
15097 org-done-keywords-for-agenda
15098 org-todo-keyword-alist-for-agenda
15099 org-tag-alist-for-agenda
15100 todo-only)
15102 (cond
15103 ((eq match t) (setq matcher t))
15104 ((eq match nil) (setq matcher t))
15105 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15107 (save-window-excursion
15108 (save-restriction
15109 (cond ((eq scope 'tree)
15110 (org-back-to-heading t)
15111 (org-narrow-to-subtree)
15112 (setq scope nil))
15113 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15114 (org-region-active-p))
15115 ;; If needed, set start-level to a string like "2"
15116 (when start-level
15117 (save-excursion
15118 (goto-char (region-beginning))
15119 (unless (org-at-heading-p) (outline-next-heading))
15120 (setq start-level (org-current-level))))
15121 (narrow-to-region (region-beginning)
15122 (save-excursion
15123 (goto-char (region-end))
15124 (unless (and (bolp) (org-at-heading-p))
15125 (outline-next-heading))
15126 (point)))
15127 (setq scope nil)))
15129 (if (not scope)
15130 (progn
15131 (org-agenda-prepare-buffers
15132 (list (buffer-file-name (current-buffer))))
15133 (setq res (org-scan-tags func matcher todo-only start-level)))
15134 ;; Get the right scope
15135 (cond
15136 ((and scope (listp scope) (symbolp (car scope)))
15137 (setq scope (eval scope)))
15138 ((eq scope 'agenda)
15139 (setq scope (org-agenda-files t)))
15140 ((eq scope 'agenda-with-archives)
15141 (setq scope (org-agenda-files t))
15142 (setq scope (org-add-archive-files scope)))
15143 ((eq scope 'file)
15144 (setq scope (list (buffer-file-name))))
15145 ((eq scope 'file-with-archives)
15146 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15147 (org-agenda-prepare-buffers scope)
15148 (while (setq file (pop scope))
15149 (with-current-buffer (org-find-base-buffer-visiting file)
15150 (save-excursion
15151 (save-restriction
15152 (widen)
15153 (goto-char (point-min))
15154 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15155 res)))
15157 ;;;; Properties
15159 ;;; Setting and retrieving properties
15161 (defconst org-special-properties
15162 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15163 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15164 "The special properties valid in Org-mode.
15166 These are properties that are not defined in the property drawer,
15167 but in some other way.")
15169 (defconst org-default-properties
15170 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15171 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15172 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15173 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15174 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15175 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15176 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15177 "Some properties that are used by Org-mode for various purposes.
15178 Being in this list makes sure that they are offered for completion.")
15180 (defun org-property-action ()
15181 "Do an action on properties."
15182 (interactive)
15183 (let (c)
15184 (org-at-property-p)
15185 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15186 (setq c (read-char-exclusive))
15187 (cond
15188 ((equal c ?s)
15189 (call-interactively 'org-set-property))
15190 ((equal c ?d)
15191 (call-interactively 'org-delete-property))
15192 ((equal c ?D)
15193 (call-interactively 'org-delete-property-globally))
15194 ((equal c ?c)
15195 (call-interactively 'org-compute-property-at-point))
15196 (t (user-error "No such property action %c" c)))))
15198 (defun org-inc-effort ()
15199 "Increment the value of the effort property in the current entry."
15200 (interactive)
15201 (org-set-effort nil t))
15203 (defvar org-clock-effort) ;; Defined in org-clock.el
15204 (defvar org-clock-current-task) ;; Defined in org-clock.el
15205 (defun org-set-effort (&optional value increment)
15206 "Set the effort property of the current entry.
15207 With numerical prefix arg, use the nth allowed value, 0 stands for the
15208 10th allowed value.
15210 When INCREMENT is non-nil, set the property to the next allowed value."
15211 (interactive "P")
15212 (if (equal value 0) (setq value 10))
15213 (let* ((completion-ignore-case t)
15214 (prop org-effort-property)
15215 (cur (org-entry-get nil prop))
15216 (allowed (org-property-get-allowed-values nil prop 'table))
15217 (existing (mapcar 'list (org-property-values prop)))
15218 (heading (nth 4 (org-heading-components)))
15220 (val (cond
15221 ((stringp value) value)
15222 ((and allowed (integerp value))
15223 (or (car (nth (1- value) allowed))
15224 (car (org-last allowed))))
15225 ((and allowed increment)
15226 (or (caadr (member (list cur) allowed))
15227 (user-error "Allowed effort values are not set")))
15228 (allowed
15229 (message "Select 1-9,0, [RET%s]: %s"
15230 (if cur (concat "=" cur) "")
15231 (mapconcat 'car allowed " "))
15232 (setq rpl (read-char-exclusive))
15233 (if (equal rpl ?\r)
15235 (setq rpl (- rpl ?0))
15236 (if (equal rpl 0) (setq rpl 10))
15237 (if (and (> rpl 0) (<= rpl (length allowed)))
15238 (car (nth (1- rpl) allowed))
15239 (org-completing-read "Effort: " allowed nil))))
15241 (let (org-completion-use-ido org-completion-use-iswitchb)
15242 (org-completing-read
15243 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15244 (concat "[" cur "]") "")
15245 ": ")
15246 existing nil nil "" nil cur))))))
15247 (unless (equal (org-entry-get nil prop) val)
15248 (org-entry-put nil prop val))
15249 (save-excursion
15250 (org-back-to-heading t)
15251 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15252 (when (string= heading org-clock-current-task)
15253 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15254 (org-clock-update-mode-line))
15255 (message "%s is now %s" prop val)))
15257 (defun org-at-property-p ()
15258 "Is cursor inside a property drawer?"
15259 (save-excursion
15260 (when (equal 'node-property (car (org-element-at-point)))
15261 (beginning-of-line 1)
15262 (looking-at org-property-re))))
15264 (defun org-get-property-block (&optional beg end force)
15265 "Return the (beg . end) range of the body of the property drawer.
15266 BEG and END are the beginning and end of the current subtree, or of
15267 the part before the first headline. If they are not given, they will
15268 be found. If the drawer does not exist and FORCE is non-nil, create
15269 the drawer."
15270 (catch 'exit
15271 (save-excursion
15272 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15273 (progn (org-back-to-heading t) (point))))
15274 (end (or end (and (not (outline-next-heading)) (point-max))
15275 (point))))
15276 (goto-char beg)
15277 (if (re-search-forward org-property-start-re end t)
15278 (setq beg (1+ (match-end 0)))
15279 (if force
15280 (save-excursion
15281 (org-insert-property-drawer)
15282 (setq end (progn (outline-next-heading) (point))))
15283 (throw 'exit nil))
15284 (goto-char beg)
15285 (if (re-search-forward org-property-start-re end t)
15286 (setq beg (1+ (match-end 0)))))
15287 (if (re-search-forward org-property-end-re end t)
15288 (setq end (match-beginning 0))
15289 (or force (throw 'exit nil))
15290 (goto-char beg)
15291 (setq end beg)
15292 (org-indent-line)
15293 (insert ":END:\n"))
15294 (cons beg end)))))
15296 (defun org-entry-properties (&optional pom which specific)
15297 "Get all properties of the entry at point-or-marker POM.
15298 This includes the TODO keyword, the tags, time strings for deadline,
15299 scheduled, and clocking, and any additional properties defined in the
15300 entry. The return value is an alist, keys may occur multiple times
15301 if the property key was used several times.
15302 POM may also be nil, in which case the current entry is used.
15303 If WHICH is nil or `all', get all properties. If WHICH is
15304 `special' or `standard', only get that subclass. If WHICH
15305 is a string only get exactly this property. SPECIFIC can be a string, the
15306 specific property we are interested in. Specifying it can speed
15307 things up because then unnecessary parsing is avoided."
15308 (setq which (or which 'all))
15309 (org-with-wide-buffer
15310 (org-with-point-at pom
15311 (let ((clockstr (substring org-clock-string 0 -1))
15312 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15313 (case-fold-search nil)
15314 beg end range props sum-props key key1 value string clocksum clocksumt)
15315 (when (and (derived-mode-p 'org-mode)
15316 (ignore-errors (org-back-to-heading t)))
15317 (setq beg (point))
15318 (setq sum-props (get-text-property (point) 'org-summaries))
15319 (setq clocksum (get-text-property (point) :org-clock-minutes)
15320 clocksumt (get-text-property (point) :org-clock-minutes-today))
15321 (outline-next-heading)
15322 (setq end (point))
15323 (when (memq which '(all special))
15324 ;; Get the special properties, like TODO and tags
15325 (goto-char beg)
15326 (when (and (or (not specific) (string= specific "TODO"))
15327 (looking-at org-todo-line-regexp) (match-end 2))
15328 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15329 (when (and (or (not specific) (string= specific "PRIORITY"))
15330 (looking-at org-priority-regexp))
15331 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15332 (when (or (not specific) (string= specific "FILE"))
15333 (push (cons "FILE" buffer-file-name) props))
15334 (when (and (or (not specific) (string= specific "TAGS"))
15335 (setq value (org-get-tags-string))
15336 (string-match "\\S-" value))
15337 (push (cons "TAGS" value) props))
15338 (when (and (or (not specific) (string= specific "ALLTAGS"))
15339 (setq value (org-get-tags-at)))
15340 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15341 ":"))
15342 props))
15343 (when (or (not specific) (string= specific "BLOCKED"))
15344 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15345 (when (or (not specific)
15346 (member specific
15347 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15348 "TIMESTAMP" "TIMESTAMP_IA")))
15349 (catch 'match
15350 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15351 (setq key (if (match-end 1)
15352 (substring (org-match-string-no-properties 1)
15353 0 -1))
15354 string (if (equal key clockstr)
15355 (org-trim
15356 (buffer-substring-no-properties
15357 (match-beginning 3) (goto-char
15358 (point-at-eol))))
15359 (substring (org-match-string-no-properties 3)
15360 1 -1)))
15361 ;; Get the correct property name from the key. This is
15362 ;; necessary if the user has configured time keywords.
15363 (setq key1 (concat key ":"))
15364 (cond
15365 ((not key)
15366 (setq key
15367 (if (= (char-after (match-beginning 3)) ?\[)
15368 "TIMESTAMP_IA" "TIMESTAMP")))
15369 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15370 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15371 ((equal key1 org-closed-string) (setq key "CLOSED"))
15372 ((equal key1 org-clock-string) (setq key "CLOCK")))
15373 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15374 (progn
15375 (push (cons key string) props)
15376 ;; no need to search further if match is found
15377 (throw 'match t))
15378 (when (or (equal key "CLOCK") (not (assoc key props)))
15379 (push (cons key string) props)))))))
15381 (when (memq which '(all standard))
15382 ;; Get the standard properties, like :PROP: ...
15383 (setq range (org-get-property-block beg end))
15384 (when range
15385 (goto-char (car range))
15386 (while (re-search-forward org-property-re
15387 (cdr range) t)
15388 (setq key (org-match-string-no-properties 2)
15389 value (org-trim (or (org-match-string-no-properties 3) "")))
15390 (unless (member key excluded)
15391 (push (cons key (or value "")) props)))))
15392 (if clocksum
15393 (push (cons "CLOCKSUM"
15394 (org-columns-number-to-string (/ (float clocksum) 60.)
15395 'add_times))
15396 props))
15397 (if clocksumt
15398 (push (cons "CLOCKSUM_T"
15399 (org-columns-number-to-string (/ (float clocksumt) 60.)
15400 'add_times))
15401 props))
15402 (unless (assoc "CATEGORY" props)
15403 (push (cons "CATEGORY" (org-get-category)) props))
15404 (append sum-props (nreverse props)))))))
15406 (defun org-entry-get (pom property &optional inherit literal-nil)
15407 "Get value of PROPERTY for entry or content at point-or-marker POM.
15408 If INHERIT is non-nil and the entry does not have the property,
15409 then also check higher levels of the hierarchy.
15410 If INHERIT is the symbol `selective', use inheritance only if the setting
15411 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15412 If the property is present but empty, the return value is the empty string.
15413 If the property is not present at all, nil is returned.
15415 Return the value as a string.
15417 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15418 do not interpret it as the list atom nil. This is used for inheritance
15419 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15420 (org-with-point-at pom
15421 (if (and inherit (if (eq inherit 'selective)
15422 (org-property-inherit-p property)
15424 (org-entry-get-with-inheritance property literal-nil)
15425 (if (member property org-special-properties)
15426 ;; We need a special property. Use `org-entry-properties'
15427 ;; to retrieve it, but specify the wanted property
15428 (cdr (assoc property (org-entry-properties nil 'special property)))
15429 (org-with-wide-buffer
15430 (let ((range (org-get-property-block)))
15431 (when (and range (not (eq (car range) (cdr range))))
15432 (let* ((props
15433 (list (or (assoc property org-file-properties)
15434 (assoc property org-global-properties)
15435 (assoc property org-global-properties-fixed))))
15436 (ap (lambda (key)
15437 (when (re-search-forward
15438 (org-re-property key) (cdr range) t)
15439 (setq props
15440 (org-update-property-plist
15442 (if (match-end 3)
15443 (org-match-string-no-properties 3) "")
15444 props)))))
15445 val)
15446 (goto-char (car range))
15447 (funcall ap property)
15448 (goto-char (car range))
15449 (while (funcall ap (concat property "+")))
15450 (setq val (cdr (assoc property props)))
15451 (when val (if literal-nil val (org-not-nil val)))))))))))
15453 (defun org-property-or-variable-value (var &optional inherit)
15454 "Check if there is a property fixing the value of VAR.
15455 If yes, return this value. If not, return the current value of the variable."
15456 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15457 (if (and prop (stringp prop) (string-match "\\S-" prop))
15458 (read prop)
15459 (symbol-value var))))
15461 (defun org-entry-delete (pom property)
15462 "Delete the property PROPERTY from entry at point-or-marker POM."
15463 (unless (member property org-special-properties)
15464 (org-with-point-at pom
15465 (let ((range (org-get-property-block)))
15466 (if (and range
15467 (goto-char (car range))
15468 (re-search-forward
15469 (org-re-property property)
15470 (cdr range) t))
15471 (progn
15472 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15473 (org-remove-empty-drawer-at (car range))
15475 nil)))))
15477 ;; Multi-values properties are properties that contain multiple values
15478 ;; These values are assumed to be single words, separated by whitespace.
15479 (defun org-entry-add-to-multivalued-property (pom property value)
15480 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15481 (let* ((old (org-entry-get pom property))
15482 (values (and old (org-split-string old "[ \t]"))))
15483 (setq value (org-entry-protect-space value))
15484 (unless (member value values)
15485 (setq values (append values (list value)))
15486 (org-entry-put pom property
15487 (mapconcat 'identity values " ")))))
15489 (defun org-entry-remove-from-multivalued-property (pom property value)
15490 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15491 (let* ((old (org-entry-get pom property))
15492 (values (and old (org-split-string old "[ \t]"))))
15493 (setq value (org-entry-protect-space value))
15494 (when (member value values)
15495 (setq values (delete value values))
15496 (org-entry-put pom property
15497 (mapconcat 'identity values " ")))))
15499 (defun org-entry-member-in-multivalued-property (pom property value)
15500 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15501 (let* ((old (org-entry-get pom property))
15502 (values (and old (org-split-string old "[ \t]"))))
15503 (setq value (org-entry-protect-space value))
15504 (member value values)))
15506 (defun org-entry-get-multivalued-property (pom property)
15507 "Return a list of values in a multivalued property."
15508 (let* ((value (org-entry-get pom property))
15509 (values (and value (org-split-string value "[ \t]"))))
15510 (mapcar 'org-entry-restore-space values)))
15512 (defun org-entry-put-multivalued-property (pom property &rest values)
15513 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15514 VALUES should be a list of strings. Spaces will be protected."
15515 (org-entry-put pom property
15516 (mapconcat 'org-entry-protect-space values " "))
15517 (let* ((value (org-entry-get pom property))
15518 (values (and value (org-split-string value "[ \t]"))))
15519 (mapcar 'org-entry-restore-space values)))
15521 (defun org-entry-protect-space (s)
15522 "Protect spaces and newline in string S."
15523 (while (string-match " " s)
15524 (setq s (replace-match "%20" t t s)))
15525 (while (string-match "\n" s)
15526 (setq s (replace-match "%0A" t t s)))
15529 (defun org-entry-restore-space (s)
15530 "Restore spaces and newline in string S."
15531 (while (string-match "%20" s)
15532 (setq s (replace-match " " t t s)))
15533 (while (string-match "%0A" s)
15534 (setq s (replace-match "\n" t t s)))
15537 (defvar org-entry-property-inherited-from (make-marker)
15538 "Marker pointing to the entry from where a property was inherited.
15539 Each call to `org-entry-get-with-inheritance' will set this marker to the
15540 location of the entry where the inheritance search matched. If there was
15541 no match, the marker will point nowhere.
15542 Note that also `org-entry-get' calls this function, if the INHERIT flag
15543 is set.")
15545 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15546 "Get PROPERTY of entry or content at point, search higher levels if needed.
15547 The search will stop at the first ancestor which has the property defined.
15548 If the value found is \"nil\", return nil to show that the property
15549 should be considered as undefined (this is the meaning of nil here).
15550 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15551 (move-marker org-entry-property-inherited-from nil)
15552 (let (tmp)
15553 (save-excursion
15554 (save-restriction
15555 (widen)
15556 (catch 'ex
15557 (while t
15558 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15559 (or (ignore-errors (org-back-to-heading t))
15560 (goto-char (point-min)))
15561 (move-marker org-entry-property-inherited-from (point))
15562 (throw 'ex tmp))
15563 (or (ignore-errors (org-up-heading-safe))
15564 (throw 'ex nil))))))
15565 (setq tmp (or tmp
15566 (cdr (assoc property org-file-properties))
15567 (cdr (assoc property org-global-properties))
15568 (cdr (assoc property org-global-properties-fixed))))
15569 (if literal-nil tmp (org-not-nil tmp))))
15571 (defvar org-property-changed-functions nil
15572 "Hook called when the value of a property has changed.
15573 Each hook function should accept two arguments, the name of the property
15574 and the new value.")
15576 (defun org-entry-put (pom property value)
15577 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15578 If the value is `nil', it is converted to the empty string.
15579 If it is not a string, an error is raised."
15580 (cond ((null value) (setq value ""))
15581 ((not (stringp value))
15582 (error "Properties values should be strings.")))
15583 (org-with-point-at pom
15584 (org-back-to-heading t)
15585 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15586 range)
15587 (cond
15588 ((equal property "TODO")
15589 (when (and (string-match "\\S-" value)
15590 (not (member value org-todo-keywords-1)))
15591 (user-error "\"%s\" is not a valid TODO state" value))
15592 (if (or (not value)
15593 (not (string-match "\\S-" value)))
15594 (setq value 'none))
15595 (org-todo value)
15596 (org-set-tags nil 'align))
15597 ((equal property "PRIORITY")
15598 (org-priority (if (and value (string-match "\\S-" value))
15599 (string-to-char value) ?\ ))
15600 (org-set-tags nil 'align))
15601 ((equal property "CLOCKSUM")
15602 (if (not (re-search-forward
15603 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15604 (error "Cannot find a clock log")
15605 (goto-char (- (match-end 1) 2))
15606 (cond
15607 ((eq value 'earlier) (org-timestamp-down))
15608 ((eq value 'later) (org-timestamp-up)))
15609 (org-clock-sum-current-item)))
15610 ((equal property "SCHEDULED")
15611 (if (re-search-forward org-scheduled-time-regexp end t)
15612 (cond
15613 ((eq value 'earlier) (org-timestamp-change -1 'day))
15614 ((eq value 'later) (org-timestamp-change 1 'day))
15615 (t (call-interactively 'org-schedule)))
15616 (call-interactively 'org-schedule)))
15617 ((equal property "DEADLINE")
15618 (if (re-search-forward org-deadline-time-regexp end t)
15619 (cond
15620 ((eq value 'earlier) (org-timestamp-change -1 'day))
15621 ((eq value 'later) (org-timestamp-change 1 'day))
15622 (t (call-interactively 'org-deadline)))
15623 (call-interactively 'org-deadline)))
15624 ((member property org-special-properties)
15625 (error "The %s property can not yet be set with `org-entry-put'"
15626 property))
15627 (t ; a non-special property
15628 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15629 (setq range (org-get-property-block beg end 'force))
15630 (goto-char (car range))
15631 (if (re-search-forward
15632 (org-re-property property) (cdr range) t)
15633 (progn
15634 (delete-region (match-beginning 0) (match-end 0))
15635 (goto-char (match-beginning 0)))
15636 (goto-char (cdr range))
15637 (insert "\n")
15638 (backward-char 1)
15639 (org-indent-line))
15640 (insert ":" property ":")
15641 (and value (insert " " value))
15642 (org-indent-line)))))
15643 (run-hook-with-args 'org-property-changed-functions property value)))
15645 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15646 "Get all property keys in the current buffer.
15647 With INCLUDE-SPECIALS, also list the special properties that reflect things
15648 like tags and TODO state.
15649 With INCLUDE-DEFAULTS, also include properties that has special meaning
15650 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15651 and others.
15652 With INCLUDE-COLUMNS, also include property names given in COLUMN
15653 formats in the current buffer."
15654 (let (rtn range cfmt s p)
15655 (save-excursion
15656 (save-restriction
15657 (widen)
15658 (goto-char (point-min))
15659 (while (re-search-forward org-property-start-re nil t)
15660 (setq range (org-get-property-block))
15661 (goto-char (car range))
15662 (while (re-search-forward org-property-re
15663 (cdr range) t)
15664 (add-to-list 'rtn (org-match-string-no-properties 2)))
15665 (outline-next-heading))))
15667 (when include-specials
15668 (setq rtn (append org-special-properties rtn)))
15670 (when include-defaults
15671 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15672 (add-to-list 'rtn org-effort-property))
15674 (when include-columns
15675 (save-excursion
15676 (save-restriction
15677 (widen)
15678 (goto-char (point-min))
15679 (while (re-search-forward
15680 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15681 nil t)
15682 (setq cfmt (match-string 2) s 0)
15683 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15684 cfmt s)
15685 (setq s (match-end 0)
15686 p (match-string 1 cfmt))
15687 (unless (or (equal p "ITEM")
15688 (member p org-special-properties))
15689 (add-to-list 'rtn (match-string 1 cfmt))))))))
15691 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15693 (defun org-property-values (key)
15694 "Return a list of all values of property KEY in the current buffer."
15695 (save-excursion
15696 (save-restriction
15697 (widen)
15698 (goto-char (point-min))
15699 (let ((re (org-re-property key))
15700 values)
15701 (while (re-search-forward re nil t)
15702 (add-to-list 'values (org-trim (match-string 3))))
15703 (delete "" values)))))
15705 (defun org-insert-property-drawer ()
15706 "Insert a property drawer into the current entry."
15707 (org-back-to-heading t)
15708 (looking-at org-outline-regexp)
15709 (let ((indent (if org-adapt-indentation
15710 (- (match-end 0) (match-beginning 0))
15712 (beg (point))
15713 (re (concat "^[ \t]*" org-keyword-time-regexp))
15714 end hiddenp)
15715 (outline-next-heading)
15716 (setq end (point))
15717 (goto-char beg)
15718 (while (re-search-forward re end t))
15719 (setq hiddenp (outline-invisible-p))
15720 (end-of-line 1)
15721 (and (equal (char-after) ?\n) (forward-char 1))
15722 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15723 (if (member (match-string 1) '("CLOCK:" ":END:"))
15724 ;; just skip this line
15725 (beginning-of-line 2)
15726 ;; Drawer start, find the end
15727 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15728 (beginning-of-line 1)))
15729 (org-skip-over-state-notes)
15730 (skip-chars-backward " \t\n\r")
15731 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15732 (forward-char 1))
15733 (goto-char (point-at-eol))
15734 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15735 (beginning-of-line 0)
15736 (org-indent-to-column indent)
15737 (beginning-of-line 2)
15738 (org-indent-to-column indent)
15739 (beginning-of-line 0)
15740 (if hiddenp
15741 (save-excursion
15742 (org-back-to-heading t)
15743 (hide-entry))
15744 (org-flag-drawer t))))
15746 (defun org-insert-drawer (&optional arg drawer)
15747 "Insert a drawer at point.
15749 Optional argument DRAWER, when non-nil, is a string representing
15750 drawer's name. Otherwise, the user is prompted for a name.
15752 If a region is active, insert the drawer around that region
15753 instead.
15755 Point is left between drawer's boundaries."
15756 (interactive "P")
15757 (let* ((drawer (if arg "PROPERTIES"
15758 (or drawer (read-from-minibuffer "Drawer: ")))))
15759 (cond
15760 ;; With C-u, fall back on `org-insert-property-drawer'
15761 (arg (org-insert-property-drawer))
15763 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15764 (user-error "Invalid drawer name"))
15765 ;; With an active region, insert a drawer at point.
15766 ((not (org-region-active-p))
15767 (progn
15768 (unless (bolp) (insert "\n"))
15769 (insert (format ":%s:\n\n:END:\n" drawer))
15770 (forward-line -2)))
15771 ;; Otherwise, insert the drawer at point
15773 (let ((rbeg (region-beginning))
15774 (rend (copy-marker (region-end))))
15775 (unwind-protect
15776 (progn
15777 (goto-char rbeg)
15778 (beginning-of-line)
15779 (when (save-excursion
15780 (re-search-forward org-outline-regexp-bol rend t))
15781 (user-error "Drawers cannot contain headlines"))
15782 ;; Position point at the beginning of the first
15783 ;; non-blank line in region. Insert drawer's opening
15784 ;; there, then indent it.
15785 (org-skip-whitespace)
15786 (beginning-of-line)
15787 (insert ":" drawer ":\n")
15788 (forward-line -1)
15789 (indent-for-tab-command)
15790 ;; Move point to the beginning of the first blank line
15791 ;; after the last non-blank line in region. Insert
15792 ;; drawer's closing, then indent it.
15793 (goto-char rend)
15794 (skip-chars-backward " \r\t\n")
15795 (insert "\n:END:")
15796 (deactivate-mark t)
15797 (indent-for-tab-command)
15798 (unless (eolp) (insert "\n")))
15799 ;; Clear marker, whatever the outcome of insertion is.
15800 (set-marker rend nil)))))))
15802 (defvar org-property-set-functions-alist nil
15803 "Property set function alist.
15804 Each entry should have the following format:
15806 (PROPERTY . READ-FUNCTION)
15808 The read function will be called with the same argument as
15809 `org-completing-read'.")
15811 (defun org-set-property-function (property)
15812 "Get the function that should be used to set PROPERTY.
15813 This is computed according to `org-property-set-functions-alist'."
15814 (or (cdr (assoc property org-property-set-functions-alist))
15815 'org-completing-read))
15817 (defun org-read-property-value (property)
15818 "Read PROPERTY value from user."
15819 (let* ((completion-ignore-case t)
15820 (allowed (org-property-get-allowed-values nil property 'table))
15821 (cur (org-entry-get nil property))
15822 (prompt (concat property " value"
15823 (if (and cur (string-match "\\S-" cur))
15824 (concat " [" cur "]") "") ": "))
15825 (set-function (org-set-property-function property))
15826 (val (if allowed
15827 (funcall set-function prompt allowed nil
15828 (not (get-text-property 0 'org-unrestricted
15829 (caar allowed))))
15830 (let (org-completion-use-ido org-completion-use-iswitchb)
15831 (funcall set-function prompt
15832 (mapcar 'list (org-property-values property))
15833 nil nil "" nil cur)))))
15834 (if (equal val "")
15836 val)))
15838 (defvar org-last-set-property nil)
15839 (defvar org-last-set-property-value nil)
15840 (defun org-read-property-name ()
15841 "Read a property name."
15842 (let* ((completion-ignore-case t)
15843 (keys (org-buffer-property-keys nil t t))
15844 (default-prop (or (save-excursion
15845 (save-match-data
15846 (beginning-of-line)
15847 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15848 (null (string= (match-string 1) "END"))
15849 (match-string 1))))
15850 org-last-set-property))
15851 (property (org-icompleting-read
15852 (concat "Property"
15853 (if default-prop (concat " [" default-prop "]") "")
15854 ": ")
15855 (mapcar 'list keys)
15856 nil nil nil nil
15857 default-prop)))
15858 (if (member property keys)
15859 property
15860 (or (cdr (assoc (downcase property)
15861 (mapcar (lambda (x) (cons (downcase x) x))
15862 keys)))
15863 property))))
15865 (defun org-set-property-and-value (use-last)
15866 "Allow to set [PROPERTY]: [value] direction from prompt.
15867 When use-default, don't even ask, just use the last
15868 \"[PROPERTY]: [value]\" string from the history."
15869 (interactive "P")
15870 (let* ((completion-ignore-case t)
15871 (pv (or (and use-last org-last-set-property-value)
15872 (org-completing-read
15873 "Enter a \"[Property]: [value]\" pair: "
15874 nil nil nil nil nil
15875 org-last-set-property-value)))
15876 prop val)
15877 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15878 (setq prop (match-string 1 pv)
15879 val (match-string 2 pv))
15880 (org-set-property prop val))))
15882 (defun org-set-property (property value)
15883 "In the current entry, set PROPERTY to VALUE.
15884 When called interactively, this will prompt for a property name, offering
15885 completion on existing and default properties. And then it will prompt
15886 for a value, offering completion either on allowed values (via an inherited
15887 xxx_ALL property) or on existing values in other instances of this property
15888 in the current file."
15889 (interactive (list nil nil))
15890 (let* ((property (or property (org-read-property-name)))
15891 (value (or value (org-read-property-value property)))
15892 (fn (cdr (assoc property org-properties-postprocess-alist))))
15893 (setq org-last-set-property property)
15894 (setq org-last-set-property-value (concat property ": " value))
15895 ;; Possibly postprocess the inserted value:
15896 (when fn (setq value (funcall fn value)))
15897 (unless (equal (org-entry-get nil property) value)
15898 (org-entry-put nil property value))))
15900 (defun org-delete-property (property)
15901 "In the current entry, delete PROPERTY."
15902 (interactive
15903 (let* ((completion-ignore-case t)
15904 (prop (org-icompleting-read "Property: "
15905 (org-entry-properties nil 'standard))))
15906 (list prop)))
15907 (message "Property %s %s" property
15908 (if (org-entry-delete nil property)
15909 "deleted"
15910 "was not present in the entry")))
15912 (defun org-delete-property-globally (property)
15913 "Remove PROPERTY globally, from all entries."
15914 (interactive
15915 (let* ((completion-ignore-case t)
15916 (prop (org-icompleting-read
15917 "Globally remove property: "
15918 (mapcar 'list (org-buffer-property-keys)))))
15919 (list prop)))
15920 (save-excursion
15921 (save-restriction
15922 (widen)
15923 (goto-char (point-min))
15924 (let ((cnt 0))
15925 (while (re-search-forward
15926 (org-re-property property)
15927 nil t)
15928 (setq cnt (1+ cnt))
15929 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15930 (message "Property \"%s\" removed from %d entries" property cnt)))))
15932 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15934 (defun org-compute-property-at-point ()
15935 "Compute the property at point.
15936 This looks for an enclosing column format, extracts the operator and
15937 then applies it to the property in the column format's scope."
15938 (interactive)
15939 (unless (org-at-property-p)
15940 (user-error "Not at a property"))
15941 (let ((prop (org-match-string-no-properties 2)))
15942 (org-columns-get-format-and-top-level)
15943 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15944 (user-error "No operator defined for property %s" prop))
15945 (org-columns-compute prop)))
15947 (defvar org-property-allowed-value-functions nil
15948 "Hook for functions supplying allowed values for a specific property.
15949 The functions must take a single argument, the name of the property, and
15950 return a flat list of allowed values. If \":ETC\" is one of
15951 the values, this means that these values are intended as defaults for
15952 completion, but that other values should be allowed too.
15953 The functions must return nil if they are not responsible for this
15954 property.")
15956 (defun org-property-get-allowed-values (pom property &optional table)
15957 "Get allowed values for the property PROPERTY.
15958 When TABLE is non-nil, return an alist that can directly be used for
15959 completion."
15960 (let (vals)
15961 (cond
15962 ((equal property "TODO")
15963 (setq vals (org-with-point-at pom
15964 (append org-todo-keywords-1 '("")))))
15965 ((equal property "PRIORITY")
15966 (let ((n org-lowest-priority))
15967 (while (>= n org-highest-priority)
15968 (push (char-to-string n) vals)
15969 (setq n (1- n)))))
15970 ((member property org-special-properties))
15971 ((setq vals (run-hook-with-args-until-success
15972 'org-property-allowed-value-functions property)))
15974 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15975 (when (and vals (string-match "\\S-" vals))
15976 (setq vals (car (read-from-string (concat "(" vals ")"))))
15977 (setq vals (mapcar (lambda (x)
15978 (cond ((stringp x) x)
15979 ((numberp x) (number-to-string x))
15980 ((symbolp x) (symbol-name x))
15981 (t "???")))
15982 vals)))))
15983 (when (member ":ETC" vals)
15984 (setq vals (remove ":ETC" vals))
15985 (org-add-props (car vals) '(org-unrestricted t)))
15986 (if table (mapcar 'list vals) vals)))
15988 (defun org-property-previous-allowed-value (&optional previous)
15989 "Switch to the next allowed value for this property."
15990 (interactive)
15991 (org-property-next-allowed-value t))
15993 (defun org-property-next-allowed-value (&optional previous)
15994 "Switch to the next allowed value for this property."
15995 (interactive)
15996 (unless (org-at-property-p)
15997 (user-error "Not at a property"))
15998 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15999 (key (match-string 2))
16000 (value (match-string 3))
16001 (allowed (or (org-property-get-allowed-values (point) key)
16002 (and (member value '("[ ]" "[-]" "[X]"))
16003 '("[ ]" "[X]"))))
16004 (heading (save-match-data (nth 4 (org-heading-components))))
16005 nval)
16006 (unless allowed
16007 (user-error "Allowed values for this property have not been defined"))
16008 (if previous (setq allowed (reverse allowed)))
16009 (if (member value allowed)
16010 (setq nval (car (cdr (member value allowed)))))
16011 (setq nval (or nval (car allowed)))
16012 (if (equal nval value)
16013 (user-error "Only one allowed value for this property"))
16014 (org-at-property-p)
16015 (replace-match (concat " :" key ": " nval) t t)
16016 (org-indent-line)
16017 (beginning-of-line 1)
16018 (skip-chars-forward " \t")
16019 (when (equal prop org-effort-property)
16020 (save-excursion
16021 (org-back-to-heading t)
16022 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
16023 (when (string= org-clock-current-task heading)
16024 (setq org-clock-effort nval)
16025 (org-clock-update-mode-line)))
16026 (run-hook-with-args 'org-property-changed-functions key nval)))
16028 (defun org-find-olp (path &optional this-buffer)
16029 "Return a marker pointing to the entry at outline path OLP.
16030 If anything goes wrong, throw an error.
16031 You can wrap this call to catch the error like this:
16033 (condition-case msg
16034 (org-mobile-locate-entry (match-string 4))
16035 (error (nth 1 msg)))
16037 The return value will then be either a string with the error message,
16038 or a marker if everything is OK.
16040 If THIS-BUFFER is set, the outline path does not contain a file,
16041 only headings."
16042 (let* ((file (if this-buffer buffer-file-name (pop path)))
16043 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16044 (level 1)
16045 (lmin 1)
16046 (lmax 1)
16047 limit re end found pos heading cnt flevel)
16048 (unless buffer (error "File not found :%s" file))
16049 (with-current-buffer buffer
16050 (save-excursion
16051 (save-restriction
16052 (widen)
16053 (setq limit (point-max))
16054 (goto-char (point-min))
16055 (while (setq heading (pop path))
16056 (setq re (format org-complex-heading-regexp-format
16057 (regexp-quote heading)))
16058 (setq cnt 0 pos (point))
16059 (while (re-search-forward re end t)
16060 (setq level (- (match-end 1) (match-beginning 1)))
16061 (if (and (>= level lmin) (<= level lmax))
16062 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16063 (when (= cnt 0) (error "Heading not found on level %d: %s"
16064 lmax heading))
16065 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16066 lmax heading))
16067 (goto-char found)
16068 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16069 (setq end (save-excursion (org-end-of-subtree t t))))
16070 (when (org-at-heading-p)
16071 (point-marker)))))))
16073 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16074 "Find node HEADING in BUFFER.
16075 Return a marker to the heading if it was found, or nil if not.
16076 If POS-ONLY is set, return just the position instead of a marker.
16078 The heading text must match exact, but it may have a TODO keyword,
16079 a priority cookie and tags in the standard locations."
16080 (with-current-buffer (or buffer (current-buffer))
16081 (save-excursion
16082 (save-restriction
16083 (widen)
16084 (goto-char (point-min))
16085 (let (case-fold-search)
16086 (if (re-search-forward
16087 (format org-complex-heading-regexp-format
16088 (regexp-quote heading)) nil t)
16089 (if pos-only
16090 (match-beginning 0)
16091 (move-marker (make-marker) (match-beginning 0)))))))))
16093 (defun org-find-exact-heading-in-directory (heading &optional dir)
16094 "Find Org node headline HEADING in all .org files in directory DIR.
16095 When the target headline is found, return a marker to this location."
16096 (let ((files (directory-files (or dir default-directory)
16097 nil "\\`[^.#].*\\.org\\'"))
16098 file visiting m buffer)
16099 (catch 'found
16100 (while (setq file (pop files))
16101 (message "trying %s" file)
16102 (setq visiting (org-find-base-buffer-visiting file))
16103 (setq buffer (or visiting (find-file-noselect file)))
16104 (setq m (org-find-exact-headline-in-buffer
16105 heading buffer))
16106 (when (and (not m) (not visiting)) (kill-buffer buffer))
16107 (and m (throw 'found m))))))
16109 (defun org-find-entry-with-id (ident)
16110 "Locate the entry that contains the ID property with exact value IDENT.
16111 IDENT can be a string, a symbol or a number, this function will search for
16112 the string representation of it.
16113 Return the position where this entry starts, or nil if there is no such entry."
16114 (interactive "sID: ")
16115 (let ((id (cond
16116 ((stringp ident) ident)
16117 ((symbol-name ident) (symbol-name ident))
16118 ((numberp ident) (number-to-string ident))
16119 (t (error "IDENT %s must be a string, symbol or number" ident))))
16120 (case-fold-search nil))
16121 (save-excursion
16122 (save-restriction
16123 (widen)
16124 (goto-char (point-min))
16125 (when (re-search-forward
16126 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16127 nil t)
16128 (org-back-to-heading t)
16129 (point))))))
16131 ;;;; Timestamps
16133 (defvar org-last-changed-timestamp nil)
16134 (defvar org-last-inserted-timestamp nil
16135 "The last time stamp inserted with `org-insert-time-stamp'.")
16136 (defvar org-ts-what) ; dynamically scoped parameter
16138 (defun org-time-stamp (arg &optional inactive)
16139 "Prompt for a date/time and insert a time stamp.
16140 If the user specifies a time like HH:MM or if this command is
16141 called with at least one prefix argument, the time stamp contains
16142 the date and the time. Otherwise, only the date is be included.
16144 All parts of a date not specified by the user is filled in from
16145 the current date/time. So if you just press return without
16146 typing anything, the time stamp will represent the current
16147 date/time.
16149 If there is already a timestamp at the cursor, it will be
16150 modified.
16152 With two universal prefix arguments, insert an active timestamp
16153 with the current time without prompting the user.
16155 When called from lisp, the timestamp is inactive if INACTIVE is
16156 non-nil."
16157 (interactive "P")
16158 (let* ((ts nil)
16159 (default-time
16160 ;; Default time is either today, or, when entering a range,
16161 ;; the range start.
16162 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16163 (save-excursion
16164 (re-search-backward
16165 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16166 (- (point) 20) t)))
16167 (apply 'encode-time (org-parse-time-string (match-string 1)))
16168 (current-time)))
16169 (default-input (and ts (org-get-compact-tod ts)))
16170 (repeater (save-excursion
16171 (save-match-data
16172 (beginning-of-line)
16173 (when (re-search-forward
16174 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16175 (save-excursion (progn (end-of-line) (point))) t)
16176 (match-string 0)))))
16177 org-time-was-given org-end-time-was-given time)
16178 (cond
16179 ((and (org-at-timestamp-p t)
16180 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16181 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16182 (insert "--")
16183 (setq time (let ((this-command this-command))
16184 (org-read-date arg 'totime nil nil
16185 default-time default-input inactive)))
16186 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16187 ((org-at-timestamp-p t)
16188 (setq time (let ((this-command this-command))
16189 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16190 (when (org-at-timestamp-p t) ; just to get the match data
16191 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16192 (replace-match "")
16193 (setq org-last-changed-timestamp
16194 (org-insert-time-stamp
16195 time (or org-time-was-given arg)
16196 inactive nil nil (list org-end-time-was-given)))
16197 (when repeater (goto-char (1- (point))) (insert " " repeater)
16198 (setq org-last-changed-timestamp
16199 (concat (substring org-last-inserted-timestamp 0 -1)
16200 " " repeater ">"))))
16201 (message "Timestamp updated"))
16202 ((equal arg '(16))
16203 (org-insert-time-stamp (current-time) t inactive))
16205 (setq time (let ((this-command this-command))
16206 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16207 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16208 nil nil (list org-end-time-was-given))))))
16210 ;; FIXME: can we use this for something else, like computing time differences?
16211 (defun org-get-compact-tod (s)
16212 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16213 (let* ((t1 (match-string 1 s))
16214 (h1 (string-to-number (match-string 2 s)))
16215 (m1 (string-to-number (match-string 3 s)))
16216 (t2 (and (match-end 4) (match-string 5 s)))
16217 (h2 (and t2 (string-to-number (match-string 6 s))))
16218 (m2 (and t2 (string-to-number (match-string 7 s))))
16219 dh dm)
16220 (if (not t2)
16222 (setq dh (- h2 h1) dm (- m2 m1))
16223 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16224 (concat t1 "+" (number-to-string dh)
16225 (and (/= 0 dm) (format ":%02d" dm)))))))
16227 (defun org-time-stamp-inactive (&optional arg)
16228 "Insert an inactive time stamp.
16229 An inactive time stamp is enclosed in square brackets instead of angle
16230 brackets. It is inactive in the sense that it does not trigger agenda entries,
16231 does not link to the calendar and cannot be changed with the S-cursor keys.
16232 So these are more for recording a certain time/date."
16233 (interactive "P")
16234 (org-time-stamp arg 'inactive))
16236 (defvar org-date-ovl (make-overlay 1 1))
16237 (overlay-put org-date-ovl 'face 'org-date-selected)
16238 (org-detach-overlay org-date-ovl)
16240 (defvar org-ans1) ; dynamically scoped parameter
16241 (defvar org-ans2) ; dynamically scoped parameter
16243 (defvar org-plain-time-of-day-regexp) ; defined below
16245 (defvar org-overriding-default-time nil) ; dynamically scoped
16246 (defvar org-read-date-overlay nil)
16247 (defvar org-dcst nil) ; dynamically scoped
16248 (defvar org-read-date-history nil)
16249 (defvar org-read-date-final-answer nil)
16250 (defvar org-read-date-analyze-futurep nil)
16251 (defvar org-read-date-analyze-forced-year nil)
16252 (defvar org-read-date-inactive)
16254 (defvar org-read-date-minibuffer-local-map
16255 (let* ((org-replace-disputed-keys nil)
16256 (map (make-sparse-keymap)))
16257 (set-keymap-parent map minibuffer-local-map)
16258 (org-defkey map (kbd ".")
16259 (lambda () (interactive)
16260 ;; Are we at the beginning of the prompt?
16261 (if (looking-back "^[^:]+: ")
16262 (org-eval-in-calendar '(calendar-goto-today))
16263 (insert "."))))
16264 (org-defkey map (kbd "C-.")
16265 (lambda () (interactive)
16266 (org-eval-in-calendar '(calendar-goto-today))))
16267 (org-defkey map [(meta shift left)]
16268 (lambda () (interactive)
16269 (org-eval-in-calendar '(calendar-backward-month 1))))
16270 (org-defkey map [(meta shift right)]
16271 (lambda () (interactive)
16272 (org-eval-in-calendar '(calendar-forward-month 1))))
16273 (org-defkey map [(meta shift up)]
16274 (lambda () (interactive)
16275 (org-eval-in-calendar '(calendar-backward-year 1))))
16276 (org-defkey map [(meta shift down)]
16277 (lambda () (interactive)
16278 (org-eval-in-calendar '(calendar-forward-year 1))))
16279 (org-defkey map [?\e (shift left)]
16280 (lambda () (interactive)
16281 (org-eval-in-calendar '(calendar-backward-month 1))))
16282 (org-defkey map [?\e (shift right)]
16283 (lambda () (interactive)
16284 (org-eval-in-calendar '(calendar-forward-month 1))))
16285 (org-defkey map [?\e (shift up)]
16286 (lambda () (interactive)
16287 (org-eval-in-calendar '(calendar-backward-year 1))))
16288 (org-defkey map [?\e (shift down)]
16289 (lambda () (interactive)
16290 (org-eval-in-calendar '(calendar-forward-year 1))))
16291 (org-defkey map [(shift up)]
16292 (lambda () (interactive)
16293 (org-eval-in-calendar '(calendar-backward-week 1))))
16294 (org-defkey map [(shift down)]
16295 (lambda () (interactive)
16296 (org-eval-in-calendar '(calendar-forward-week 1))))
16297 (org-defkey map [(shift left)]
16298 (lambda () (interactive)
16299 (org-eval-in-calendar '(calendar-backward-day 1))))
16300 (org-defkey map [(shift right)]
16301 (lambda () (interactive)
16302 (org-eval-in-calendar '(calendar-forward-day 1))))
16303 (org-defkey map "!"
16304 (lambda () (interactive)
16305 (org-eval-in-calendar '(diary-view-entries))
16306 (message "")))
16307 (org-defkey map ">"
16308 (lambda () (interactive)
16309 (org-eval-in-calendar '(scroll-calendar-left 1))))
16310 (org-defkey map "<"
16311 (lambda () (interactive)
16312 (org-eval-in-calendar '(scroll-calendar-right 1))))
16313 (org-defkey map "\C-v"
16314 (lambda () (interactive)
16315 (org-eval-in-calendar
16316 '(calendar-scroll-left-three-months 1))))
16317 (org-defkey map "\M-v"
16318 (lambda () (interactive)
16319 (org-eval-in-calendar
16320 '(calendar-scroll-right-three-months 1))))
16321 map)
16322 "Keymap for minibuffer commands when using `org-read-date'.")
16324 (defvar org-def)
16325 (defvar org-defdecode)
16326 (defvar org-with-time)
16328 (defun org-read-date (&optional org-with-time to-time from-string prompt
16329 default-time default-input inactive)
16330 "Read a date, possibly a time, and make things smooth for the user.
16331 The prompt will suggest to enter an ISO date, but you can also enter anything
16332 which will at least partially be understood by `parse-time-string'.
16333 Unrecognized parts of the date will default to the current day, month, year,
16334 hour and minute. If this command is called to replace a timestamp at point,
16335 or to enter the second timestamp of a range, the default time is taken
16336 from the existing stamp. Furthermore, the command prefers the future,
16337 so if you are giving a date where the year is not given, and the day-month
16338 combination is already past in the current year, it will assume you
16339 mean next year. For details, see the manual. A few examples:
16341 3-2-5 --> 2003-02-05
16342 feb 15 --> currentyear-02-15
16343 2/15 --> currentyear-02-15
16344 sep 12 9 --> 2009-09-12
16345 12:45 --> today 12:45
16346 22 sept 0:34 --> currentyear-09-22 0:34
16347 12 --> currentyear-currentmonth-12
16348 Fri --> nearest Friday after today
16349 -Tue --> last Tuesday
16350 etc.
16352 Furthermore you can specify a relative date by giving, as the *first* thing
16353 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16354 change in days weeks, months, years.
16355 With a single plus or minus, the date is relative to today. With a double
16356 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16357 +4d --> four days from today
16358 +4 --> same as above
16359 +2w --> two weeks from today
16360 ++5 --> five days from default date
16362 The function understands only English month and weekday abbreviations.
16364 While prompting, a calendar is popped up - you can also select the
16365 date with the mouse (button 1). The calendar shows a period of three
16366 months. To scroll it to other months, use the keys `>' and `<'.
16367 If you don't like the calendar, turn it off with
16368 \(setq org-read-date-popup-calendar nil)
16370 With optional argument TO-TIME, the date will immediately be converted
16371 to an internal time.
16372 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16373 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16374 still enter a time, and this function will inform the calling routine
16375 about this change. The calling routine may then choose to change the
16376 format used to insert the time stamp into the buffer to include the time.
16377 With optional argument FROM-STRING, read from this string instead from
16378 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16379 the time/date that is used for everything that is not specified by the
16380 user."
16381 (require 'parse-time)
16382 (let* ((org-time-stamp-rounding-minutes
16383 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16384 (org-dcst org-display-custom-times)
16385 (ct (org-current-time))
16386 (org-def (or org-overriding-default-time default-time ct))
16387 (org-defdecode (decode-time org-def))
16388 (dummy (progn
16389 (when (< (nth 2 org-defdecode) org-extend-today-until)
16390 (setcar (nthcdr 2 org-defdecode) -1)
16391 (setcar (nthcdr 1 org-defdecode) 59)
16392 (setq org-def (apply 'encode-time org-defdecode)
16393 org-defdecode (decode-time org-def)))))
16394 (mouse-autoselect-window nil) ; Don't let the mouse jump
16395 (calendar-frame-setup nil)
16396 (calendar-setup nil)
16397 (calendar-move-hook nil)
16398 (calendar-view-diary-initially-flag nil)
16399 (calendar-view-holidays-initially-flag nil)
16400 (timestr (format-time-string
16401 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16402 (prompt (concat (if prompt (concat prompt " ") "")
16403 (format "Date+time [%s]: " timestr)))
16404 ans (org-ans0 "") org-ans1 org-ans2 final)
16406 (cond
16407 (from-string (setq ans from-string))
16408 (org-read-date-popup-calendar
16409 (save-excursion
16410 (save-window-excursion
16411 (calendar)
16412 (org-eval-in-calendar '(setq cursor-type nil) t)
16413 (unwind-protect
16414 (progn
16415 (calendar-forward-day (- (time-to-days org-def)
16416 (calendar-absolute-from-gregorian
16417 (calendar-current-date))))
16418 (org-eval-in-calendar nil t)
16419 (let* ((old-map (current-local-map))
16420 (map (copy-keymap calendar-mode-map))
16421 (minibuffer-local-map
16422 (copy-keymap org-read-date-minibuffer-local-map)))
16423 (org-defkey map (kbd "RET") 'org-calendar-select)
16424 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16425 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16426 (unwind-protect
16427 (progn
16428 (use-local-map map)
16429 (setq org-read-date-inactive inactive)
16430 (add-hook 'post-command-hook 'org-read-date-display)
16431 (setq org-ans0 (read-string prompt default-input
16432 'org-read-date-history nil))
16433 ;; org-ans0: from prompt
16434 ;; org-ans1: from mouse click
16435 ;; org-ans2: from calendar motion
16436 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16437 (remove-hook 'post-command-hook 'org-read-date-display)
16438 (use-local-map old-map)
16439 (when org-read-date-overlay
16440 (delete-overlay org-read-date-overlay)
16441 (setq org-read-date-overlay nil)))))
16442 (bury-buffer "*Calendar*")))))
16444 (t ; Naked prompt only
16445 (unwind-protect
16446 (setq ans (read-string prompt default-input
16447 'org-read-date-history timestr))
16448 (when org-read-date-overlay
16449 (delete-overlay org-read-date-overlay)
16450 (setq org-read-date-overlay nil)))))
16452 (setq final (org-read-date-analyze ans org-def org-defdecode))
16454 (when org-read-date-analyze-forced-year
16455 (message "Year was forced into %s"
16456 (if org-read-date-force-compatible-dates
16457 "compatible range (1970-2037)"
16458 "range representable on this machine"))
16459 (ding))
16461 ;; One round trip to get rid of 34th of August and stuff like that....
16462 (setq final (decode-time (apply 'encode-time final)))
16464 (setq org-read-date-final-answer ans)
16466 (if to-time
16467 (apply 'encode-time final)
16468 (if (and (boundp 'org-time-was-given) org-time-was-given)
16469 (format "%04d-%02d-%02d %02d:%02d"
16470 (nth 5 final) (nth 4 final) (nth 3 final)
16471 (nth 2 final) (nth 1 final))
16472 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16474 (defun org-read-date-display ()
16475 "Display the current date prompt interpretation in the minibuffer."
16476 (when org-read-date-display-live
16477 (when org-read-date-overlay
16478 (delete-overlay org-read-date-overlay))
16479 (when (minibufferp (current-buffer))
16480 (save-excursion
16481 (end-of-line 1)
16482 (while (not (equal (buffer-substring
16483 (max (point-min) (- (point) 4)) (point))
16484 " "))
16485 (insert " ")))
16486 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16487 " " (or org-ans1 org-ans2)))
16488 (org-end-time-was-given nil)
16489 (f (org-read-date-analyze ans org-def org-defdecode))
16490 (fmts (if org-dcst
16491 org-time-stamp-custom-formats
16492 org-time-stamp-formats))
16493 (fmt (if (or org-with-time
16494 (and (boundp 'org-time-was-given) org-time-was-given))
16495 (cdr fmts)
16496 (car fmts)))
16497 (txt (format-time-string fmt (apply 'encode-time f)))
16498 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16499 (txt (concat "=> " txt)))
16500 (when (and org-end-time-was-given
16501 (string-match org-plain-time-of-day-regexp txt))
16502 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16503 org-end-time-was-given
16504 (substring txt (match-end 0)))))
16505 (when org-read-date-analyze-futurep
16506 (setq txt (concat txt " (=>F)")))
16507 (setq org-read-date-overlay
16508 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16509 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16511 (defun org-read-date-analyze (ans org-def org-defdecode)
16512 "Analyze the combined answer of the date prompt."
16513 ;; FIXME: cleanup and comment
16514 (let ((nowdecode (decode-time (current-time)))
16515 delta deltan deltaw deltadef year month day
16516 hour minute second wday pm h2 m2 tl wday1
16517 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16518 (setq org-read-date-analyze-futurep nil
16519 org-read-date-analyze-forced-year nil)
16520 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16521 (setq ans "+0"))
16523 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16524 (setq ans (replace-match "" t t ans)
16525 deltan (car delta)
16526 deltaw (nth 1 delta)
16527 deltadef (nth 2 delta)))
16529 ;; Check if there is an iso week date in there. If yes, store the
16530 ;; info and postpone interpreting it until the rest of the parsing
16531 ;; is done.
16532 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16533 (setq iso-year (if (match-end 1)
16534 (org-small-year-to-year
16535 (string-to-number (match-string 1 ans))))
16536 iso-weekday (if (match-end 3)
16537 (string-to-number (match-string 3 ans)))
16538 iso-week (string-to-number (match-string 2 ans)))
16539 (setq ans (replace-match "" t t ans)))
16541 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16542 (when (string-match
16543 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16544 (setq year (if (match-end 2)
16545 (string-to-number (match-string 2 ans))
16546 (progn (setq kill-year t)
16547 (string-to-number (format-time-string "%Y"))))
16548 month (string-to-number (match-string 3 ans))
16549 day (string-to-number (match-string 4 ans)))
16550 (if (< year 100) (setq year (+ 2000 year)))
16551 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16552 t nil ans)))
16554 ;; Help matching dotted european dates
16555 (when (string-match
16556 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16557 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16558 (setq kill-year t)
16559 (string-to-number (format-time-string "%Y")))
16560 day (string-to-number (match-string 1 ans))
16561 month (string-to-number (match-string 2 ans))
16562 ans (replace-match (format "%04d-%02d-%02d" year month day)
16563 t nil ans)))
16565 ;; Help matching american dates, like 5/30 or 5/30/7
16566 (when (string-match
16567 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16568 (setq year (if (match-end 4)
16569 (string-to-number (match-string 4 ans))
16570 (progn (setq kill-year t)
16571 (string-to-number (format-time-string "%Y"))))
16572 month (string-to-number (match-string 1 ans))
16573 day (string-to-number (match-string 2 ans)))
16574 (if (< year 100) (setq year (+ 2000 year)))
16575 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16576 t nil ans)))
16577 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16578 ;; If there is a time with am/pm, and *no* time without it, we convert
16579 ;; so that matching will be successful.
16580 (loop for i from 1 to 2 do ; twice, for end time as well
16581 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16582 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16583 (setq hour (string-to-number (match-string 1 ans))
16584 minute (if (match-end 3)
16585 (string-to-number (match-string 3 ans))
16587 pm (equal ?p
16588 (string-to-char (downcase (match-string 4 ans)))))
16589 (if (and (= hour 12) (not pm))
16590 (setq hour 0)
16591 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16592 (setq ans (replace-match (format "%02d:%02d" hour minute)
16593 t t ans))))
16595 ;; Check if a time range is given as a duration
16596 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16597 (setq hour (string-to-number (match-string 1 ans))
16598 h2 (+ hour (string-to-number (match-string 3 ans)))
16599 minute (string-to-number (match-string 2 ans))
16600 m2 (+ minute (if (match-end 5) (string-to-number
16601 (match-string 5 ans))0)))
16602 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16603 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16604 t t ans)))
16606 ;; Check if there is a time range
16607 (when (boundp 'org-end-time-was-given)
16608 (setq org-time-was-given nil)
16609 (when (and (string-match org-plain-time-of-day-regexp ans)
16610 (match-end 8))
16611 (setq org-end-time-was-given (match-string 8 ans))
16612 (setq ans (concat (substring ans 0 (match-beginning 7))
16613 (substring ans (match-end 7))))))
16615 (setq tl (parse-time-string ans)
16616 day (or (nth 3 tl) (nth 3 org-defdecode))
16617 month (or (nth 4 tl)
16618 (if (and org-read-date-prefer-future
16619 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16620 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16621 (nth 4 org-defdecode)))
16622 year (or (and (not kill-year) (nth 5 tl))
16623 (if (and org-read-date-prefer-future
16624 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16625 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16626 (nth 5 org-defdecode)))
16627 hour (or (nth 2 tl) (nth 2 org-defdecode))
16628 minute (or (nth 1 tl) (nth 1 org-defdecode))
16629 second (or (nth 0 tl) 0)
16630 wday (nth 6 tl))
16632 (when (and (eq org-read-date-prefer-future 'time)
16633 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16634 (equal day (nth 3 nowdecode))
16635 (equal month (nth 4 nowdecode))
16636 (equal year (nth 5 nowdecode))
16637 (nth 2 tl)
16638 (or (< (nth 2 tl) (nth 2 nowdecode))
16639 (and (= (nth 2 tl) (nth 2 nowdecode))
16640 (nth 1 tl)
16641 (< (nth 1 tl) (nth 1 nowdecode)))))
16642 (setq day (1+ day)
16643 futurep t))
16645 ;; Special date definitions below
16646 (cond
16647 (iso-week
16648 ;; There was an iso week
16649 (require 'cal-iso)
16650 (setq futurep nil)
16651 (setq year (or iso-year year)
16652 day (or iso-weekday wday 1)
16653 wday nil ; to make sure that the trigger below does not match
16654 iso-date (calendar-gregorian-from-absolute
16655 (calendar-absolute-from-iso
16656 (list iso-week day year))))
16657 ; FIXME: Should we also push ISO weeks into the future?
16658 ; (when (and org-read-date-prefer-future
16659 ; (not iso-year)
16660 ; (< (calendar-absolute-from-gregorian iso-date)
16661 ; (time-to-days (current-time))))
16662 ; (setq year (1+ year)
16663 ; iso-date (calendar-gregorian-from-absolute
16664 ; (calendar-absolute-from-iso
16665 ; (list iso-week day year)))))
16666 (setq month (car iso-date)
16667 year (nth 2 iso-date)
16668 day (nth 1 iso-date)))
16669 (deltan
16670 (setq futurep nil)
16671 (unless deltadef
16672 (let ((now (decode-time (current-time))))
16673 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16674 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16675 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16676 ((equal deltaw "m") (setq month (+ month deltan)))
16677 ((equal deltaw "y") (setq year (+ year deltan)))))
16678 ((and wday (not (nth 3 tl)))
16679 ;; Weekday was given, but no day, so pick that day in the week
16680 ;; on or after the derived date.
16681 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16682 (unless (equal wday wday1)
16683 (setq day (+ day (% (- wday wday1 -7) 7))))))
16684 (if (and (boundp 'org-time-was-given)
16685 (nth 2 tl))
16686 (setq org-time-was-given t))
16687 (if (< year 100) (setq year (+ 2000 year)))
16688 ;; Check of the date is representable
16689 (if org-read-date-force-compatible-dates
16690 (progn
16691 (if (< year 1970)
16692 (setq year 1970 org-read-date-analyze-forced-year t))
16693 (if (> year 2037)
16694 (setq year 2037 org-read-date-analyze-forced-year t)))
16695 (condition-case nil
16696 (ignore (encode-time second minute hour day month year))
16697 (error
16698 (setq year (nth 5 org-defdecode))
16699 (setq org-read-date-analyze-forced-year t))))
16700 (setq org-read-date-analyze-futurep futurep)
16701 (list second minute hour day month year)))
16703 (defvar parse-time-weekdays)
16704 (defun org-read-date-get-relative (s today default)
16705 "Check string S for special relative date string.
16706 TODAY and DEFAULT are internal times, for today and for a default.
16707 Return shift list (N what def-flag)
16708 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16709 N is the number of WHATs to shift.
16710 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16711 the DEFAULT date rather than TODAY."
16712 (require 'parse-time)
16713 (when (and
16714 (string-match
16715 (concat
16716 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16717 "\\([0-9]+\\)?"
16718 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16719 "\\([ \t]\\|$\\)") s)
16720 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16721 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16722 (string-to-char (substring (match-string 1 s) -1))
16723 ?+))
16724 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16725 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16726 (what (if (match-end 3) (match-string 3 s) "d"))
16727 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16728 (date (if rel default today))
16729 (wday (nth 6 (decode-time date)))
16730 delta)
16731 (if wday1
16732 (progn
16733 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16734 (if (= delta 0) (setq delta 7))
16735 (if (= dir ?-)
16736 (progn
16737 (setq delta (- delta 7))
16738 (if (= delta 0) (setq delta -7))))
16739 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16740 (list delta "d" rel))
16741 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16743 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16744 "Turn a user-specified date into the internal representation.
16745 The internal representation needed by the calendar is (month day year).
16746 This is a wrapper to handle the brain-dead convention in calendar that
16747 user function argument order change dependent on argument order."
16748 (if (boundp 'calendar-date-style)
16749 (cond
16750 ((eq calendar-date-style 'american)
16751 (list arg1 arg2 arg3))
16752 ((eq calendar-date-style 'european)
16753 (list arg2 arg1 arg3))
16754 ((eq calendar-date-style 'iso)
16755 (list arg2 arg3 arg1)))
16756 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16757 (if (org-bound-and-true-p european-calendar-style)
16758 (list arg2 arg1 arg3)
16759 (list arg1 arg2 arg3)))))
16761 (defun org-eval-in-calendar (form &optional keepdate)
16762 "Eval FORM in the calendar window and return to current window.
16763 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16764 otherwise stick to the current value of `org-ans2'."
16765 (let ((sf (selected-frame))
16766 (sw (selected-window)))
16767 (select-window (get-buffer-window "*Calendar*" t))
16768 (eval form)
16769 (when (and (not keepdate) (calendar-cursor-to-date))
16770 (let* ((date (calendar-cursor-to-date))
16771 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16772 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16773 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16774 (select-window sw)
16775 (org-select-frame-set-input-focus sf)))
16777 (defun org-calendar-select ()
16778 "Return to `org-read-date' with the date currently selected.
16779 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16780 (interactive)
16781 (when (calendar-cursor-to-date)
16782 (let* ((date (calendar-cursor-to-date))
16783 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16784 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16785 (if (active-minibuffer-window) (exit-minibuffer))))
16787 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16788 "Insert a date stamp for the date given by the internal TIME.
16789 WITH-HM means use the stamp format that includes the time of the day.
16790 INACTIVE means use square brackets instead of angular ones, so that the
16791 stamp will not contribute to the agenda.
16792 PRE and POST are optional strings to be inserted before and after the
16793 stamp.
16794 The command returns the inserted time stamp."
16795 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16796 stamp)
16797 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16798 (insert-before-markers (or pre ""))
16799 (when (listp extra)
16800 (setq extra (car extra))
16801 (if (and (stringp extra)
16802 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16803 (setq extra (format "-%02d:%02d"
16804 (string-to-number (match-string 1 extra))
16805 (string-to-number (match-string 2 extra))))
16806 (setq extra nil)))
16807 (when extra
16808 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16809 (insert-before-markers (setq stamp (format-time-string fmt time)))
16810 (insert-before-markers (or post ""))
16811 (setq org-last-inserted-timestamp stamp)))
16813 (defun org-toggle-time-stamp-overlays ()
16814 "Toggle the use of custom time stamp formats."
16815 (interactive)
16816 (setq org-display-custom-times (not org-display-custom-times))
16817 (unless org-display-custom-times
16818 (let ((p (point-min)) (bmp (buffer-modified-p)))
16819 (while (setq p (next-single-property-change p 'display))
16820 (if (and (get-text-property p 'display)
16821 (eq (get-text-property p 'face) 'org-date))
16822 (remove-text-properties
16823 p (setq p (next-single-property-change p 'display))
16824 '(display t))))
16825 (set-buffer-modified-p bmp)))
16826 (if (featurep 'xemacs)
16827 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16828 (org-restart-font-lock)
16829 (setq org-table-may-need-update t)
16830 (if org-display-custom-times
16831 (message "Time stamps are overlaid with custom format")
16832 (message "Time stamp overlays removed")))
16834 (defun org-display-custom-time (beg end)
16835 "Overlay modified time stamp format over timestamp between BEG and END."
16836 (let* ((ts (buffer-substring beg end))
16837 t1 w1 with-hm tf time str w2 (off 0))
16838 (save-match-data
16839 (setq t1 (org-parse-time-string ts t))
16840 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16841 (setq off (- (match-end 0) (match-beginning 0)))))
16842 (setq end (- end off))
16843 (setq w1 (- end beg)
16844 with-hm (and (nth 1 t1) (nth 2 t1))
16845 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16846 time (org-fix-decoded-time t1)
16847 str (org-add-props
16848 (format-time-string
16849 (substring tf 1 -1) (apply 'encode-time time))
16850 nil 'mouse-face 'highlight)
16851 w2 (length str))
16852 (if (not (= w2 w1))
16853 (add-text-properties (1+ beg) (+ 2 beg)
16854 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16855 (if (featurep 'xemacs)
16856 (progn
16857 (put-text-property beg end 'invisible t)
16858 (put-text-property beg end 'end-glyph (make-glyph str)))
16859 (put-text-property beg end 'display str))))
16861 (defun org-translate-time (string)
16862 "Translate all timestamps in STRING to custom format.
16863 But do this only if the variable `org-display-custom-times' is set."
16864 (when org-display-custom-times
16865 (save-match-data
16866 (let* ((start 0)
16867 (re org-ts-regexp-both)
16868 t1 with-hm inactive tf time str beg end)
16869 (while (setq start (string-match re string start))
16870 (setq beg (match-beginning 0)
16871 end (match-end 0)
16872 t1 (save-match-data
16873 (org-parse-time-string (substring string beg end) t))
16874 with-hm (and (nth 1 t1) (nth 2 t1))
16875 inactive (equal (substring string beg (1+ beg)) "[")
16876 tf (funcall (if with-hm 'cdr 'car)
16877 org-time-stamp-custom-formats)
16878 time (org-fix-decoded-time t1)
16879 str (format-time-string
16880 (concat
16881 (if inactive "[" "<") (substring tf 1 -1)
16882 (if inactive "]" ">"))
16883 (apply 'encode-time time))
16884 string (replace-match str t t string)
16885 start (+ start (length str)))))))
16886 string)
16888 (defun org-fix-decoded-time (time)
16889 "Set 0 instead of nil for the first 6 elements of time.
16890 Don't touch the rest."
16891 (let ((n 0))
16892 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16894 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16896 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16897 "Difference between TIMESTAMP-STRING and now in days.
16898 If SECONDS is non-nil, return the difference in seconds."
16899 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16900 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16901 (funcall fdiff (current-time)))))
16903 (defun org-deadline-close (timestamp-string &optional ndays)
16904 "Is the time in TIMESTAMP-STRING close to the current date?"
16905 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16906 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16907 (not (org-entry-is-done-p))))
16909 (defun org-get-wdays (ts &optional delay zero-delay)
16910 "Get the deadline lead time appropriate for timestring TS.
16911 When DELAY is non-nil, get the delay time for scheduled items
16912 instead of the deadline lead time. When ZERO-DELAY is non-nil
16913 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16914 don't try to find the delay cookie in the scheduled timestamp."
16915 (let ((tv (if delay org-scheduled-delay-days
16916 org-deadline-warning-days)))
16917 (cond
16918 ((or (and delay (< tv 0))
16919 (and delay zero-delay (<= tv 0))
16920 (and (not delay) (<= tv 0)))
16921 ;; Enforce this value no matter what
16922 (- tv))
16923 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16924 ;; lead time is specified.
16925 (floor (* (string-to-number (match-string 1 ts))
16926 (cdr (assoc (match-string 2 ts)
16927 '(("d" . 1) ("w" . 7)
16928 ("m" . 30.4) ("y" . 365.25)
16929 ("h" . 0.041667)))))))
16930 ;; go for the default.
16931 (t tv))))
16933 (defun org-calendar-select-mouse (ev)
16934 "Return to `org-read-date' with the date currently selected.
16935 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16936 (interactive "e")
16937 (mouse-set-point ev)
16938 (when (calendar-cursor-to-date)
16939 (let* ((date (calendar-cursor-to-date))
16940 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16941 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16942 (if (active-minibuffer-window) (exit-minibuffer))))
16944 (defun org-check-deadlines (ndays)
16945 "Check if there are any deadlines due or past due.
16946 A deadline is considered due if it happens within `org-deadline-warning-days'
16947 days from today's date. If the deadline appears in an entry marked DONE,
16948 it is not shown. The prefix arg NDAYS can be used to test that many
16949 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16950 (interactive "P")
16951 (let* ((org-warn-days
16952 (cond
16953 ((equal ndays '(4)) 100000)
16954 (ndays (prefix-numeric-value ndays))
16955 (t (abs org-deadline-warning-days))))
16956 (case-fold-search nil)
16957 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16958 (callback
16959 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16961 (message "%d deadlines past-due or due within %d days"
16962 (org-occur regexp nil callback)
16963 org-warn-days)))
16965 (defsubst org-re-timestamp (type)
16966 "Return a regexp for timestamp TYPE.
16967 Allowed values for TYPE are:
16969 all: all timestamps
16970 active: only active timestamps (<...>)
16971 inactive: only inactive timestamps ([...])
16972 scheduled: only scheduled timestamps
16973 deadline: only deadline timestamps
16974 closed: only closed time-stamps
16976 When TYPE is nil, fall back on returning a regexp that matches
16977 both scheduled and deadline timestamps."
16978 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16979 ((eq type 'active) org-ts-regexp)
16980 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16981 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16982 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16983 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16984 ((eq type 'scheduled-or-deadline)
16985 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16987 (defun org-check-before-date (date)
16988 "Check if there are deadlines or scheduled entries before DATE."
16989 (interactive (list (org-read-date)))
16990 (let ((case-fold-search nil)
16991 (regexp (org-re-timestamp org-ts-type))
16992 (callback
16993 (lambda () (time-less-p
16994 (org-time-string-to-time (match-string 1))
16995 (org-time-string-to-time date)))))
16996 (message "%d entries before %s"
16997 (org-occur regexp nil callback) date)))
16999 (defun org-check-after-date (date)
17000 "Check if there are deadlines or scheduled entries after DATE."
17001 (interactive (list (org-read-date)))
17002 (let ((case-fold-search nil)
17003 (regexp (org-re-timestamp org-ts-type))
17004 (callback
17005 (lambda () (not
17006 (time-less-p
17007 (org-time-string-to-time (match-string 1))
17008 (org-time-string-to-time date))))))
17009 (message "%d entries after %s"
17010 (org-occur regexp nil callback) date)))
17012 (defun org-check-dates-range (start-date end-date)
17013 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17014 (interactive (list (org-read-date nil nil nil "Range starts")
17015 (org-read-date nil nil nil "Range end")))
17016 (let ((case-fold-search nil)
17017 (regexp (org-re-timestamp org-ts-type))
17018 (callback
17019 (lambda ()
17020 (let ((match (match-string 1)))
17021 (and
17022 (not (time-less-p
17023 (org-time-string-to-time match)
17024 (org-time-string-to-time start-date)))
17025 (time-less-p
17026 (org-time-string-to-time match)
17027 (org-time-string-to-time end-date)))))))
17028 (message "%d entries between %s and %s"
17029 (org-occur regexp nil callback) start-date end-date)))
17031 (defun org-evaluate-time-range (&optional to-buffer)
17032 "Evaluate a time range by computing the difference between start and end.
17033 Normally the result is just printed in the echo area, but with prefix arg
17034 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17035 If the time range is actually in a table, the result is inserted into the
17036 next column.
17037 For time difference computation, a year is assumed to be exactly 365
17038 days in order to avoid rounding problems."
17039 (interactive "P")
17041 (org-clock-update-time-maybe)
17042 (save-excursion
17043 (unless (org-at-date-range-p t)
17044 (goto-char (point-at-bol))
17045 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17046 (if (not (org-at-date-range-p t))
17047 (user-error "Not at a time-stamp range, and none found in current line")))
17048 (let* ((ts1 (match-string 1))
17049 (ts2 (match-string 2))
17050 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17051 (match-end (match-end 0))
17052 (time1 (org-time-string-to-time ts1))
17053 (time2 (org-time-string-to-time ts2))
17054 (t1 (org-float-time time1))
17055 (t2 (org-float-time time2))
17056 (diff (abs (- t2 t1)))
17057 (negative (< (- t2 t1) 0))
17058 ;; (ys (floor (* 365 24 60 60)))
17059 (ds (* 24 60 60))
17060 (hs (* 60 60))
17061 (fy "%dy %dd %02d:%02d")
17062 (fy1 "%dy %dd")
17063 (fd "%dd %02d:%02d")
17064 (fd1 "%dd")
17065 (fh "%02d:%02d")
17066 y d h m align)
17067 (if havetime
17068 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17070 d (floor (/ diff ds)) diff (mod diff ds)
17071 h (floor (/ diff hs)) diff (mod diff hs)
17072 m (floor (/ diff 60)))
17073 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17075 d (floor (+ (/ diff ds) 0.5))
17076 h 0 m 0))
17077 (if (not to-buffer)
17078 (message "%s" (org-make-tdiff-string y d h m))
17079 (if (org-at-table-p)
17080 (progn
17081 (goto-char match-end)
17082 (setq align t)
17083 (and (looking-at " *|") (goto-char (match-end 0))))
17084 (goto-char match-end))
17085 (if (looking-at
17086 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17087 (replace-match ""))
17088 (if negative (insert " -"))
17089 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17090 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17091 (insert " " (format fh h m))))
17092 (if align (org-table-align))
17093 (message "Time difference inserted")))))
17095 (defun org-make-tdiff-string (y d h m)
17096 (let ((fmt "")
17097 (l nil))
17098 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17099 l (push y l)))
17100 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17101 l (push d l)))
17102 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17103 l (push h l)))
17104 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17105 l (push m l)))
17106 (apply 'format fmt (nreverse l))))
17108 (defun org-time-string-to-time (s &optional buffer pos)
17109 "Convert a timestamp string into internal time."
17110 (condition-case errdata
17111 (apply 'encode-time (org-parse-time-string s))
17112 (error (error "Bad timestamp `%s'%s\nError was: %s"
17113 s (if (not (and buffer pos))
17115 (format " at %d in buffer `%s'" pos buffer))
17116 (cdr errdata)))))
17118 (defun org-time-string-to-seconds (s)
17119 "Convert a timestamp string to a number of seconds."
17120 (org-float-time (org-time-string-to-time s)))
17122 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17123 "Convert a time stamp to an absolute day number.
17124 If there is a specifier for a cyclic time stamp, get the closest
17125 date to DAYNR.
17126 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17127 The variable `date' is bound by the calendar when this is called."
17128 (cond
17129 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17130 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17131 daynr
17132 (+ daynr 1000)))
17133 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17134 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17135 (time-to-days (current-time))) (match-string 0 s)
17136 prefer show-all))
17137 (t (time-to-days
17138 (condition-case errdata
17139 (apply 'encode-time (org-parse-time-string s))
17140 (error (error "Bad timestamp `%s'%s\nError was: %s"
17141 s (if (not (and buffer pos))
17143 (format " at %d in buffer `%s'" pos buffer))
17144 (cdr errdata))))))))
17146 (defun org-days-to-iso-week (days)
17147 "Return the iso week number."
17148 (require 'cal-iso)
17149 (car (calendar-iso-from-absolute days)))
17151 (defun org-small-year-to-year (year)
17152 "Convert 2-digit years into 4-digit years.
17153 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17154 The year 2000 cannot be abbreviated. Any year larger than 99
17155 is returned unchanged."
17156 (if (< year 38)
17157 (setq year (+ 2000 year))
17158 (if (< year 100)
17159 (setq year (+ 1900 year))))
17160 year)
17162 (defun org-time-from-absolute (d)
17163 "Return the time corresponding to date D.
17164 D may be an absolute day number, or a calendar-type list (month day year)."
17165 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17166 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17168 (defun org-calendar-holiday ()
17169 "List of holidays, for Diary display in Org-mode."
17170 (require 'holidays)
17171 (let ((hl (funcall
17172 (if (fboundp 'calendar-check-holidays)
17173 'calendar-check-holidays 'check-calendar-holidays) date)))
17174 (if hl (mapconcat 'identity hl "; "))))
17176 (defun org-diary-sexp-entry (sexp entry date)
17177 "Process a SEXP diary ENTRY for DATE."
17178 (require 'diary-lib)
17179 (let ((result (if calendar-debug-sexp
17180 (let ((stack-trace-on-error t))
17181 (eval (car (read-from-string sexp))))
17182 (condition-case nil
17183 (eval (car (read-from-string sexp)))
17184 (error
17185 (beep)
17186 (message "Bad sexp at line %d in %s: %s"
17187 (org-current-line)
17188 (buffer-file-name) sexp)
17189 (sleep-for 2))))))
17190 (cond ((stringp result) (split-string result "; "))
17191 ((and (consp result)
17192 (not (consp (cdr result)))
17193 (stringp (cdr result))) (cdr result))
17194 ((and (consp result)
17195 (stringp (car result))) result)
17196 (result entry))))
17198 (defun org-diary-to-ical-string (frombuf)
17199 "Get iCalendar entries from diary entries in buffer FROMBUF.
17200 This uses the icalendar.el library."
17201 (let* ((tmpdir (if (featurep 'xemacs)
17202 (temp-directory)
17203 temporary-file-directory))
17204 (tmpfile (make-temp-name
17205 (expand-file-name "orgics" tmpdir)))
17206 buf rtn b e)
17207 (with-current-buffer frombuf
17208 (icalendar-export-region (point-min) (point-max) tmpfile)
17209 (setq buf (find-buffer-visiting tmpfile))
17210 (set-buffer buf)
17211 (goto-char (point-min))
17212 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17213 (setq b (match-beginning 0)))
17214 (goto-char (point-max))
17215 (if (re-search-backward "^END:VEVENT" nil t)
17216 (setq e (match-end 0)))
17217 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17218 (kill-buffer buf)
17219 (delete-file tmpfile)
17220 rtn))
17222 (defun org-closest-date (start current change prefer show-all)
17223 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17224 When PREFER is `past', return a date that is either CURRENT or past.
17225 When PREFER is `future', return a date that is either CURRENT or future.
17226 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17227 ;; Make the proper lists from the dates
17228 (catch 'exit
17229 (let ((a1 '(("h" . hour)
17230 ("d" . day)
17231 ("w" . week)
17232 ("m" . month)
17233 ("y" . year)))
17234 (shour (nth 2 (org-parse-time-string start)))
17235 dn dw sday cday n1 n2 n0
17236 d m y y1 y2 date1 date2 nmonths nm ny m2)
17238 (setq start (org-date-to-gregorian start)
17239 current (org-date-to-gregorian
17240 (if show-all
17241 current
17242 (time-to-days (current-time))))
17243 sday (calendar-absolute-from-gregorian start)
17244 cday (calendar-absolute-from-gregorian current))
17246 (if (<= cday sday) (throw 'exit sday))
17248 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17249 (setq dn (string-to-number (match-string 1 change))
17250 dw (cdr (assoc (match-string 2 change) a1)))
17251 (user-error "Invalid change specifier: %s" change))
17252 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17253 (cond
17254 ((eq dw 'hour)
17255 (let ((missing-hours
17256 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17257 dn)))
17258 (setq n1 (if (zerop missing-hours) cday
17259 (- cday (1+ (floor (/ missing-hours 24)))))
17260 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17261 ((eq dw 'day)
17262 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17263 n2 (+ n1 dn)))
17264 ((eq dw 'year)
17265 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17266 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17267 (setq date1 (list m d y1)
17268 n1 (calendar-absolute-from-gregorian date1)
17269 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17270 n2 (calendar-absolute-from-gregorian date2)))
17271 ((eq dw 'month)
17272 ;; approx number of month between the two dates
17273 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17274 ;; How often does dn fit in there?
17275 (setq d (nth 1 start) m (car start) y (nth 2 start)
17276 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17277 m (+ m nm)
17278 ny (floor (/ m 12))
17279 y (+ y ny)
17280 m (- m (* ny 12)))
17281 (while (> m 12) (setq m (- m 12) y (1+ y)))
17282 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17283 (setq m2 (+ m dn) y2 y)
17284 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17285 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17286 (while (<= n2 cday)
17287 (setq n1 n2 m m2 y y2)
17288 (setq m2 (+ m dn) y2 y)
17289 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17290 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17291 ;; Make sure n1 is the earlier date
17292 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17293 (if show-all
17294 (cond
17295 ((eq prefer 'past) (if (= cday n2) n2 n1))
17296 ((eq prefer 'future) (if (= cday n1) n1 n2))
17297 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17298 (cond
17299 ((eq prefer 'past) (if (= cday n2) n2 n1))
17300 ((eq prefer 'future) (if (= cday n1) n1 n2))
17301 (t (if (= cday n1) n1 n2)))))))
17303 (defun org-date-to-gregorian (date)
17304 "Turn any specification of DATE into a Gregorian date for the calendar."
17305 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17306 ((and (listp date) (= (length date) 3)) date)
17307 ((stringp date)
17308 (setq date (org-parse-time-string date))
17309 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17310 ((listp date)
17311 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17313 (defun org-parse-time-string (s &optional nodefault)
17314 "Parse the standard Org-mode time string.
17315 This should be a lot faster than the normal `parse-time-string'.
17316 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17317 hour and minute fields will be nil if not given."
17318 (cond ((string-match org-ts-regexp0 s)
17319 (list 0
17320 (if (or (match-beginning 8) (not nodefault))
17321 (string-to-number (or (match-string 8 s) "0")))
17322 (if (or (match-beginning 7) (not nodefault))
17323 (string-to-number (or (match-string 7 s) "0")))
17324 (string-to-number (match-string 4 s))
17325 (string-to-number (match-string 3 s))
17326 (string-to-number (match-string 2 s))
17327 nil nil nil))
17328 ((string-match "^<[^>]+>$" s)
17329 (decode-time (seconds-to-time (org-matcher-time s))))
17330 (t (error "Not a standard Org-mode time string: %s" s))))
17332 (defun org-timestamp-up (&optional arg)
17333 "Increase the date item at the cursor by one.
17334 If the cursor is on the year, change the year. If it is on the month,
17335 the day or the time, change that.
17336 With prefix ARG, change by that many units."
17337 (interactive "p")
17338 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17340 (defun org-timestamp-down (&optional arg)
17341 "Decrease the date item at the cursor by one.
17342 If the cursor is on the year, change the year. If it is on the month,
17343 the day or the time, change that.
17344 With prefix ARG, change by that many units."
17345 (interactive "p")
17346 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17348 (defun org-timestamp-up-day (&optional arg)
17349 "Increase the date in the time stamp by one day.
17350 With prefix ARG, change that many days."
17351 (interactive "p")
17352 (if (and (not (org-at-timestamp-p t))
17353 (org-at-heading-p))
17354 (org-todo 'up)
17355 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17357 (defun org-timestamp-down-day (&optional arg)
17358 "Decrease the date in the time stamp by one day.
17359 With prefix ARG, change that many days."
17360 (interactive "p")
17361 (if (and (not (org-at-timestamp-p t))
17362 (org-at-heading-p))
17363 (org-todo 'down)
17364 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17366 (defun org-at-timestamp-p (&optional inactive-ok)
17367 "Determine if the cursor is in or at a timestamp."
17368 (interactive)
17369 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17370 (pos (point))
17371 (ans (or (looking-at tsr)
17372 (save-excursion
17373 (skip-chars-backward "^[<\n\r\t")
17374 (if (> (point) (point-min)) (backward-char 1))
17375 (and (looking-at tsr)
17376 (> (- (match-end 0) pos) -1))))))
17377 (and ans
17378 (boundp 'org-ts-what)
17379 (setq org-ts-what
17380 (cond
17381 ((= pos (match-beginning 0)) 'bracket)
17382 ;; Point is considered to be "on the bracket" whether
17383 ;; it's really on it or right after it.
17384 ((= pos (1- (match-end 0))) 'bracket)
17385 ((= pos (match-end 0)) 'after)
17386 ((org-pos-in-match-range pos 2) 'year)
17387 ((org-pos-in-match-range pos 3) 'month)
17388 ((org-pos-in-match-range pos 7) 'hour)
17389 ((org-pos-in-match-range pos 8) 'minute)
17390 ((or (org-pos-in-match-range pos 4)
17391 (org-pos-in-match-range pos 5)) 'day)
17392 ((and (> pos (or (match-end 8) (match-end 5)))
17393 (< pos (match-end 0)))
17394 (- pos (or (match-end 8) (match-end 5))))
17395 (t 'day))))
17396 ans))
17398 (defun org-toggle-timestamp-type ()
17399 "Toggle the type (<active> or [inactive]) of a time stamp."
17400 (interactive)
17401 (when (org-at-timestamp-p t)
17402 (let ((beg (match-beginning 0)) (end (match-end 0))
17403 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17404 (save-excursion
17405 (goto-char beg)
17406 (while (re-search-forward "[][<>]" end t)
17407 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17408 t t)))
17409 (message "Timestamp is now %sactive"
17410 (if (equal (char-after beg) ?<) "" "in")))))
17412 (defun org-at-clock-log-p nil
17413 "Is the cursor on the clock log line?"
17414 (save-excursion
17415 (move-beginning-of-line 1)
17416 (looking-at "^[ \t]*CLOCK:")))
17418 (defvar org-clock-history) ; defined in org-clock.el
17419 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17420 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17421 "Change the date in the time stamp at point.
17422 The date will be changed by N times WHAT. WHAT can be `day', `month',
17423 `year', `minute', `second'. If WHAT is not given, the cursor position
17424 in the timestamp determines what will be changed.
17425 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17426 (let ((origin (point)) origin-cat
17427 with-hm inactive
17428 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17429 org-ts-what
17430 extra rem
17431 ts time time0 fixnext clrgx)
17432 (if (not (org-at-timestamp-p t))
17433 (user-error "Not at a timestamp"))
17434 (if (and (not what) (eq org-ts-what 'bracket))
17435 (org-toggle-timestamp-type)
17436 ;; Point isn't on brackets. Remember the part of the time-stamp
17437 ;; the point was in. Indeed, size of time-stamps may change,
17438 ;; but point must be kept in the same category nonetheless.
17439 (setq origin-cat org-ts-what)
17440 (if (and (not what) (not (eq org-ts-what 'day))
17441 org-display-custom-times
17442 (get-text-property (point) 'display)
17443 (not (get-text-property (1- (point)) 'display)))
17444 (setq org-ts-what 'day))
17445 (setq org-ts-what (or what org-ts-what)
17446 inactive (= (char-after (match-beginning 0)) ?\[)
17447 ts (match-string 0))
17448 (replace-match "")
17449 (when (string-match
17450 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17452 (setq extra (match-string 1 ts))
17453 (if suppress-tmp-delay
17454 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17455 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17456 (setq with-hm t))
17457 (setq time0 (org-parse-time-string ts))
17458 (when (and updown
17459 (eq org-ts-what 'minute)
17460 (not current-prefix-arg))
17461 ;; This looks like s-up and s-down. Change by one rounding step.
17462 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17463 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17464 (setcar (cdr time0) (+ (nth 1 time0)
17465 (if (> n 0) (- rem) (- dm rem))))))
17466 (setq time
17467 (encode-time (or (car time0) 0)
17468 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17469 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17470 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17471 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17472 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17473 (nthcdr 6 time0)))
17474 (when (and (member org-ts-what '(hour minute))
17475 extra
17476 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17477 (setq extra (org-modify-ts-extra
17478 extra
17479 (if (eq org-ts-what 'hour) 2 5)
17480 n dm)))
17481 (when (integerp org-ts-what)
17482 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17483 (if (eq what 'calendar)
17484 (let ((cal-date (org-get-date-from-calendar)))
17485 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17486 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17487 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17488 (setcar time0 (or (car time0) 0))
17489 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17490 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17491 (setq time (apply 'encode-time time0))))
17492 ;; Insert the new time-stamp, and ensure point stays in the same
17493 ;; category as before (i.e. not after the last position in that
17494 ;; category).
17495 (let ((pos (point)))
17496 ;; Stay before inserted string. `save-excursion' is of no use.
17497 (setq org-last-changed-timestamp
17498 (org-insert-time-stamp time with-hm inactive nil nil extra))
17499 (goto-char pos))
17500 (save-match-data
17501 (looking-at org-ts-regexp3)
17502 (goto-char (cond
17503 ;; `day' category ends before `hour' if any, or at
17504 ;; the end of the day name.
17505 ((eq origin-cat 'day)
17506 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17507 ((eq origin-cat 'hour) (min (match-end 7) origin))
17508 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17509 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17510 ;; `year' and `month' have both fixed size: point
17511 ;; couldn't have moved into another part.
17512 (t origin))))
17513 ;; Update clock if on a CLOCK line.
17514 (org-clock-update-time-maybe)
17515 ;; Maybe adjust the closest clock in `org-clock-history'
17516 (when org-clock-adjust-closest
17517 (if (not (and (org-at-clock-log-p)
17518 (< 1 (length (delq nil (mapcar 'marker-position
17519 org-clock-history))))))
17520 (message "No clock to adjust")
17521 (cond ((save-excursion ; fix previous clock?
17522 (re-search-backward org-ts-regexp0 nil t)
17523 (org-looking-back (concat org-clock-string " \\[")))
17524 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17525 ((save-excursion ; fix next clock?
17526 (re-search-backward org-ts-regexp0 nil t)
17527 (looking-at (concat org-ts-regexp0 "\\] =>")))
17528 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17529 (save-window-excursion
17530 ;; Find closest clock to point, adjust the previous/next one in history
17531 (let* ((p (save-excursion (org-back-to-heading t)))
17532 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17533 (clfixnth
17534 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17535 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17536 (if (not clfixpos)
17537 (message "No clock to adjust")
17538 (save-excursion
17539 (org-goto-marker-or-bmk clfixpos)
17540 (org-show-subtree)
17541 (when (re-search-forward clrgx nil t)
17542 (goto-char (match-beginning 1))
17543 (let (org-clock-adjust-closest)
17544 (org-timestamp-change n org-ts-what updown))
17545 (message "Clock adjusted in %s for heading: %s"
17546 (file-name-nondirectory (buffer-file-name))
17547 (org-get-heading t t)))))))))
17548 ;; Try to recenter the calendar window, if any.
17549 (if (and org-calendar-follow-timestamp-change
17550 (get-buffer-window "*Calendar*" t)
17551 (memq org-ts-what '(day month year)))
17552 (org-recenter-calendar (time-to-days time))))))
17554 (defun org-modify-ts-extra (s pos n dm)
17555 "Change the different parts of the lead-time and repeat fields in timestamp."
17556 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17557 ng h m new rem)
17558 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17559 (cond
17560 ((or (org-pos-in-match-range pos 2)
17561 (org-pos-in-match-range pos 3))
17562 (setq m (string-to-number (match-string 3 s))
17563 h (string-to-number (match-string 2 s)))
17564 (if (org-pos-in-match-range pos 2)
17565 (setq h (+ h n))
17566 (setq n (* dm (org-no-warnings (signum n))))
17567 (when (not (= 0 (setq rem (% m dm))))
17568 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17569 (setq m (+ m n)))
17570 (if (< m 0) (setq m (+ m 60) h (1- h)))
17571 (if (> m 59) (setq m (- m 60) h (1+ h)))
17572 (setq h (min 24 (max 0 h)))
17573 (setq ng 1 new (format "-%02d:%02d" h m)))
17574 ((org-pos-in-match-range pos 6)
17575 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17576 ((org-pos-in-match-range pos 5)
17577 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17579 ((org-pos-in-match-range pos 9)
17580 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17581 ((org-pos-in-match-range pos 8)
17582 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17584 (when ng
17585 (setq s (concat
17586 (substring s 0 (match-beginning ng))
17588 (substring s (match-end ng))))))
17591 (defun org-recenter-calendar (date)
17592 "If the calendar is visible, recenter it to DATE."
17593 (let ((cwin (get-buffer-window "*Calendar*" t)))
17594 (when cwin
17595 (let ((calendar-move-hook nil))
17596 (with-selected-window cwin
17597 (calendar-goto-date (if (listp date) date
17598 (calendar-gregorian-from-absolute date))))))))
17600 (defun org-goto-calendar (&optional arg)
17601 "Go to the Emacs calendar at the current date.
17602 If there is a time stamp in the current line, go to that date.
17603 A prefix ARG can be used to force the current date."
17604 (interactive "P")
17605 (let ((tsr org-ts-regexp) diff
17606 (calendar-move-hook nil)
17607 (calendar-view-holidays-initially-flag nil)
17608 (calendar-view-diary-initially-flag nil))
17609 (if (or (org-at-timestamp-p)
17610 (save-excursion
17611 (beginning-of-line 1)
17612 (looking-at (concat ".*" tsr))))
17613 (let ((d1 (time-to-days (current-time)))
17614 (d2 (time-to-days
17615 (org-time-string-to-time (match-string 1)))))
17616 (setq diff (- d2 d1))))
17617 (calendar)
17618 (calendar-goto-today)
17619 (if (and diff (not arg)) (calendar-forward-day diff))))
17621 (defun org-get-date-from-calendar ()
17622 "Return a list (month day year) of date at point in calendar."
17623 (with-current-buffer "*Calendar*"
17624 (save-match-data
17625 (calendar-cursor-to-date))))
17627 (defun org-date-from-calendar ()
17628 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17629 If there is already a time stamp at the cursor position, update it."
17630 (interactive)
17631 (if (org-at-timestamp-p t)
17632 (org-timestamp-change 0 'calendar)
17633 (let ((cal-date (org-get-date-from-calendar)))
17634 (org-insert-time-stamp
17635 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17637 (defcustom org-effort-durations
17638 `(("h" . 60)
17639 ("d" . ,(* 60 8))
17640 ("w" . ,(* 60 8 5))
17641 ("m" . ,(* 60 8 5 4))
17642 ("y" . ,(* 60 8 5 40)))
17643 "Conversion factor to minutes for an effort modifier.
17645 Each entry has the form (MODIFIER . MINUTES).
17647 In an effort string, a number followed by MODIFIER is multiplied
17648 by the specified number of MINUTES to obtain an effort in
17649 minutes.
17651 For example, if the value of this variable is ((\"hours\" . 60)), then an
17652 effort string \"2hours\" is equivalent to 120 minutes."
17653 :group 'org-agenda
17654 :version "24.1"
17655 :type '(alist :key-type (string :tag "Modifier")
17656 :value-type (number :tag "Minutes")))
17658 (defun org-minutes-to-clocksum-string (m)
17659 "Format number of minutes as a clocksum string.
17660 The format is determined by `org-time-clocksum-format',
17661 `org-time-clocksum-use-fractional' and
17662 `org-time-clocksum-fractional-format' and
17663 `org-time-clocksum-use-effort-durations'."
17664 (let ((clocksum "")
17665 (m (round m)) ; Don't allow fractions of minutes
17666 h d w mo y fmt n)
17667 (setq h (if org-time-clocksum-use-effort-durations
17668 (cdr (assoc "h" org-effort-durations)) 60)
17669 d (if org-time-clocksum-use-effort-durations
17670 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17671 w (if org-time-clocksum-use-effort-durations
17672 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17673 mo (if org-time-clocksum-use-effort-durations
17674 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17675 y (if org-time-clocksum-use-effort-durations
17676 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17677 ;; fractional format
17678 (if org-time-clocksum-use-fractional
17679 (cond
17680 ;; single format string
17681 ((stringp org-time-clocksum-fractional-format)
17682 (format org-time-clocksum-fractional-format (/ m (float h))))
17683 ;; choice of fractional formats for different time units
17684 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17685 (> (/ (truncate m) (* y d h)) 0))
17686 (format fmt (/ m (* y d (float h)))))
17687 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17688 (> (/ (truncate m) (* mo d h)) 0))
17689 (format fmt (/ m (* mo d (float h)))))
17690 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17691 (> (/ (truncate m) (* w d h)) 0))
17692 (format fmt (/ m (* w d (float h)))))
17693 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17694 (> (/ (truncate m) (* d h)) 0))
17695 (format fmt (/ m (* d (float h)))))
17696 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17697 (> (/ (truncate m) h) 0))
17698 (format fmt (/ m (float h))))
17699 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17700 (format fmt m))
17701 ;; fall back to smallest time unit with a format
17702 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17703 (format fmt (/ m (float h))))
17704 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17705 (format fmt (/ m (* d (float h)))))
17706 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17707 (format fmt (/ m (* w d (float h)))))
17708 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17709 (format fmt (/ m (* mo d (float h)))))
17710 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17711 (format fmt (/ m (* y d (float h))))))
17712 ;; standard (non-fractional) format, with single format string
17713 (if (stringp org-time-clocksum-format)
17714 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17715 ;; separate formats components
17716 (and (setq fmt (plist-get org-time-clocksum-format :years))
17717 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17718 (plist-get org-time-clocksum-format :require-years))
17719 (setq clocksum (concat clocksum (format fmt n))
17720 m (- m (* n y d h))))
17721 (and (setq fmt (plist-get org-time-clocksum-format :months))
17722 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17723 (plist-get org-time-clocksum-format :require-months))
17724 (setq clocksum (concat clocksum (format fmt n))
17725 m (- m (* n mo d h))))
17726 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17727 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17728 (plist-get org-time-clocksum-format :require-weeks))
17729 (setq clocksum (concat clocksum (format fmt n))
17730 m (- m (* n w d h))))
17731 (and (setq fmt (plist-get org-time-clocksum-format :days))
17732 (or (> (setq n (/ (truncate m) (* d h))) 0)
17733 (plist-get org-time-clocksum-format :require-days))
17734 (setq clocksum (concat clocksum (format fmt n))
17735 m (- m (* n d h))))
17736 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17737 (or (> (setq n (/ (truncate m) h)) 0)
17738 (plist-get org-time-clocksum-format :require-hours))
17739 (setq clocksum (concat clocksum (format fmt n))
17740 m (- m (* n h))))
17741 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17742 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17743 (setq clocksum (concat clocksum (format fmt m))))
17744 ;; return formatted time duration
17745 clocksum))))
17747 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17748 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17749 "Org mode version 8.0")
17751 (defun org-hours-to-clocksum-string (n)
17752 (org-minutes-to-clocksum-string (* n 60)))
17754 (defun org-hh:mm-string-to-minutes (s)
17755 "Convert a string H:MM to a number of minutes.
17756 If the string is just a number, interpret it as minutes.
17757 In fact, the first hh:mm or number in the string will be taken,
17758 there can be extra stuff in the string.
17759 If no number is found, the return value is 0."
17760 (cond
17761 ((integerp s) s)
17762 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17763 (+ (* (string-to-number (match-string 1 s)) 60)
17764 (string-to-number (match-string 2 s))))
17765 ((string-match "\\([0-9]+\\)" s)
17766 (string-to-number (match-string 1 s)))
17767 (t 0)))
17769 (defcustom org-image-actual-width t
17770 "Should we use the actual width of images when inlining them?
17772 When set to `t', always use the image width.
17774 When set to a number, use imagemagick (when available) to set
17775 the image's width to this value.
17777 When set to a number in a list, try to get the width from any
17778 #+ATTR.* keyword if it matches a width specification like
17780 #+ATTR_HTML: :width 300px
17782 and fall back on that number if none is found.
17784 When set to nil, try to get the width from an #+ATTR.* keyword
17785 and fall back on the original width if none is found.
17787 This requires Emacs >= 24.1, build with imagemagick support."
17788 :group 'org-appearance
17789 :version "24.4"
17790 :package-version '(Org . "8.0")
17791 :type '(choice
17792 (const :tag "Use the image width" t)
17793 (integer :tag "Use a number of pixels")
17794 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17795 (const :tag "Use #+ATTR* or don't resize" nil)))
17797 (defcustom org-agenda-inhibit-startup nil
17798 "Inhibit startup when preparing agenda buffers.
17799 When this variable is `t' (the default), the initialization of
17800 the Org agenda buffers is inhibited: e.g. the visibility state
17801 is not set, the tables are not re-aligned, etc."
17802 :type 'boolean
17803 :version "24.3"
17804 :group 'org-agenda)
17806 (defcustom org-agenda-ignore-drawer-properties nil
17807 "Avoid updating text properties when building the agenda.
17808 Properties are used to prepare buffers for effort estimates, appointments,
17809 and subtree-local categories.
17810 If you don't use these in the agenda, you can add them to this list and
17811 agenda building will be a bit faster.
17812 The value is a list, with zero or more of the symbols `effort', `appt',
17813 or `category'."
17814 :type '(set :greedy t
17815 (const effort)
17816 (const appt)
17817 (const category))
17818 :version "24.3"
17819 :group 'org-agenda)
17821 (defun org-duration-string-to-minutes (s &optional output-to-string)
17822 "Convert a duration string S to minutes.
17824 A bare number is interpreted as minutes, modifiers can be set by
17825 customizing `org-effort-durations' (which see).
17827 Entries containing a colon are interpreted as H:MM by
17828 `org-hh:mm-string-to-minutes'."
17829 (let ((result 0)
17830 (re (concat "\\([0-9.]+\\) *\\("
17831 (regexp-opt (mapcar 'car org-effort-durations))
17832 "\\)")))
17833 (while (string-match re s)
17834 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17835 (string-to-number (match-string 1 s))))
17836 (setq s (replace-match "" nil t s)))
17837 (setq result (floor result))
17838 (incf result (org-hh:mm-string-to-minutes s))
17839 (if output-to-string (number-to-string result) result)))
17841 ;;;; Files
17843 (defun org-save-all-org-buffers ()
17844 "Save all Org-mode buffers without user confirmation."
17845 (interactive)
17846 (message "Saving all Org-mode buffers...")
17847 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17848 (when (featurep 'org-id) (org-id-locations-save))
17849 (message "Saving all Org-mode buffers... done"))
17851 (defun org-revert-all-org-buffers ()
17852 "Revert all Org-mode buffers.
17853 Prompt for confirmation when there are unsaved changes.
17854 Be sure you know what you are doing before letting this function
17855 overwrite your changes.
17857 This function is useful in a setup where one tracks org files
17858 with a version control system, to revert on one machine after pulling
17859 changes from another. I believe the procedure must be like this:
17861 1. M-x org-save-all-org-buffers
17862 2. Pull changes from the other machine, resolve conflicts
17863 3. M-x org-revert-all-org-buffers"
17864 (interactive)
17865 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17866 (user-error "Abort"))
17867 (save-excursion
17868 (save-window-excursion
17869 (mapc
17870 (lambda (b)
17871 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17872 (with-current-buffer b buffer-file-name))
17873 (org-pop-to-buffer-same-window b)
17874 (revert-buffer t 'no-confirm)))
17875 (buffer-list))
17876 (when (and (featurep 'org-id) org-id-track-globally)
17877 (org-id-locations-load)))))
17879 ;;;; Agenda files
17881 ;;;###autoload
17882 (defun org-switchb (&optional arg)
17883 "Switch between Org buffers.
17884 With one prefix argument, restrict available buffers to files.
17885 With two prefix arguments, restrict available buffers to agenda files.
17887 Defaults to `iswitchb' for buffer name completion.
17888 Set `org-completion-use-ido' to make it use ido instead."
17889 (interactive "P")
17890 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17891 ((equal arg '(16)) (org-buffer-list 'agenda))
17892 (t (org-buffer-list))))
17893 (org-completion-use-iswitchb org-completion-use-iswitchb)
17894 (org-completion-use-ido org-completion-use-ido))
17895 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17896 (setq org-completion-use-iswitchb t))
17897 (org-pop-to-buffer-same-window
17898 (org-icompleting-read "Org buffer: "
17899 (mapcar 'list (mapcar 'buffer-name blist))
17900 nil t))))
17902 ;;; Define some older names previously used for this functionality
17903 ;;;###autoload
17904 (defalias 'org-ido-switchb 'org-switchb)
17905 ;;;###autoload
17906 (defalias 'org-iswitchb 'org-switchb)
17908 (defun org-buffer-list (&optional predicate exclude-tmp)
17909 "Return a list of Org buffers.
17910 PREDICATE can be `export', `files' or `agenda'.
17912 export restrict the list to Export buffers.
17913 files restrict the list to buffers visiting Org files.
17914 agenda restrict the list to buffers visiting agenda files.
17916 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17917 (let* ((bfn nil)
17918 (agenda-files (and (eq predicate 'agenda)
17919 (mapcar 'file-truename (org-agenda-files t))))
17920 (filter
17921 (cond
17922 ((eq predicate 'files)
17923 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17924 ((eq predicate 'export)
17925 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17926 ((eq predicate 'agenda)
17927 (lambda (b)
17928 (with-current-buffer b
17929 (and (derived-mode-p 'org-mode)
17930 (setq bfn (buffer-file-name b))
17931 (member (file-truename bfn) agenda-files)))))
17932 (t (lambda (b) (with-current-buffer b
17933 (or (derived-mode-p 'org-mode)
17934 (string-match "\*Org .*Export"
17935 (buffer-name b)))))))))
17936 (delq nil
17937 (mapcar
17938 (lambda(b)
17939 (if (and (funcall filter b)
17940 (or (not exclude-tmp)
17941 (not (string-match "tmp" (buffer-name b)))))
17943 nil))
17944 (buffer-list)))))
17946 (defun org-agenda-files (&optional unrestricted archives)
17947 "Get the list of agenda files.
17948 Optional UNRESTRICTED means return the full list even if a restriction
17949 is currently in place.
17950 When ARCHIVES is t, include all archive files that are really being
17951 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17952 `org-agenda-archives-mode' is t."
17953 (let ((files
17954 (cond
17955 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17956 ((stringp org-agenda-files) (org-read-agenda-file-list))
17957 ((listp org-agenda-files) org-agenda-files)
17958 (t (error "Invalid value of `org-agenda-files'")))))
17959 (setq files (apply 'append
17960 (mapcar (lambda (f)
17961 (if (file-directory-p f)
17962 (directory-files
17963 f t org-agenda-file-regexp)
17964 (list f)))
17965 files)))
17966 (when org-agenda-skip-unavailable-files
17967 (setq files (delq nil
17968 (mapcar (function
17969 (lambda (file)
17970 (and (file-readable-p file) file)))
17971 files))))
17972 (when (or (eq archives t)
17973 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17974 (setq files (org-add-archive-files files)))
17975 files))
17977 (defun org-agenda-file-p (&optional file)
17978 "Return non-nil, if FILE is an agenda file.
17979 If FILE is omitted, use the file associated with the current
17980 buffer."
17981 (member (or file (buffer-file-name))
17982 (org-agenda-files t)))
17984 (defun org-edit-agenda-file-list ()
17985 "Edit the list of agenda files.
17986 Depending on setup, this either uses customize to edit the variable
17987 `org-agenda-files', or it visits the file that is holding the list. In the
17988 latter case, the buffer is set up in a way that saving it automatically kills
17989 the buffer and restores the previous window configuration."
17990 (interactive)
17991 (if (stringp org-agenda-files)
17992 (let ((cw (current-window-configuration)))
17993 (find-file org-agenda-files)
17994 (org-set-local 'org-window-configuration cw)
17995 (org-add-hook 'after-save-hook
17996 (lambda ()
17997 (set-window-configuration
17998 (prog1 org-window-configuration
17999 (kill-buffer (current-buffer))))
18000 (org-install-agenda-files-menu)
18001 (message "New agenda file list installed"))
18002 nil 'local)
18003 (message "%s" (substitute-command-keys
18004 "Edit list and finish with \\[save-buffer]")))
18005 (customize-variable 'org-agenda-files)))
18007 (defun org-store-new-agenda-file-list (list)
18008 "Set new value for the agenda file list and save it correctly."
18009 (if (stringp org-agenda-files)
18010 (let ((fe (org-read-agenda-file-list t)) b u)
18011 (while (setq b (find-buffer-visiting org-agenda-files))
18012 (kill-buffer b))
18013 (with-temp-file org-agenda-files
18014 (insert
18015 (mapconcat
18016 (lambda (f) ;; Keep un-expanded entries.
18017 (if (setq u (assoc f fe))
18018 (cdr u)
18020 list "\n")
18021 "\n")))
18022 (let ((org-mode-hook nil) (org-inhibit-startup t)
18023 (org-insert-mode-line-in-empty-file nil))
18024 (setq org-agenda-files list)
18025 (customize-save-variable 'org-agenda-files org-agenda-files))))
18027 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18028 "Read the list of agenda files from a file.
18029 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18030 filenames, used by `org-store-new-agenda-file-list' to write back
18031 un-expanded file names."
18032 (when (file-directory-p org-agenda-files)
18033 (error "`org-agenda-files' cannot be a single directory"))
18034 (when (stringp org-agenda-files)
18035 (with-temp-buffer
18036 (insert-file-contents org-agenda-files)
18037 (mapcar
18038 (lambda (f)
18039 (let ((e (expand-file-name (substitute-in-file-name f)
18040 org-directory)))
18041 (if pair-with-expansion
18042 (cons e f)
18043 e)))
18044 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18046 ;;;###autoload
18047 (defun org-cycle-agenda-files ()
18048 "Cycle through the files in `org-agenda-files'.
18049 If the current buffer visits an agenda file, find the next one in the list.
18050 If the current buffer does not, find the first agenda file."
18051 (interactive)
18052 (let* ((fs (org-agenda-files t))
18053 (files (append fs (list (car fs))))
18054 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18055 file)
18056 (unless files (user-error "No agenda files"))
18057 (catch 'exit
18058 (while (setq file (pop files))
18059 (if (equal (file-truename file) tcf)
18060 (when (car files)
18061 (find-file (car files))
18062 (throw 'exit t))))
18063 (find-file (car fs)))
18064 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18066 (defun org-agenda-file-to-front (&optional to-end)
18067 "Move/add the current file to the top of the agenda file list.
18068 If the file is not present in the list, it is added to the front. If it is
18069 present, it is moved there. With optional argument TO-END, add/move to the
18070 end of the list."
18071 (interactive "P")
18072 (let ((org-agenda-skip-unavailable-files nil)
18073 (file-alist (mapcar (lambda (x)
18074 (cons (file-truename x) x))
18075 (org-agenda-files t)))
18076 (ctf (file-truename
18077 (or buffer-file-name
18078 (user-error "Please save the current buffer to a file"))))
18079 x had)
18080 (setq x (assoc ctf file-alist) had x)
18082 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18083 (if to-end
18084 (setq file-alist (append (delq x file-alist) (list x)))
18085 (setq file-alist (cons x (delq x file-alist))))
18086 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18087 (org-install-agenda-files-menu)
18088 (message "File %s to %s of agenda file list"
18089 (if had "moved" "added") (if to-end "end" "front"))))
18091 (defun org-remove-file (&optional file)
18092 "Remove current file from the list of files in variable `org-agenda-files'.
18093 These are the files which are being checked for agenda entries.
18094 Optional argument FILE means use this file instead of the current."
18095 (interactive)
18096 (let* ((org-agenda-skip-unavailable-files nil)
18097 (file (or file buffer-file-name
18098 (user-error "Current buffer does not visit a file")))
18099 (true-file (file-truename file))
18100 (afile (abbreviate-file-name file))
18101 (files (delq nil (mapcar
18102 (lambda (x)
18103 (if (equal true-file
18104 (file-truename x))
18105 nil x))
18106 (org-agenda-files t)))))
18107 (if (not (= (length files) (length (org-agenda-files t))))
18108 (progn
18109 (org-store-new-agenda-file-list files)
18110 (org-install-agenda-files-menu)
18111 (message "Removed file: %s" afile))
18112 (message "File was not in list: %s (not removed)" afile))))
18114 (defun org-file-menu-entry (file)
18115 (vector file (list 'find-file file) t))
18117 (defun org-check-agenda-file (file)
18118 "Make sure FILE exists. If not, ask user what to do."
18119 (when (not (file-exists-p file))
18120 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18121 (abbreviate-file-name file))
18122 (let ((r (downcase (read-char-exclusive))))
18123 (cond
18124 ((equal r ?r)
18125 (org-remove-file file)
18126 (throw 'nextfile t))
18127 (t (error "Abort"))))))
18129 (defun org-get-agenda-file-buffer (file)
18130 "Get a buffer visiting FILE. If the buffer needs to be created, add
18131 it to the list of buffers which might be released later."
18132 (let ((buf (org-find-base-buffer-visiting file)))
18133 (if buf
18134 buf ; just return it
18135 ;; Make a new buffer and remember it
18136 (setq buf (find-file-noselect file))
18137 (if buf (push buf org-agenda-new-buffers))
18138 buf)))
18140 (defun org-release-buffers (blist)
18141 "Release all buffers in list, asking the user for confirmation when needed.
18142 When a buffer is unmodified, it is just killed. When modified, it is saved
18143 \(if the user agrees) and then killed."
18144 (let (buf file)
18145 (while (setq buf (pop blist))
18146 (setq file (buffer-file-name buf))
18147 (when (and (buffer-modified-p buf)
18148 file
18149 (y-or-n-p (format "Save file %s? " file)))
18150 (with-current-buffer buf (save-buffer)))
18151 (kill-buffer buf))))
18153 (defun org-agenda-prepare-buffers (files)
18154 "Create buffers for all agenda files, protect archived trees and comments."
18155 (interactive)
18156 (let ((pa '(:org-archived t))
18157 (pc '(:org-comment t))
18158 (pall '(:org-archived t :org-comment t))
18159 (inhibit-read-only t)
18160 (org-inhibit-startup org-agenda-inhibit-startup)
18161 (rea (concat ":" org-archive-tag ":"))
18162 file re pos)
18163 (setq org-tag-alist-for-agenda nil
18164 org-tag-groups-alist-for-agenda nil)
18165 (save-window-excursion
18166 (save-restriction
18167 (while (setq file (pop files))
18168 (catch 'nextfile
18169 (if (bufferp file)
18170 (set-buffer file)
18171 (org-check-agenda-file file)
18172 (set-buffer (org-get-agenda-file-buffer file)))
18173 (widen)
18174 (org-set-regexps-and-options-for-tags)
18175 (setq pos (point))
18176 (goto-char (point-min))
18177 (let ((case-fold-search t))
18178 (when (search-forward "#+setupfile" nil t)
18179 ;; Don't set all regexps and options systematically as
18180 ;; this is only run for setting agenda tags from setup
18181 ;; file
18182 (org-set-regexps-and-options)))
18183 (or (memq 'category org-agenda-ignore-drawer-properties)
18184 (org-refresh-category-properties))
18185 (or (memq 'effort org-agenda-ignore-drawer-properties)
18186 (org-refresh-properties org-effort-property 'org-effort))
18187 (or (memq 'appt org-agenda-ignore-drawer-properties)
18188 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18189 (setq org-todo-keywords-for-agenda
18190 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18191 (setq org-done-keywords-for-agenda
18192 (append org-done-keywords-for-agenda org-done-keywords))
18193 (setq org-todo-keyword-alist-for-agenda
18194 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18195 (setq org-tag-alist-for-agenda
18196 (org-uniquify
18197 (append org-tag-alist-for-agenda
18198 org-tag-alist
18199 org-tag-persistent-alist)))
18200 (if org-group-tags
18201 (setq org-tag-groups-alist-for-agenda
18202 (org-uniquify-alist
18203 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18204 (org-with-silent-modifications
18205 (save-excursion
18206 (remove-text-properties (point-min) (point-max) pall)
18207 (when org-agenda-skip-archived-trees
18208 (goto-char (point-min))
18209 (while (re-search-forward rea nil t)
18210 (if (org-at-heading-p t)
18211 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18212 (goto-char (point-min))
18213 (setq re (format org-heading-keyword-regexp-format
18214 org-comment-string))
18215 (while (re-search-forward re nil t)
18216 (add-text-properties
18217 (match-beginning 0) (org-end-of-subtree t) pc))))
18218 (goto-char pos)))))
18219 (setq org-todo-keywords-for-agenda
18220 (org-uniquify org-todo-keywords-for-agenda))
18221 (setq org-todo-keyword-alist-for-agenda
18222 (org-uniquify org-todo-keyword-alist-for-agenda))))
18225 ;;;; CDLaTeX minor mode
18227 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18228 "Keymap for the minor `org-cdlatex-mode'.")
18230 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18231 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18232 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18233 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18234 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18236 (defvar org-cdlatex-texmathp-advice-is-done nil
18237 "Flag remembering if we have applied the advice to texmathp already.")
18239 (define-minor-mode org-cdlatex-mode
18240 "Toggle the minor `org-cdlatex-mode'.
18241 This mode supports entering LaTeX environment and math in LaTeX fragments
18242 in Org-mode.
18243 \\{org-cdlatex-mode-map}"
18244 nil " OCDL" nil
18245 (when org-cdlatex-mode
18246 (require 'cdlatex)
18247 (run-hooks 'cdlatex-mode-hook)
18248 (cdlatex-compute-tables))
18249 (unless org-cdlatex-texmathp-advice-is-done
18250 (setq org-cdlatex-texmathp-advice-is-done t)
18251 (defadvice texmathp (around org-math-always-on activate)
18252 "Always return t in org-mode buffers.
18253 This is because we want to insert math symbols without dollars even outside
18254 the LaTeX math segments. If Orgmode thinks that point is actually inside
18255 an embedded LaTeX fragment, let texmathp do its job.
18256 \\[org-cdlatex-mode-map]"
18257 (interactive)
18258 (let (p)
18259 (cond
18260 ((not (derived-mode-p 'org-mode)) ad-do-it)
18261 ((eq this-command 'cdlatex-math-symbol)
18262 (setq ad-return-value t
18263 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18265 (let ((p (org-inside-LaTeX-fragment-p)))
18266 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18267 (setq ad-return-value t
18268 texmathp-why '("Org-mode embedded math" . 0))
18269 (if p ad-do-it)))))))))
18271 (defun turn-on-org-cdlatex ()
18272 "Unconditionally turn on `org-cdlatex-mode'."
18273 (org-cdlatex-mode 1))
18275 (defun org-try-cdlatex-tab ()
18276 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18277 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18278 - inside a LaTeX fragment, or
18279 - after the first word in a line, where an abbreviation expansion could
18280 insert a LaTeX environment."
18281 (when org-cdlatex-mode
18282 (cond
18283 ;; Before any word on the line: No expansion possible.
18284 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18285 ;; Just after first word on the line: Expand it. Make sure it
18286 ;; cannot happen on headlines, though.
18287 ((save-excursion
18288 (skip-chars-backward "a-zA-Z0-9*")
18289 (skip-chars-backward " \t")
18290 (and (bolp) (not (org-at-heading-p))))
18291 (cdlatex-tab) t)
18292 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18294 (defun org-cdlatex-underscore-caret (&optional arg)
18295 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18296 Revert to the normal definition outside of these fragments."
18297 (interactive "P")
18298 (if (org-inside-LaTeX-fragment-p)
18299 (call-interactively 'cdlatex-sub-superscript)
18300 (let (org-cdlatex-mode)
18301 (call-interactively (key-binding (vector last-input-event))))))
18303 (defun org-cdlatex-math-modify (&optional arg)
18304 "Execute `cdlatex-math-modify' in LaTeX fragments.
18305 Revert to the normal definition outside of these fragments."
18306 (interactive "P")
18307 (if (org-inside-LaTeX-fragment-p)
18308 (call-interactively 'cdlatex-math-modify)
18309 (let (org-cdlatex-mode)
18310 (call-interactively (key-binding (vector last-input-event))))))
18314 ;;;; LaTeX fragments
18316 (defun org-inside-LaTeX-fragment-p ()
18317 "Test if point is inside a LaTeX fragment.
18318 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18319 sequence appearing also before point.
18320 Even though the matchers for math are configurable, this function assumes
18321 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18322 delimiters are skipped when they have been removed by customization.
18323 The return value is nil, or a cons cell with the delimiter and the
18324 position of this delimiter.
18326 This function does a reasonably good job, but can locally be fooled by
18327 for example currency specifications. For example it will assume being in
18328 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18329 fragments that are properly closed, but during editing, we have to live
18330 with the uncertainty caused by missing closing delimiters. This function
18331 looks only before point, not after."
18332 (catch 'exit
18333 (let ((pos (point))
18334 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18335 (lim (progn
18336 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18337 (point)))
18338 dd-on str (start 0) m re)
18339 (goto-char pos)
18340 (when dodollar
18341 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18342 re (nth 1 (assoc "$" org-latex-regexps)))
18343 (while (string-match re str start)
18344 (cond
18345 ((= (match-end 0) (length str))
18346 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18347 ((= (match-end 0) (- (length str) 5))
18348 (throw 'exit nil))
18349 (t (setq start (match-end 0))))))
18350 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18351 (goto-char pos)
18352 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18353 (and (match-beginning 2) (throw 'exit nil))
18354 ;; count $$
18355 (while (re-search-backward "\\$\\$" lim t)
18356 (setq dd-on (not dd-on)))
18357 (goto-char pos)
18358 (if dd-on (cons "$$" m))))))
18360 (defun org-inside-latex-macro-p ()
18361 "Is point inside a LaTeX macro or its arguments?"
18362 (save-match-data
18363 (org-in-regexp
18364 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18366 (defvar org-latex-fragment-image-overlays nil
18367 "List of overlays carrying the images of latex fragments.")
18368 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18370 (defun org-remove-latex-fragment-image-overlays ()
18371 "Remove all overlays with LaTeX fragment images in current buffer."
18372 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18373 (setq org-latex-fragment-image-overlays nil))
18375 (defun org-preview-latex-fragment (&optional subtree)
18376 "Preview the LaTeX fragment at point, or all locally or globally.
18377 If the cursor is in a LaTeX fragment, create the image and overlay
18378 it over the source code. If there is no fragment at point, display
18379 all fragments in the current text, from one headline to the next. With
18380 prefix SUBTREE, display all fragments in the current subtree. With a
18381 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18382 the cursor is before the first headline,
18383 display all fragments in the buffer.
18384 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18385 (interactive "P")
18386 (unless buffer-file-name
18387 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18388 (when (display-graphic-p)
18389 (org-remove-latex-fragment-image-overlays)
18390 (save-excursion
18391 (save-restriction
18392 (let (beg end at msg)
18393 (cond
18394 ((or (equal subtree '(16))
18395 (not (save-excursion
18396 (re-search-backward org-outline-regexp-bol nil t))))
18397 (setq beg (point-min) end (point-max)
18398 msg "Creating images for buffer...%s"))
18399 ((equal subtree '(4))
18400 (org-back-to-heading)
18401 (setq beg (point) end (org-end-of-subtree t)
18402 msg "Creating images for subtree...%s"))
18404 (if (setq at (org-inside-LaTeX-fragment-p))
18405 (goto-char (max (point-min) (- (cdr at) 2)))
18406 (org-back-to-heading))
18407 (setq beg (point) end (progn (outline-next-heading) (point))
18408 msg (if at "Creating image...%s"
18409 "Creating images for entry...%s"))))
18410 (message msg "")
18411 (narrow-to-region beg end)
18412 (goto-char beg)
18413 (org-format-latex
18414 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18415 (file-name-nondirectory
18416 buffer-file-name)))
18417 default-directory 'overlays msg at 'forbuffer
18418 org-latex-create-formula-image-program)
18419 (message msg "done. Use `C-c C-c' to remove images."))))))
18421 (defun org-format-latex (prefix &optional dir overlays msg at
18422 forbuffer processing-type)
18423 "Replace LaTeX fragments with links to an image, and produce images.
18424 Some of the options can be changed using the variable
18425 `org-format-latex-options'."
18426 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18427 (let* ((prefixnodir (file-name-nondirectory prefix))
18428 (absprefix (expand-file-name prefix dir))
18429 (todir (file-name-directory absprefix))
18430 (opt org-format-latex-options)
18431 (optnew org-format-latex-options)
18432 (matchers (plist-get opt :matchers))
18433 (re-list org-latex-regexps)
18434 (cnt 0) txt hash link beg end re e checkdir
18435 string
18436 m n block-type block linkfile movefile ov)
18437 ;; Check the different regular expressions
18438 (while (setq e (pop re-list))
18439 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18440 block (if block-type "\n\n" ""))
18441 (when (member m matchers)
18442 (goto-char (point-min))
18443 (while (re-search-forward re nil t)
18444 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18445 (or (not overlays)
18446 (not (eq (get-char-property (match-beginning n)
18447 'org-overlay-type)
18448 'org-latex-overlay))))
18449 (cond
18450 ((eq processing-type 'verbatim))
18451 ((eq processing-type 'mathjax)
18452 ;; Prepare for MathJax processing.
18453 (setq string (match-string n))
18454 (when (member m '("$" "$1"))
18455 (save-excursion
18456 (delete-region (match-beginning n) (match-end n))
18457 (goto-char (match-beginning n))
18458 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18459 ((or (eq processing-type 'dvipng)
18460 (eq processing-type 'imagemagick))
18461 ;; Process to an image.
18462 (setq txt (match-string n)
18463 beg (match-beginning n) end (match-end n)
18464 cnt (1+ cnt))
18465 (let ((face (face-at-point))
18466 (fg (plist-get opt :foreground))
18467 (bg (plist-get opt :background))
18468 ;; Ensure full list is printed.
18469 print-length print-level)
18470 (when forbuffer
18471 ;; Get the colors from the face at point.
18472 (goto-char beg)
18473 (when (eq fg 'auto)
18474 (setq fg (face-attribute face :foreground nil 'default)))
18475 (when (eq bg 'auto)
18476 (setq bg (face-attribute face :background nil 'default)))
18477 (setq optnew (copy-sequence opt))
18478 (plist-put optnew :foreground fg)
18479 (plist-put optnew :background bg))
18480 (setq hash (sha1 (prin1-to-string
18481 (list org-format-latex-header
18482 org-latex-default-packages-alist
18483 org-latex-packages-alist
18484 org-format-latex-options
18485 forbuffer txt fg bg)))
18486 linkfile (format "%s_%s.png" prefix hash)
18487 movefile (format "%s_%s.png" absprefix hash)))
18488 (setq link (concat block "[[file:" linkfile "]]" block))
18489 (if msg (message msg cnt))
18490 (goto-char beg)
18491 (unless checkdir ; Ensure the directory exists.
18492 (setq checkdir t)
18493 (or (file-directory-p todir) (make-directory todir t)))
18494 (unless (file-exists-p movefile)
18495 (org-create-formula-image
18496 txt movefile optnew forbuffer processing-type))
18497 (if overlays
18498 (progn
18499 (mapc (lambda (o)
18500 (if (eq (overlay-get o 'org-overlay-type)
18501 'org-latex-overlay)
18502 (delete-overlay o)))
18503 (overlays-in beg end))
18504 (setq ov (make-overlay beg end))
18505 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18506 (if (featurep 'xemacs)
18507 (progn
18508 (overlay-put ov 'invisible t)
18509 (overlay-put
18510 ov 'end-glyph
18511 (make-glyph (vector 'png :file movefile))))
18512 (overlay-put
18513 ov 'display
18514 (list 'image :type 'png :file movefile :ascent 'center)))
18515 (push ov org-latex-fragment-image-overlays)
18516 (goto-char end))
18517 (delete-region beg end)
18518 (insert (org-add-props link
18519 (list 'org-latex-src
18520 (replace-regexp-in-string
18521 "\"" "" txt)
18522 'org-latex-src-embed-type
18523 (if block-type 'paragraph 'character))))))
18524 ((eq processing-type 'mathml)
18525 ;; Process to MathML
18526 (unless (save-match-data (org-format-latex-mathml-available-p))
18527 (user-error "LaTeX to MathML converter not configured"))
18528 (setq txt (match-string n)
18529 beg (match-beginning n) end (match-end n)
18530 cnt (1+ cnt))
18531 (if msg (message msg cnt))
18532 (goto-char beg)
18533 (delete-region beg end)
18534 (insert (org-format-latex-as-mathml
18535 txt block-type prefix dir)))
18537 (error "Unknown conversion type %s for LaTeX fragments"
18538 processing-type)))))))))
18540 (defun org-create-math-formula (latex-frag &optional mathml-file)
18541 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18542 Use `org-latex-to-mathml-convert-command'. If the conversion is
18543 sucessful, return the portion between \"<math...> </math>\"
18544 elements otherwise return nil. When MATHML-FILE is specified,
18545 write the results in to that file. When invoked as an
18546 interactive command, prompt for LATEX-FRAG, with initial value
18547 set to the current active region and echo the results for user
18548 inspection."
18549 (interactive (list (let ((frag (when (org-region-active-p)
18550 (buffer-substring-no-properties
18551 (region-beginning) (region-end)))))
18552 (read-string "LaTeX Fragment: " frag nil frag))))
18553 (unless latex-frag (error "Invalid LaTeX fragment"))
18554 (let* ((tmp-in-file (file-relative-name
18555 (make-temp-name (expand-file-name "ltxmathml-in"))))
18556 (ignore (write-region latex-frag nil tmp-in-file))
18557 (tmp-out-file (file-relative-name
18558 (make-temp-name (expand-file-name "ltxmathml-out"))))
18559 (cmd (format-spec
18560 org-latex-to-mathml-convert-command
18561 `((?j . ,(shell-quote-argument
18562 (expand-file-name org-latex-to-mathml-jar-file)))
18563 (?I . ,(shell-quote-argument tmp-in-file))
18564 (?o . ,(shell-quote-argument tmp-out-file)))))
18565 mathml shell-command-output)
18566 (when (org-called-interactively-p 'any)
18567 (unless (org-format-latex-mathml-available-p)
18568 (user-error "LaTeX to MathML converter not configured")))
18569 (message "Running %s" cmd)
18570 (setq shell-command-output (shell-command-to-string cmd))
18571 (setq mathml
18572 (when (file-readable-p tmp-out-file)
18573 (with-current-buffer (find-file-noselect tmp-out-file t)
18574 (goto-char (point-min))
18575 (when (re-search-forward
18576 (concat
18577 (regexp-quote
18578 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18579 "\\(.\\|\n\\)*"
18580 (regexp-quote "</math>")) nil t)
18581 (prog1 (match-string 0) (kill-buffer))))))
18582 (cond
18583 (mathml
18584 (setq mathml
18585 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18586 (when mathml-file
18587 (write-region mathml nil mathml-file))
18588 (when (org-called-interactively-p 'any)
18589 (message mathml)))
18590 ((message "LaTeX to MathML conversion failed")
18591 (message shell-command-output)))
18592 (delete-file tmp-in-file)
18593 (when (file-exists-p tmp-out-file)
18594 (delete-file tmp-out-file))
18595 mathml))
18597 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18598 prefix &optional dir)
18599 "Use `org-create-math-formula' but check local cache first."
18600 (let* ((absprefix (expand-file-name prefix dir))
18601 (print-length nil) (print-level nil)
18602 (formula-id (concat
18603 "formula-"
18604 (sha1
18605 (prin1-to-string
18606 (list latex-frag
18607 org-latex-to-mathml-convert-command)))))
18608 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18609 (formula-cache-dir (file-name-directory formula-cache)))
18611 (unless (file-directory-p formula-cache-dir)
18612 (make-directory formula-cache-dir t))
18614 (unless (file-exists-p formula-cache)
18615 (org-create-math-formula latex-frag formula-cache))
18617 (if (file-exists-p formula-cache)
18618 ;; Successful conversion. Return the link to MathML file.
18619 (org-add-props
18620 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18621 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18622 'org-latex-src-embed-type (if latex-frag-type
18623 'paragraph 'character)))
18624 ;; Failed conversion. Return the LaTeX fragment verbatim
18625 latex-frag)))
18627 (defun org-create-formula-image (string tofile options buffer &optional type)
18628 "Create an image from LaTeX source using dvipng or convert.
18629 This function calls either `org-create-formula-image-with-dvipng'
18630 or `org-create-formula-image-with-imagemagick' depending on the
18631 value of `org-latex-create-formula-image-program' or on the value
18632 of the optional TYPE variable.
18634 Note: ultimately these two function should be combined as they
18635 share a good deal of logic."
18636 (org-check-external-command
18637 "latex" "needed to convert LaTeX fragments to images")
18638 (funcall
18639 (case (or type org-latex-create-formula-image-program)
18640 ('dvipng
18641 (org-check-external-command
18642 "dvipng" "needed to convert LaTeX fragments to images")
18643 #'org-create-formula-image-with-dvipng)
18644 ('imagemagick
18645 (org-check-external-command
18646 "convert" "you need to install imagemagick")
18647 #'org-create-formula-image-with-imagemagick)
18648 (t (error
18649 "Invalid value of `org-latex-create-formula-image-program'")))
18650 string tofile options buffer))
18652 (declare-function org-export-get-backend "ox" (name))
18653 (declare-function org-export--get-global-options "ox" (&optional backend))
18654 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18655 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18656 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18657 (defun org-create-formula--latex-header ()
18658 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18659 (let ((info (org-combine-plists (org-export--get-global-options
18660 (org-export-get-backend 'latex))
18661 (org-export--get-inbuffer-options
18662 (org-export-get-backend 'latex)))))
18663 (org-latex-guess-babel-language
18664 (org-latex-guess-inputenc
18665 (org-splice-latex-header
18666 org-format-latex-header
18667 org-latex-default-packages-alist
18668 org-latex-packages-alist t
18669 (plist-get info :latex-header)))
18670 info)))
18672 ;; This function borrows from Ganesh Swami's latex2png.el
18673 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18674 "This calls dvipng."
18675 (require 'ox-latex)
18676 (let* ((tmpdir (if (featurep 'xemacs)
18677 (temp-directory)
18678 temporary-file-directory))
18679 (texfilebase (make-temp-name
18680 (expand-file-name "orgtex" tmpdir)))
18681 (texfile (concat texfilebase ".tex"))
18682 (dvifile (concat texfilebase ".dvi"))
18683 (pngfile (concat texfilebase ".png"))
18684 (fnh (if (featurep 'xemacs)
18685 (font-height (face-font 'default))
18686 (face-attribute 'default :height nil)))
18687 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18688 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18689 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18690 "Black"))
18691 (bg (or (plist-get options (if buffer :background :html-background))
18692 "Transparent")))
18693 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18694 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18695 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18696 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18697 (let ((latex-header (org-create-formula--latex-header)))
18698 (with-temp-file texfile
18699 (insert latex-header)
18700 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18701 (let ((dir default-directory))
18702 (condition-case nil
18703 (progn
18704 (cd tmpdir)
18705 (call-process "latex" nil nil nil texfile))
18706 (error nil))
18707 (cd dir))
18708 (if (not (file-exists-p dvifile))
18709 (progn (message "Failed to create dvi file from %s" texfile) nil)
18710 (condition-case nil
18711 (if (featurep 'xemacs)
18712 (call-process "dvipng" nil nil nil
18713 "-fg" fg "-bg" bg
18714 "-T" "tight"
18715 "-o" pngfile
18716 dvifile)
18717 (call-process "dvipng" nil nil nil
18718 "-fg" fg "-bg" bg
18719 "-D" dpi
18720 ;;"-x" scale "-y" scale
18721 "-T" "tight"
18722 "-o" pngfile
18723 dvifile))
18724 (error nil))
18725 (if (not (file-exists-p pngfile))
18726 (if org-format-latex-signal-error
18727 (error "Failed to create png file from %s" texfile)
18728 (message "Failed to create png file from %s" texfile)
18729 nil)
18730 ;; Use the requested file name and clean up
18731 (copy-file pngfile tofile 'replace)
18732 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18733 (if (file-exists-p (concat texfilebase e))
18734 (delete-file (concat texfilebase e))))
18735 pngfile))))
18737 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18738 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18739 "This calls convert, which is included into imagemagick."
18740 (require 'ox-latex)
18741 (let* ((tmpdir (if (featurep 'xemacs)
18742 (temp-directory)
18743 temporary-file-directory))
18744 (texfilebase (make-temp-name
18745 (expand-file-name "orgtex" tmpdir)))
18746 (texfile (concat texfilebase ".tex"))
18747 (pdffile (concat texfilebase ".pdf"))
18748 (pngfile (concat texfilebase ".png"))
18749 (fnh (if (featurep 'xemacs)
18750 (font-height (face-font 'default))
18751 (face-attribute 'default :height nil)))
18752 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18753 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18754 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18755 "black"))
18756 (bg (or (plist-get options (if buffer :background :html-background))
18757 "white")))
18758 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18759 (setq fg (org-latex-color-format fg)))
18760 (if (eq bg 'default) (setq bg (org-latex-color :background))
18761 (setq bg (org-latex-color-format
18762 (if (string= bg "Transparent") "white" bg))))
18763 (let ((latex-header (org-create-formula--latex-header)))
18764 (with-temp-file texfile
18765 (insert latex-header)
18766 (insert "\n\\begin{document}\n"
18767 "\\definecolor{fg}{rgb}{" fg "}\n"
18768 "\\definecolor{bg}{rgb}{" bg "}\n"
18769 "\n\\pagecolor{bg}\n"
18770 "\n{\\color{fg}\n"
18771 string
18772 "\n}\n"
18773 "\n\\end{document}\n")))
18774 (org-latex-compile texfile t)
18775 (if (not (file-exists-p pdffile))
18776 (progn (message "Failed to create pdf file from %s" texfile) nil)
18777 (condition-case nil
18778 (if (featurep 'xemacs)
18779 (call-process "convert" nil nil nil
18780 "-density" "96"
18781 "-trim"
18782 "-antialias"
18783 pdffile
18784 "-quality" "100"
18785 ;; "-sharpen" "0x1.0"
18786 pngfile)
18787 (call-process "convert" nil nil nil
18788 "-density" dpi
18789 "-trim"
18790 "-antialias"
18791 pdffile
18792 "-quality" "100"
18793 ;; "-sharpen" "0x1.0"
18794 pngfile))
18795 (error nil))
18796 (if (not (file-exists-p pngfile))
18797 (if org-format-latex-signal-error
18798 (error "Failed to create png file from %s" texfile)
18799 (message "Failed to create png file from %s" texfile)
18800 nil)
18801 ;; Use the requested file name and clean up
18802 (copy-file pngfile tofile 'replace)
18803 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18804 (if (file-exists-p (concat texfilebase e))
18805 (delete-file (concat texfilebase e))))
18806 pngfile))))
18808 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18809 "Fill a LaTeX header template TPL.
18810 In the template, the following place holders will be recognized:
18812 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18813 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18814 [PACKAGES] \\usepackage statements for PKG
18815 [NO-PACKAGES] do not include PKG
18816 [EXTRA] the string EXTRA
18817 [NO-EXTRA] do not include EXTRA
18819 For backward compatibility, if both the positive and the negative place
18820 holder is missing, the positive one (without the \"NO-\") will be
18821 assumed to be present at the end of the template.
18822 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18823 EXTRA is a string.
18824 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18825 (let (rpl (end ""))
18826 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18827 (setq rpl (if (or (match-end 1) (not def-pkg))
18828 "" (org-latex-packages-to-string def-pkg snippets-p t))
18829 tpl (replace-match rpl t t tpl))
18830 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18832 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18833 (setq rpl (if (or (match-end 1) (not pkg))
18834 "" (org-latex-packages-to-string pkg snippets-p t))
18835 tpl (replace-match rpl t t tpl))
18836 (if pkg (setq end
18837 (concat end "\n"
18838 (org-latex-packages-to-string pkg snippets-p)))))
18840 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18841 (setq rpl (if (or (match-end 1) (not extra))
18842 "" (concat extra "\n"))
18843 tpl (replace-match rpl t t tpl))
18844 (if (and extra (string-match "\\S-" extra))
18845 (setq end (concat end "\n" extra))))
18847 (if (string-match "\\S-" end)
18848 (concat tpl "\n" end)
18849 tpl)))
18851 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18852 "Turn an alist of packages into a string with the \\usepackage macros."
18853 (setq pkg (mapconcat (lambda(p)
18854 (cond
18855 ((stringp p) p)
18856 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18857 (format "%% Package %s omitted" (cadr p)))
18858 ((equal "" (car p))
18859 (format "\\usepackage{%s}" (cadr p)))
18861 (format "\\usepackage[%s]{%s}"
18862 (car p) (cadr p)))))
18864 "\n"))
18865 (if newline (concat pkg "\n") pkg))
18867 (defun org-dvipng-color (attr)
18868 "Return a RGB color specification for dvipng."
18869 (apply 'format "rgb %s %s %s"
18870 (mapcar 'org-normalize-color
18871 (if (featurep 'xemacs)
18872 (color-rgb-components
18873 (face-property 'default
18874 (cond ((eq attr :foreground) 'foreground)
18875 ((eq attr :background) 'background))))
18876 (color-values (face-attribute 'default attr nil))))))
18878 (defun org-dvipng-color-format (color-name)
18879 "Convert COLOR-NAME to a RGB color value for dvipng."
18880 (apply 'format "rgb %s %s %s"
18881 (mapcar 'org-normalize-color
18882 (color-values color-name))))
18884 (defun org-latex-color (attr)
18885 "Return a RGB color for the LaTeX color package."
18886 (apply 'format "%s,%s,%s"
18887 (mapcar 'org-normalize-color
18888 (if (featurep 'xemacs)
18889 (color-rgb-components
18890 (face-property 'default
18891 (cond ((eq attr :foreground) 'foreground)
18892 ((eq attr :background) 'background))))
18893 (color-values (face-attribute 'default attr nil))))))
18895 (defun org-latex-color-format (color-name)
18896 "Convert COLOR-NAME to a RGB color value."
18897 (apply 'format "%s,%s,%s"
18898 (mapcar 'org-normalize-color
18899 (color-values color-name))))
18901 (defun org-normalize-color (value)
18902 "Return string to be used as color value for an RGB component."
18903 (format "%g" (/ value 65535.0)))
18907 ;; Image display
18909 (defvar org-inline-image-overlays nil)
18910 (make-variable-buffer-local 'org-inline-image-overlays)
18912 (defun org-toggle-inline-images (&optional include-linked)
18913 "Toggle the display of inline images.
18914 INCLUDE-LINKED is passed to `org-display-inline-images'."
18915 (interactive "P")
18916 (if org-inline-image-overlays
18917 (progn
18918 (org-remove-inline-images)
18919 (message "Inline image display turned off"))
18920 (org-display-inline-images include-linked)
18921 (if (and (org-called-interactively-p)
18922 org-inline-image-overlays)
18923 (message "%d images displayed inline"
18924 (length org-inline-image-overlays))
18925 (message "No images to display inline"))))
18927 (defun org-redisplay-inline-images ()
18928 "Refresh the display of inline images."
18929 (interactive)
18930 (if (not org-inline-image-overlays)
18931 (org-toggle-inline-images)
18932 (org-toggle-inline-images)
18933 (org-toggle-inline-images)))
18935 (defun org-display-inline-images (&optional include-linked refresh beg end)
18936 "Display inline images.
18938 An inline image is a link which follows either of these
18939 conventions:
18941 1. Its path is a file with an extension matching return value
18942 from `image-file-name-regexp' and it has no contents.
18944 2. Its description consists in a single link of the previous
18945 type.
18947 When optional argument INCLUDE-LINKED is non-nil, also links with
18948 a text description part will be inlined. This can be nice for
18949 a quick look at those images, but it does not reflect what
18950 exported files will look like.
18952 When optional argument REFRESH is non-nil, refresh existing
18953 images between BEG and END. This will create new image displays
18954 only if necessary. BEG and END default to the buffer
18955 boundaries."
18956 (interactive "P")
18957 (when (display-graphic-p)
18958 (unless refresh
18959 (org-remove-inline-images)
18960 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18961 (org-with-wide-buffer
18962 (goto-char (or beg (point-min)))
18963 (let ((case-fold-search t)
18964 (file-extension-re (org-image-file-name-regexp)))
18965 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
18966 (let ((link (save-match-data (org-element-context))))
18967 ;; Check if we're at an inline image.
18968 (when (and (equal (org-element-property :type link) "file")
18969 (or include-linked
18970 (not (org-element-property :contents-begin link)))
18971 (let ((parent (org-element-property :parent link)))
18972 (or (not (eq (org-element-type parent) 'link))
18973 (not (cdr (org-element-contents parent)))))
18974 (org-string-match-p file-extension-re
18975 (org-element-property :path link)))
18976 (let ((file (expand-file-name (org-element-property :path link))))
18977 (when (file-exists-p file)
18978 (let ((width
18979 ;; Apply `org-image-actual-width' specifications.
18980 (cond
18981 ((not (image-type-available-p 'imagemagick)) nil)
18982 ((eq org-image-actual-width t) nil)
18983 ((listp org-image-actual-width)
18985 ;; First try to find a width among
18986 ;; attributes associated to the paragraph
18987 ;; containing link.
18988 (let ((paragraph
18989 (let ((e link))
18990 (while (and (setq e (org-element-property
18991 :parent e))
18992 (not (eq (org-element-type e)
18993 'paragraph))))
18994 e)))
18995 (when paragraph
18996 (save-excursion
18997 (goto-char (org-element-property :begin paragraph))
18998 (when (save-match-data
18999 (re-search-forward
19000 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19001 (org-element-property
19002 :post-affiliated paragraph)
19004 (string-to-number (match-string 1))))))
19005 ;; Otherwise, fall-back to provided number.
19006 (car org-image-actual-width)))
19007 ((numberp org-image-actual-width)
19008 org-image-actual-width)))
19009 (old (get-char-property-and-overlay
19010 (org-element-property :begin link)
19011 'org-image-overlay)))
19012 (if (and (car-safe old) refresh)
19013 (image-refresh (overlay-get (cdr old) 'display))
19014 (let ((image (save-match-data
19015 (create-image file
19016 (and width 'imagemagick)
19018 :width width))))
19019 (when image
19020 (let* ((link
19021 ;; If inline image is the description
19022 ;; of another link, be sure to
19023 ;; consider the latter as the one to
19024 ;; apply the overlay on.
19025 (let ((parent
19026 (org-element-property :parent link)))
19027 (if (eq (org-element-type parent) 'link)
19028 parent
19029 link)))
19030 (ov (make-overlay
19031 (org-element-property :begin link)
19032 (progn
19033 (goto-char
19034 (org-element-property :end link))
19035 (skip-chars-backward " \t")
19036 (point)))))
19037 (overlay-put ov 'display image)
19038 (overlay-put ov 'face 'default)
19039 (overlay-put ov 'org-image-overlay t)
19040 (overlay-put
19041 ov 'modification-hooks
19042 (list 'org-display-inline-remove-overlay))
19043 (push ov org-inline-image-overlays)))))))))))))))
19045 (define-obsolete-function-alias
19046 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19048 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19049 "Remove inline-display overlay if a corresponding region is modified."
19050 (let ((inhibit-modification-hooks t))
19051 (when (and ov after)
19052 (delete ov org-inline-image-overlays)
19053 (delete-overlay ov))))
19055 (defun org-remove-inline-images ()
19056 "Remove inline display of images."
19057 (interactive)
19058 (mapc 'delete-overlay org-inline-image-overlays)
19059 (setq org-inline-image-overlays nil))
19061 ;;;; Key bindings
19063 ;; Outline functions from `outline-mode-prefix-map'
19064 ;; that can be remapped in Org:
19065 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19066 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19067 (define-key org-mode-map [remap outline-forward-same-level]
19068 'org-forward-heading-same-level)
19069 (define-key org-mode-map [remap outline-backward-same-level]
19070 'org-backward-heading-same-level)
19071 (define-key org-mode-map [remap show-branches]
19072 'org-kill-note-or-show-branches)
19073 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19074 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19075 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19077 ;; Outline functions from `outline-mode-prefix-map' that can not
19078 ;; be remapped in Org:
19080 ;; - the column "key binding" shows whether the Outline function is still
19081 ;; available in Org mode on the same key that it has been bound to in
19082 ;; Outline mode:
19083 ;; - "overridden": key used for a different functionality in Org mode
19084 ;; - else: key still bound to the same Outline function in Org mode
19086 ;; | Outline function | key binding | Org replacement |
19087 ;; |------------------------------------+-------------+-----------------------|
19088 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19089 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19090 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19091 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19092 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19093 ;; | `show-entry' | overridden | no replacement |
19094 ;; | `show-children' | `C-c C-i' | visibility cycling |
19095 ;; | `show-branches' | `C-c C-k' | still same function |
19096 ;; | `show-subtree' | overridden | visibility cycling |
19097 ;; | `show-all' | overridden | no replacement |
19098 ;; | `hide-subtree' | overridden | visibility cycling |
19099 ;; | `hide-body' | overridden | no replacement |
19100 ;; | `hide-entry' | overridden | visibility cycling |
19101 ;; | `hide-leaves' | overridden | no replacement |
19102 ;; | `hide-sublevels' | overridden | no replacement |
19103 ;; | `hide-other' | overridden | no replacement |
19105 ;; Make `C-c C-x' a prefix key
19106 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19108 ;; TAB key with modifiers
19109 (org-defkey org-mode-map "\C-i" 'org-cycle)
19110 (org-defkey org-mode-map [(tab)] 'org-cycle)
19111 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19112 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19113 ;; The following line is necessary under Suse GNU/Linux
19114 (unless (featurep 'xemacs)
19115 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19116 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19117 (define-key org-mode-map [backtab] 'org-shifttab)
19119 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19120 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19121 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19123 ;; Cursor keys with modifiers
19124 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19125 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19126 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19127 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19129 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19130 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19131 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19132 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19134 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19135 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19136 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19137 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19139 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19140 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19141 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19142 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19144 ;; Babel keys
19145 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19146 (mapc (lambda (pair)
19147 (define-key org-babel-map (car pair) (cdr pair)))
19148 org-babel-key-bindings)
19150 ;;; Extra keys for tty access.
19151 ;; We only set them when really needed because otherwise the
19152 ;; menus don't show the simple keys
19154 (when (or org-use-extra-keys
19155 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19156 (not window-system))
19157 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19158 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19159 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19160 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19161 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19162 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19163 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19164 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19165 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19166 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19167 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19168 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19169 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19170 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19171 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19172 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19173 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19174 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19175 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19176 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19177 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19178 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19179 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19180 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19181 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19182 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19183 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19184 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19186 ;; All the other keys
19188 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19189 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19190 (if (boundp 'narrow-map)
19191 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19192 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19193 (if (boundp 'narrow-map)
19194 (org-defkey narrow-map "b" 'org-narrow-to-block)
19195 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19196 (if (boundp 'narrow-map)
19197 (org-defkey narrow-map "e" 'org-narrow-to-element)
19198 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19199 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19200 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19201 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19202 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19203 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19204 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19205 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19206 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19207 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19208 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19209 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19210 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19211 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19212 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19213 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19214 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19215 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19216 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19217 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19218 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19219 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19220 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19221 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19222 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19223 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19224 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19225 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19226 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19227 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19228 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19229 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19230 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19231 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19232 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19233 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19234 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19235 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19236 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19237 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19238 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19239 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19240 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19241 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19242 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19243 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19244 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19245 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19246 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19247 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19248 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19249 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19250 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19251 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19252 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19253 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19254 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19255 (org-defkey org-mode-map "\C-c^" 'org-sort)
19256 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19257 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19258 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19259 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19260 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19261 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19262 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19263 (org-defkey org-mode-map "\C-m" 'org-return)
19264 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19265 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19266 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19267 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19268 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19269 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19270 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19271 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19272 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19273 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19274 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19275 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19276 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19277 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19278 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19279 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19280 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19281 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19282 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19283 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19284 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19285 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19287 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19288 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19289 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19291 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19292 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19293 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19294 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19295 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19296 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19297 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19298 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19299 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19300 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19301 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19302 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19303 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19304 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19305 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19306 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19307 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19308 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19309 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19310 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19311 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19312 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19313 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19315 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19316 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19317 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19318 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19319 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19321 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19323 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19325 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19326 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19328 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19331 (when (featurep 'xemacs)
19332 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19335 (defconst org-speed-commands-default
19337 ("Outline Navigation")
19338 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19339 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19340 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19341 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19342 ("F" . org-next-block)
19343 ("B" . org-previous-block)
19344 ("u" . (org-speed-move-safe 'outline-up-heading))
19345 ("j" . org-goto)
19346 ("g" . (org-refile t))
19347 ("Outline Visibility")
19348 ("c" . org-cycle)
19349 ("C" . org-shifttab)
19350 (" " . org-display-outline-path)
19351 ("s" . org-narrow-to-subtree)
19352 ("=" . org-columns)
19353 ("Outline Structure Editing")
19354 ("U" . org-shiftmetaup)
19355 ("D" . org-shiftmetadown)
19356 ("r" . org-metaright)
19357 ("l" . org-metaleft)
19358 ("R" . org-shiftmetaright)
19359 ("L" . org-shiftmetaleft)
19360 ("i" . (progn (forward-char 1) (call-interactively
19361 'org-insert-heading-respect-content)))
19362 ("^" . org-sort)
19363 ("w" . org-refile)
19364 ("a" . org-archive-subtree-default-with-confirmation)
19365 ("@" . org-mark-subtree)
19366 ("#" . org-toggle-comment)
19367 ("Clock Commands")
19368 ("I" . org-clock-in)
19369 ("O" . org-clock-out)
19370 ("Meta Data Editing")
19371 ("t" . org-todo)
19372 ("," . (org-priority))
19373 ("0" . (org-priority ?\ ))
19374 ("1" . (org-priority ?A))
19375 ("2" . (org-priority ?B))
19376 ("3" . (org-priority ?C))
19377 (":" . org-set-tags-command)
19378 ("e" . org-set-effort)
19379 ("E" . org-inc-effort)
19380 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19381 (org-entry-put (point) "APPT_WARNTIME" m)))
19382 ("Agenda Views etc")
19383 ("v" . org-agenda)
19384 ("/" . org-sparse-tree)
19385 ("Misc")
19386 ("o" . org-open-at-point)
19387 ("?" . org-speed-command-help)
19388 ("<" . (org-agenda-set-restriction-lock 'subtree))
19389 (">" . (org-agenda-remove-restriction-lock))
19391 "The default speed commands.")
19393 (defun org-print-speed-command (e)
19394 (if (> (length (car e)) 1)
19395 (progn
19396 (princ "\n")
19397 (princ (car e))
19398 (princ "\n")
19399 (princ (make-string (length (car e)) ?-))
19400 (princ "\n"))
19401 (princ (car e))
19402 (princ " ")
19403 (if (symbolp (cdr e))
19404 (princ (symbol-name (cdr e)))
19405 (prin1 (cdr e)))
19406 (princ "\n")))
19408 (defun org-speed-command-help ()
19409 "Show the available speed commands."
19410 (interactive)
19411 (if (not org-use-speed-commands)
19412 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19413 (with-output-to-temp-buffer "*Help*"
19414 (princ "User-defined Speed commands\n===========================\n")
19415 (mapc 'org-print-speed-command org-speed-commands-user)
19416 (princ "\n")
19417 (princ "Built-in Speed commands\n=======================\n")
19418 (mapc 'org-print-speed-command org-speed-commands-default))
19419 (with-current-buffer "*Help*"
19420 (setq truncate-lines t))))
19422 (defun org-speed-move-safe (cmd)
19423 "Execute CMD, but make sure that the cursor always ends up in a headline.
19424 If not, return to the original position and throw an error."
19425 (interactive)
19426 (let ((pos (point)))
19427 (call-interactively cmd)
19428 (unless (and (bolp) (org-at-heading-p))
19429 (goto-char pos)
19430 (error "Boundary reached while executing %s" cmd))))
19432 (defvar org-self-insert-command-undo-counter 0)
19434 (defvar org-table-auto-blank-field) ; defined in org-table.el
19435 (defvar org-speed-command nil)
19437 (define-obsolete-function-alias
19438 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19440 (defun org-speed-command-activate (keys)
19441 "Hook for activating single-letter speed commands.
19442 `org-speed-commands-default' specifies a minimal command set.
19443 Use `org-speed-commands-user' for further customization."
19444 (when (or (and (bolp) (looking-at org-outline-regexp))
19445 (and (functionp org-use-speed-commands)
19446 (funcall org-use-speed-commands)))
19447 (cdr (assoc keys (append org-speed-commands-user
19448 org-speed-commands-default)))))
19450 (define-obsolete-function-alias
19451 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19453 (defun org-babel-speed-command-activate (keys)
19454 "Hook for activating single-letter code block commands."
19455 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19456 (cdr (assoc keys org-babel-key-bindings))))
19458 (defcustom org-speed-command-hook
19459 '(org-speed-command-default-hook org-babel-speed-command-hook)
19460 "Hook for activating speed commands at strategic locations.
19461 Hook functions are called in sequence until a valid handler is
19462 found.
19464 Each hook takes a single argument, a user-pressed command key
19465 which is also a `self-insert-command' from the global map.
19467 Within the hook, examine the cursor position and the command key
19468 and return nil or a valid handler as appropriate. Handler could
19469 be one of an interactive command, a function, or a form.
19471 Set `org-use-speed-commands' to non-nil value to enable this
19472 hook. The default setting is `org-speed-command-activate'."
19473 :group 'org-structure
19474 :version "24.1"
19475 :type 'hook)
19477 (defun org-self-insert-command (N)
19478 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19479 If the cursor is in a table looking at whitespace, the whitespace is
19480 overwritten, and the table is not marked as requiring realignment."
19481 (interactive "p")
19482 (org-check-before-invisible-edit 'insert)
19483 (cond
19484 ((and org-use-speed-commands
19485 (setq org-speed-command
19486 (run-hook-with-args-until-success
19487 'org-speed-command-hook (this-command-keys))))
19488 (cond
19489 ((commandp org-speed-command)
19490 (setq this-command org-speed-command)
19491 (call-interactively org-speed-command))
19492 ((functionp org-speed-command)
19493 (funcall org-speed-command))
19494 ((and org-speed-command (listp org-speed-command))
19495 (eval org-speed-command))
19496 (t (let (org-use-speed-commands)
19497 (call-interactively 'org-self-insert-command)))))
19498 ((and
19499 (org-table-p)
19500 (progn
19501 ;; check if we blank the field, and if that triggers align
19502 (and (featurep 'org-table) org-table-auto-blank-field
19503 (member last-command
19504 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19505 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19506 ;; got extra space, this field does not determine column width
19507 (let (org-table-may-need-update) (org-table-blank-field))
19508 ;; no extra space, this field may determine column width
19509 (org-table-blank-field)))
19511 (eq N 1)
19512 (looking-at "[^|\n]* |"))
19513 (let (org-table-may-need-update)
19514 (goto-char (1- (match-end 0)))
19515 (backward-delete-char 1)
19516 (goto-char (match-beginning 0))
19517 (self-insert-command N)))
19519 (setq org-table-may-need-update t)
19520 (self-insert-command N)
19521 (org-fix-tags-on-the-fly)
19522 (if org-self-insert-cluster-for-undo
19523 (if (not (eq last-command 'org-self-insert-command))
19524 (setq org-self-insert-command-undo-counter 1)
19525 (if (>= org-self-insert-command-undo-counter 20)
19526 (setq org-self-insert-command-undo-counter 1)
19527 (and (> org-self-insert-command-undo-counter 0)
19528 buffer-undo-list (listp buffer-undo-list)
19529 (not (cadr buffer-undo-list)) ; remove nil entry
19530 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19531 (setq org-self-insert-command-undo-counter
19532 (1+ org-self-insert-command-undo-counter))))))))
19534 (defun org-check-before-invisible-edit (kind)
19535 "Check is editing if kind KIND would be dangerous with invisible text around.
19536 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19537 ;; First, try to get out of here as quickly as possible, to reduce overhead
19538 (if (and org-catch-invisible-edits
19539 (or (not (boundp 'visible-mode)) (not visible-mode))
19540 (or (get-char-property (point) 'invisible)
19541 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19542 ;; OK, we need to take a closer look
19543 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19544 (invisible-before-point (if (bobp) nil (get-char-property
19545 (1- (point)) 'invisible)))
19546 (border-and-ok-direction
19548 ;; Check if we are acting predictably before invisible text
19549 (and invisible-at-point (not invisible-before-point)
19550 (memq kind '(insert delete-backward)))
19551 ;; Check if we are acting predictably after invisible text
19552 ;; This works not well, and I have turned it off. It seems
19553 ;; better to always show and stop after invisible text.
19554 ;; (and (not invisible-at-point) invisible-before-point
19555 ;; (memq kind '(insert delete)))
19557 (when (or (memq invisible-at-point '(outline org-hide-block t))
19558 (memq invisible-before-point '(outline org-hide-block t)))
19559 (if (eq org-catch-invisible-edits 'error)
19560 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19561 (if (and org-custom-properties-overlays
19562 (y-or-n-p "Display invisible properties in this buffer? "))
19563 (org-toggle-custom-properties-visibility)
19564 ;; Make the area visible
19565 (save-excursion
19566 (if invisible-before-point
19567 (goto-char (previous-single-char-property-change
19568 (point) 'invisible)))
19569 (org-cycle))
19570 (cond
19571 ((eq org-catch-invisible-edits 'show)
19572 ;; That's it, we do the edit after showing
19573 (message
19574 "Unfolding invisible region around point before editing")
19575 (sit-for 1))
19576 ((and (eq org-catch-invisible-edits 'smart)
19577 border-and-ok-direction)
19578 (message "Unfolding invisible region around point before editing"))
19580 ;; Don't do the edit, make the user repeat it in full visibility
19581 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19583 (defun org-fix-tags-on-the-fly ()
19584 (when (and (equal (char-after (point-at-bol)) ?*)
19585 (org-at-heading-p))
19586 (org-align-tags-here org-tags-column)))
19588 (defun org-delete-backward-char (N)
19589 "Like `delete-backward-char', insert whitespace at field end in tables.
19590 When deleting backwards, in tables this function will insert whitespace in
19591 front of the next \"|\" separator, to keep the table aligned. The table will
19592 still be marked for re-alignment if the field did fill the entire column,
19593 because, in this case the deletion might narrow the column."
19594 (interactive "p")
19595 (save-match-data
19596 (org-check-before-invisible-edit 'delete-backward)
19597 (if (and (org-table-p)
19598 (eq N 1)
19599 (string-match "|" (buffer-substring (point-at-bol) (point)))
19600 (looking-at ".*?|"))
19601 (let ((pos (point))
19602 (noalign (looking-at "[^|\n\r]* |"))
19603 (c org-table-may-need-update))
19604 (backward-delete-char N)
19605 (if (not overwrite-mode)
19606 (progn
19607 (skip-chars-forward "^|")
19608 (insert " ")
19609 (goto-char (1- pos))))
19610 ;; noalign: if there were two spaces at the end, this field
19611 ;; does not determine the width of the column.
19612 (if noalign (setq org-table-may-need-update c)))
19613 (backward-delete-char N)
19614 (org-fix-tags-on-the-fly))))
19616 (defun org-delete-char (N)
19617 "Like `delete-char', but insert whitespace at field end in tables.
19618 When deleting characters, in tables this function will insert whitespace in
19619 front of the next \"|\" separator, to keep the table aligned. The table will
19620 still be marked for re-alignment if the field did fill the entire column,
19621 because, in this case the deletion might narrow the column."
19622 (interactive "p")
19623 (save-match-data
19624 (org-check-before-invisible-edit 'delete)
19625 (if (and (org-table-p)
19626 (not (bolp))
19627 (not (= (char-after) ?|))
19628 (eq N 1))
19629 (if (looking-at ".*?|")
19630 (let ((pos (point))
19631 (noalign (looking-at "[^|\n\r]* |"))
19632 (c org-table-may-need-update))
19633 (replace-match
19634 (concat (substring (match-string 0) 1 -1) " |") nil t)
19635 (goto-char pos)
19636 ;; noalign: if there were two spaces at the end, this field
19637 ;; does not determine the width of the column.
19638 (if noalign (setq org-table-may-need-update c)))
19639 (delete-char N))
19640 (delete-char N)
19641 (org-fix-tags-on-the-fly))))
19643 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19644 (put 'org-self-insert-command 'delete-selection
19645 (lambda ()
19646 (not (run-hook-with-args-until-success
19647 'self-insert-uses-region-functions))))
19648 (put 'orgtbl-self-insert-command 'delete-selection
19649 (lambda ()
19650 (not (run-hook-with-args-until-success
19651 'self-insert-uses-region-functions))))
19652 (put 'org-delete-char 'delete-selection 'supersede)
19653 (put 'org-delete-backward-char 'delete-selection 'supersede)
19654 (put 'org-yank 'delete-selection 'yank)
19656 ;; Make `flyspell-mode' delay after some commands
19657 (put 'org-self-insert-command 'flyspell-delayed t)
19658 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19659 (put 'org-delete-char 'flyspell-delayed t)
19660 (put 'org-delete-backward-char 'flyspell-delayed t)
19662 ;; Make pabbrev-mode expand after org-mode commands
19663 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19664 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19666 (defun org-remap (map &rest commands)
19667 "In MAP, remap the functions given in COMMANDS.
19668 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19669 (let (new old)
19670 (while commands
19671 (setq old (pop commands) new (pop commands))
19672 (if (fboundp 'command-remapping)
19673 (org-defkey map (vector 'remap old) new)
19674 (substitute-key-definition old new map global-map)))))
19676 (defun org-transpose-words ()
19677 "Transpose words for Org.
19678 This uses the `org-mode-transpose-word-syntax-table' syntax
19679 table, which interprets characters in `org-emphasis-alist' as
19680 word constituents."
19681 (interactive)
19682 (with-syntax-table org-mode-transpose-word-syntax-table
19683 (call-interactively 'transpose-words)))
19684 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19686 (when (eq org-enable-table-editor 'optimized)
19687 ;; If the user wants maximum table support, we need to hijack
19688 ;; some standard editing functions
19689 (org-remap org-mode-map
19690 'self-insert-command 'org-self-insert-command
19691 'delete-char 'org-delete-char
19692 'delete-backward-char 'org-delete-backward-char)
19693 (org-defkey org-mode-map "|" 'org-force-self-insert))
19695 (defvar org-ctrl-c-ctrl-c-hook nil
19696 "Hook for functions attaching themselves to `C-c C-c'.
19698 This can be used to add additional functionality to the C-c C-c
19699 key which executes context-dependent commands. This hook is run
19700 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19701 run after the last test.
19703 Each function will be called with no arguments. The function
19704 must check if the context is appropriate for it to act. If yes,
19705 it should do its thing and then return a non-nil value. If the
19706 context is wrong, just do nothing and return nil.")
19708 (defvar org-ctrl-c-ctrl-c-final-hook nil
19709 "Hook for functions attaching themselves to `C-c C-c'.
19711 This can be used to add additional functionality to the C-c C-c
19712 key which executes context-dependent commands. This hook is run
19713 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19714 before the first test.
19716 Each function will be called with no arguments. The function
19717 must check if the context is appropriate for it to act. If yes,
19718 it should do its thing and then return a non-nil value. If the
19719 context is wrong, just do nothing and return nil.")
19721 (defvar org-tab-first-hook nil
19722 "Hook for functions to attach themselves to TAB.
19723 See `org-ctrl-c-ctrl-c-hook' for more information.
19724 This hook runs as the first action when TAB is pressed, even before
19725 `org-cycle' messes around with the `outline-regexp' to cater for
19726 inline tasks and plain list item folding.
19727 If any function in this hook returns t, any other actions that
19728 would have been caused by TAB (such as table field motion or visibility
19729 cycling) will not occur.")
19731 (defvar org-tab-after-check-for-table-hook nil
19732 "Hook for functions to attach themselves to TAB.
19733 See `org-ctrl-c-ctrl-c-hook' for more information.
19734 This hook runs after it has been established that the cursor is not in a
19735 table, but before checking if the cursor is in a headline or if global cycling
19736 should be done.
19737 If any function in this hook returns t, not other actions like visibility
19738 cycling will be done.")
19740 (defvar org-tab-after-check-for-cycling-hook nil
19741 "Hook for functions to attach themselves to TAB.
19742 See `org-ctrl-c-ctrl-c-hook' for more information.
19743 This hook runs after it has been established that not table field motion and
19744 not visibility should be done because of current context. This is probably
19745 the place where a package like yasnippets can hook in.")
19747 (defvar org-tab-before-tab-emulation-hook nil
19748 "Hook for functions to attach themselves to TAB.
19749 See `org-ctrl-c-ctrl-c-hook' for more information.
19750 This hook runs after every other options for TAB have been exhausted, but
19751 before indentation and \t insertion takes place.")
19753 (defvar org-metaleft-hook nil
19754 "Hook for functions attaching themselves to `M-left'.
19755 See `org-ctrl-c-ctrl-c-hook' for more information.")
19756 (defvar org-metaright-hook nil
19757 "Hook for functions attaching themselves to `M-right'.
19758 See `org-ctrl-c-ctrl-c-hook' for more information.")
19759 (defvar org-metaup-hook nil
19760 "Hook for functions attaching themselves to `M-up'.
19761 See `org-ctrl-c-ctrl-c-hook' for more information.")
19762 (defvar org-metadown-hook nil
19763 "Hook for functions attaching themselves to `M-down'.
19764 See `org-ctrl-c-ctrl-c-hook' for more information.")
19765 (defvar org-shiftmetaleft-hook nil
19766 "Hook for functions attaching themselves to `M-S-left'.
19767 See `org-ctrl-c-ctrl-c-hook' for more information.")
19768 (defvar org-shiftmetaright-hook nil
19769 "Hook for functions attaching themselves to `M-S-right'.
19770 See `org-ctrl-c-ctrl-c-hook' for more information.")
19771 (defvar org-shiftmetaup-hook nil
19772 "Hook for functions attaching themselves to `M-S-up'.
19773 See `org-ctrl-c-ctrl-c-hook' for more information.")
19774 (defvar org-shiftmetadown-hook nil
19775 "Hook for functions attaching themselves to `M-S-down'.
19776 See `org-ctrl-c-ctrl-c-hook' for more information.")
19777 (defvar org-metareturn-hook nil
19778 "Hook for functions attaching themselves to `M-RET'.
19779 See `org-ctrl-c-ctrl-c-hook' for more information.")
19780 (defvar org-shiftup-hook nil
19781 "Hook for functions attaching themselves to `S-up'.
19782 See `org-ctrl-c-ctrl-c-hook' for more information.")
19783 (defvar org-shiftup-final-hook nil
19784 "Hook for functions attaching themselves to `S-up'.
19785 This one runs after all other options except shift-select have been excluded.
19786 See `org-ctrl-c-ctrl-c-hook' for more information.")
19787 (defvar org-shiftdown-hook nil
19788 "Hook for functions attaching themselves to `S-down'.
19789 See `org-ctrl-c-ctrl-c-hook' for more information.")
19790 (defvar org-shiftdown-final-hook nil
19791 "Hook for functions attaching themselves to `S-down'.
19792 This one runs after all other options except shift-select have been excluded.
19793 See `org-ctrl-c-ctrl-c-hook' for more information.")
19794 (defvar org-shiftleft-hook nil
19795 "Hook for functions attaching themselves to `S-left'.
19796 See `org-ctrl-c-ctrl-c-hook' for more information.")
19797 (defvar org-shiftleft-final-hook nil
19798 "Hook for functions attaching themselves to `S-left'.
19799 This one runs after all other options except shift-select have been excluded.
19800 See `org-ctrl-c-ctrl-c-hook' for more information.")
19801 (defvar org-shiftright-hook nil
19802 "Hook for functions attaching themselves to `S-right'.
19803 See `org-ctrl-c-ctrl-c-hook' for more information.")
19804 (defvar org-shiftright-final-hook nil
19805 "Hook for functions attaching themselves to `S-right'.
19806 This one runs after all other options except shift-select have been excluded.
19807 See `org-ctrl-c-ctrl-c-hook' for more information.")
19809 (defun org-modifier-cursor-error ()
19810 "Throw an error, a modified cursor command was applied in wrong context."
19811 (user-error "This command is active in special context like tables, headlines or items"))
19813 (defun org-shiftselect-error ()
19814 "Throw an error because Shift-Cursor command was applied in wrong context."
19815 (if (and (boundp 'shift-select-mode) shift-select-mode)
19816 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19817 (user-error "This command works only in special context like headlines or timestamps")))
19819 (defun org-call-for-shift-select (cmd)
19820 (let ((this-command-keys-shift-translated t))
19821 (call-interactively cmd)))
19823 (defun org-shifttab (&optional arg)
19824 "Global visibility cycling or move to previous table field.
19825 Call `org-table-previous-field' within a table.
19826 When ARG is nil, cycle globally through visibility states.
19827 When ARG is a numeric prefix, show contents of this level."
19828 (interactive "P")
19829 (cond
19830 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19831 ((integerp arg)
19832 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19833 (message "Content view to level: %d" arg)
19834 (org-content (prefix-numeric-value arg2))
19835 (org-cycle-show-empty-lines t)
19836 (setq org-cycle-global-status 'overview)))
19837 (t (call-interactively 'org-global-cycle))))
19839 (defun org-shiftmetaleft ()
19840 "Promote subtree or delete table column.
19841 Calls `org-promote-subtree', `org-outdent-item-tree', or
19842 `org-table-delete-column', depending on context. See the
19843 individual commands for more information."
19844 (interactive)
19845 (cond
19846 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19847 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19848 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19849 ((if (not (org-region-active-p)) (org-at-item-p)
19850 (save-excursion (goto-char (region-beginning))
19851 (org-at-item-p)))
19852 (call-interactively 'org-outdent-item-tree))
19853 (t (org-modifier-cursor-error))))
19855 (defun org-shiftmetaright ()
19856 "Demote subtree or insert table column.
19857 Calls `org-demote-subtree', `org-indent-item-tree', or
19858 `org-table-insert-column', depending on context. See the
19859 individual commands for more information."
19860 (interactive)
19861 (cond
19862 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19863 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19864 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19865 ((if (not (org-region-active-p)) (org-at-item-p)
19866 (save-excursion (goto-char (region-beginning))
19867 (org-at-item-p)))
19868 (call-interactively 'org-indent-item-tree))
19869 (t (org-modifier-cursor-error))))
19871 (defun org-shiftmetaup (&optional arg)
19872 "Move subtree up or kill table row.
19873 Calls `org-move-subtree-up' or `org-table-kill-row' or
19874 `org-move-item-up' or `org-timestamp-up', depending on context.
19875 See the individual commands for more information."
19876 (interactive "P")
19877 (cond
19878 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19879 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19880 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19881 ((org-at-item-p) (call-interactively 'org-move-item-up))
19882 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19883 (call-interactively 'org-timestamp-up)))
19884 (t (call-interactively 'org-drag-line-backward))))
19886 (defun org-shiftmetadown (&optional arg)
19887 "Move subtree down or insert table row.
19888 Calls `org-move-subtree-down' or `org-table-insert-row' or
19889 `org-move-item-down' or `org-timestamp-up', depending on context.
19890 See the individual commands for more information."
19891 (interactive "P")
19892 (cond
19893 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19894 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19895 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19896 ((org-at-item-p) (call-interactively 'org-move-item-down))
19897 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19898 (call-interactively 'org-timestamp-down)))
19899 (t (call-interactively 'org-drag-line-forward))))
19901 (defsubst org-hidden-tree-error ()
19902 (user-error
19903 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19905 (defun org-metaleft (&optional arg)
19906 "Promote heading or move table column to left.
19907 Calls `org-do-promote' or `org-table-move-column', depending on context.
19908 With no specific context, calls the Emacs default `backward-word'.
19909 See the individual commands for more information."
19910 (interactive "P")
19911 (cond
19912 ((run-hook-with-args-until-success 'org-metaleft-hook))
19913 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19914 ((org-with-limited-levels
19915 (or (org-at-heading-p)
19916 (and (org-region-active-p)
19917 (save-excursion
19918 (goto-char (region-beginning))
19919 (org-at-heading-p)))))
19920 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19921 (call-interactively 'org-do-promote))
19922 ;; At an inline task.
19923 ((org-at-heading-p)
19924 (call-interactively 'org-inlinetask-promote))
19925 ((or (org-at-item-p)
19926 (and (org-region-active-p)
19927 (save-excursion
19928 (goto-char (region-beginning))
19929 (org-at-item-p))))
19930 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19931 (call-interactively 'org-outdent-item))
19932 (t (call-interactively 'backward-word))))
19934 (defun org-metaright (&optional arg)
19935 "Demote a subtree, a list item or move table column to right.
19936 In front of a drawer or a block keyword, indent it correctly.
19937 With no specific context, calls the Emacs default `forward-word'.
19938 See the individual commands for more information."
19939 (interactive "P")
19940 (cond
19941 ((run-hook-with-args-until-success 'org-metaright-hook))
19942 ((org-at-table-p) (call-interactively 'org-table-move-column))
19943 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19944 ((org-at-block-p) (call-interactively 'org-indent-block))
19945 ((org-with-limited-levels
19946 (or (org-at-heading-p)
19947 (and (org-region-active-p)
19948 (save-excursion
19949 (goto-char (region-beginning))
19950 (org-at-heading-p)))))
19951 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19952 (call-interactively 'org-do-demote))
19953 ;; At an inline task.
19954 ((org-at-heading-p)
19955 (call-interactively 'org-inlinetask-demote))
19956 ((or (org-at-item-p)
19957 (and (org-region-active-p)
19958 (save-excursion
19959 (goto-char (region-beginning))
19960 (org-at-item-p))))
19961 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19962 (call-interactively 'org-indent-item))
19963 (t (call-interactively 'forward-word))))
19965 (defun org-check-for-hidden (what)
19966 "Check if there are hidden headlines/items in the current visual line.
19967 WHAT can be either `headlines' or `items'. If the current line is
19968 an outline or item heading and it has a folded subtree below it,
19969 this function returns t, nil otherwise."
19970 (let ((re (cond
19971 ((eq what 'headlines) org-outline-regexp-bol)
19972 ((eq what 'items) (org-item-beginning-re))
19973 (t (error "This should not happen"))))
19974 beg end)
19975 (save-excursion
19976 (catch 'exit
19977 (unless (org-region-active-p)
19978 (setq beg (point-at-bol))
19979 (beginning-of-line 2)
19980 (while (and (not (eobp)) ;; this is like `next-line'
19981 (get-char-property (1- (point)) 'invisible))
19982 (beginning-of-line 2))
19983 (setq end (point))
19984 (goto-char beg)
19985 (goto-char (point-at-eol))
19986 (setq end (max end (point)))
19987 (while (re-search-forward re end t)
19988 (if (get-char-property (match-beginning 0) 'invisible)
19989 (throw 'exit t))))
19990 nil))))
19992 (defun org-metaup (&optional arg)
19993 "Move subtree up or move table row up.
19994 Calls `org-move-subtree-up' or `org-table-move-row' or
19995 `org-move-item-up', depending on context. See the individual commands
19996 for more information."
19997 (interactive "P")
19998 (cond
19999 ((run-hook-with-args-until-success 'org-metaup-hook))
20000 ((org-region-active-p)
20001 (let* ((a (min (region-beginning) (region-end)))
20002 (b (1- (max (region-beginning) (region-end))))
20003 (c (save-excursion (goto-char a)
20004 (move-beginning-of-line 0)))
20005 (d (save-excursion (goto-char a)
20006 (move-end-of-line 0) (point))))
20007 (transpose-regions a b c d)
20008 (goto-char c)))
20009 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20010 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20011 ((org-at-item-p) (call-interactively 'org-move-item-up))
20012 (t (org-drag-element-backward))))
20014 (defun org-metadown (&optional arg)
20015 "Move subtree down or move table row down.
20016 Calls `org-move-subtree-down' or `org-table-move-row' or
20017 `org-move-item-down', depending on context. See the individual
20018 commands for more information."
20019 (interactive "P")
20020 (cond
20021 ((run-hook-with-args-until-success 'org-metadown-hook))
20022 ((org-region-active-p)
20023 (let* ((a (min (region-beginning) (region-end)))
20024 (b (max (region-beginning) (region-end)))
20025 (c (save-excursion (goto-char b)
20026 (move-beginning-of-line 1)))
20027 (d (save-excursion (goto-char b)
20028 (move-end-of-line 1) (1+ (point)))))
20029 (transpose-regions a b c d)
20030 (goto-char d)))
20031 ((org-at-table-p) (call-interactively 'org-table-move-row))
20032 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20033 ((org-at-item-p) (call-interactively 'org-move-item-down))
20034 (t (org-drag-element-forward))))
20036 (defun org-shiftup (&optional arg)
20037 "Increase item in timestamp or increase priority of current headline.
20038 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20039 depending on context. See the individual commands for more information."
20040 (interactive "P")
20041 (cond
20042 ((run-hook-with-args-until-success 'org-shiftup-hook))
20043 ((and org-support-shift-select (org-region-active-p))
20044 (org-call-for-shift-select 'previous-line))
20045 ((org-at-timestamp-p t)
20046 (call-interactively (if org-edit-timestamp-down-means-later
20047 'org-timestamp-down 'org-timestamp-up)))
20048 ((and (not (eq org-support-shift-select 'always))
20049 org-enable-priority-commands
20050 (org-at-heading-p))
20051 (call-interactively 'org-priority-up))
20052 ((and (not org-support-shift-select) (org-at-item-p))
20053 (call-interactively 'org-previous-item))
20054 ((org-clocktable-try-shift 'up arg))
20055 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20056 (org-support-shift-select
20057 (org-call-for-shift-select 'previous-line))
20058 (t (org-shiftselect-error))))
20060 (defun org-shiftdown (&optional arg)
20061 "Decrease item in timestamp or decrease priority of current headline.
20062 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20063 depending on context. See the individual commands for more information."
20064 (interactive "P")
20065 (cond
20066 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20067 ((and org-support-shift-select (org-region-active-p))
20068 (org-call-for-shift-select 'next-line))
20069 ((org-at-timestamp-p t)
20070 (call-interactively (if org-edit-timestamp-down-means-later
20071 'org-timestamp-up 'org-timestamp-down)))
20072 ((and (not (eq org-support-shift-select 'always))
20073 org-enable-priority-commands
20074 (org-at-heading-p))
20075 (call-interactively 'org-priority-down))
20076 ((and (not org-support-shift-select) (org-at-item-p))
20077 (call-interactively 'org-next-item))
20078 ((org-clocktable-try-shift 'down arg))
20079 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20080 (org-support-shift-select
20081 (org-call-for-shift-select 'next-line))
20082 (t (org-shiftselect-error))))
20084 (defun org-shiftright (&optional arg)
20085 "Cycle the thing at point or in the current line, depending on context.
20086 Depending on context, this does one of the following:
20088 - switch a timestamp at point one day into the future
20089 - on a headline, switch to the next TODO keyword.
20090 - on an item, switch entire list to the next bullet type
20091 - on a property line, switch to the next allowed value
20092 - on a clocktable definition line, move time block into the future"
20093 (interactive "P")
20094 (cond
20095 ((run-hook-with-args-until-success 'org-shiftright-hook))
20096 ((and org-support-shift-select (org-region-active-p))
20097 (org-call-for-shift-select 'forward-char))
20098 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20099 ((and (not (eq org-support-shift-select 'always))
20100 (org-at-heading-p))
20101 (let ((org-inhibit-logging
20102 (not org-treat-S-cursor-todo-selection-as-state-change))
20103 (org-inhibit-blocking
20104 (not org-treat-S-cursor-todo-selection-as-state-change)))
20105 (org-call-with-arg 'org-todo 'right)))
20106 ((or (and org-support-shift-select
20107 (not (eq org-support-shift-select 'always))
20108 (org-at-item-bullet-p))
20109 (and (not org-support-shift-select) (org-at-item-p)))
20110 (org-call-with-arg 'org-cycle-list-bullet nil))
20111 ((and (not (eq org-support-shift-select 'always))
20112 (org-at-property-p))
20113 (call-interactively 'org-property-next-allowed-value))
20114 ((org-clocktable-try-shift 'right arg))
20115 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20116 (org-support-shift-select
20117 (org-call-for-shift-select 'forward-char))
20118 (t (org-shiftselect-error))))
20120 (defun org-shiftleft (&optional arg)
20121 "Cycle the thing at point or in the current line, depending on context.
20122 Depending on context, this does one of the following:
20124 - switch a timestamp at point one day into the past
20125 - on a headline, switch to the previous TODO keyword.
20126 - on an item, switch entire list to the previous bullet type
20127 - on a property line, switch to the previous allowed value
20128 - on a clocktable definition line, move time block into the past"
20129 (interactive "P")
20130 (cond
20131 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20132 ((and org-support-shift-select (org-region-active-p))
20133 (org-call-for-shift-select 'backward-char))
20134 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20135 ((and (not (eq org-support-shift-select 'always))
20136 (org-at-heading-p))
20137 (let ((org-inhibit-logging
20138 (not org-treat-S-cursor-todo-selection-as-state-change))
20139 (org-inhibit-blocking
20140 (not org-treat-S-cursor-todo-selection-as-state-change)))
20141 (org-call-with-arg 'org-todo 'left)))
20142 ((or (and org-support-shift-select
20143 (not (eq org-support-shift-select 'always))
20144 (org-at-item-bullet-p))
20145 (and (not org-support-shift-select) (org-at-item-p)))
20146 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20147 ((and (not (eq org-support-shift-select 'always))
20148 (org-at-property-p))
20149 (call-interactively 'org-property-previous-allowed-value))
20150 ((org-clocktable-try-shift 'left arg))
20151 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20152 (org-support-shift-select
20153 (org-call-for-shift-select 'backward-char))
20154 (t (org-shiftselect-error))))
20156 (defun org-shiftcontrolright ()
20157 "Switch to next TODO set."
20158 (interactive)
20159 (cond
20160 ((and org-support-shift-select (org-region-active-p))
20161 (org-call-for-shift-select 'forward-word))
20162 ((and (not (eq org-support-shift-select 'always))
20163 (org-at-heading-p))
20164 (org-call-with-arg 'org-todo 'nextset))
20165 (org-support-shift-select
20166 (org-call-for-shift-select 'forward-word))
20167 (t (org-shiftselect-error))))
20169 (defun org-shiftcontrolleft ()
20170 "Switch to previous TODO set."
20171 (interactive)
20172 (cond
20173 ((and org-support-shift-select (org-region-active-p))
20174 (org-call-for-shift-select 'backward-word))
20175 ((and (not (eq org-support-shift-select 'always))
20176 (org-at-heading-p))
20177 (org-call-with-arg 'org-todo 'previousset))
20178 (org-support-shift-select
20179 (org-call-for-shift-select 'backward-word))
20180 (t (org-shiftselect-error))))
20182 (defun org-shiftcontrolup (&optional n)
20183 "Change timestamps synchronously up in CLOCK log lines.
20184 Optional argument N tells to change by that many units."
20185 (interactive "P")
20186 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20187 (let (org-support-shift-select)
20188 (org-clock-timestamps-up n))
20189 (user-error "Not at a clock log")))
20191 (defun org-shiftcontroldown (&optional n)
20192 "Change timestamps synchronously down in CLOCK log lines.
20193 Optional argument N tells to change by that many units."
20194 (interactive "P")
20195 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20196 (let (org-support-shift-select)
20197 (org-clock-timestamps-down n))
20198 (user-error "Not at a clock log")))
20200 (defun org-ctrl-c-ret ()
20201 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20202 (interactive)
20203 (cond
20204 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20205 (t (call-interactively 'org-insert-heading))))
20207 (defun org-find-visible ()
20208 (let ((s (point)))
20209 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20210 (get-char-property s 'invisible)))
20212 (defun org-find-invisible ()
20213 (let ((s (point)))
20214 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20215 (not (get-char-property s 'invisible))))
20218 (defun org-copy-visible (beg end)
20219 "Copy the visible parts of the region."
20220 (interactive "r")
20221 (let (snippets s)
20222 (save-excursion
20223 (save-restriction
20224 (narrow-to-region beg end)
20225 (setq s (goto-char (point-min)))
20226 (while (not (= (point) (point-max)))
20227 (goto-char (org-find-invisible))
20228 (push (buffer-substring s (point)) snippets)
20229 (setq s (goto-char (org-find-visible))))))
20230 (kill-new (apply 'concat (nreverse snippets)))))
20232 (defun org-copy-special ()
20233 "Copy region in table or copy current subtree.
20234 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20235 See the individual commands for more information."
20236 (interactive)
20237 (call-interactively
20238 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20240 (defun org-cut-special ()
20241 "Cut region in table or cut current subtree.
20242 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20243 See the individual commands for more information."
20244 (interactive)
20245 (call-interactively
20246 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20248 (defun org-paste-special (arg)
20249 "Paste rectangular region into table, or past subtree relative to level.
20250 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20251 See the individual commands for more information."
20252 (interactive "P")
20253 (if (org-at-table-p)
20254 (org-table-paste-rectangle)
20255 (org-paste-subtree arg)))
20257 (defsubst org-in-fixed-width-region-p ()
20258 "Is point in a fixed-width region?"
20259 (save-match-data
20260 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20262 (defun org-edit-special (&optional arg)
20263 "Call a special editor for the element at point.
20264 When at a table, call the formula editor with `org-table-edit-formulas'.
20265 When in a source code block, call `org-edit-src-code'.
20266 When in a fixed-width region, call `org-edit-fixed-width-region'.
20267 When at an #+INCLUDE keyword, visit the included file.
20268 On a link, call `ffap' to visit the link at point.
20269 Otherwise, return a user error."
20270 (interactive "P")
20271 (let ((element (org-element-at-point)))
20272 (assert (not buffer-read-only) nil
20273 "Buffer is read-only: %s" (buffer-name))
20274 (case (org-element-type element)
20275 (src-block
20276 (if (not arg) (org-edit-src-code)
20277 (let* ((info (org-babel-get-src-block-info))
20278 (lang (nth 0 info))
20279 (params (nth 2 info))
20280 (session (cdr (assq :session params))))
20281 (if (not session) (org-edit-src-code)
20282 ;; At a src-block with a session and function called with
20283 ;; an ARG: switch to the buffer related to the inferior
20284 ;; process.
20285 (switch-to-buffer
20286 (funcall (intern (concat "org-babel-prep-session:" lang))
20287 session params))))))
20288 (keyword
20289 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20290 (find-file-other-window
20291 (org-remove-double-quotes
20292 (car (org-split-string (org-element-property :value element)))))
20293 (user-error "No special environment to edit here")))
20294 (table
20295 (if (eq (org-element-property :type element) 'table.el)
20296 (org-edit-src-code)
20297 (call-interactively 'org-table-edit-formulas)))
20298 ;; Only Org tables contain `table-row' type elements.
20299 (table-row (call-interactively 'org-table-edit-formulas))
20300 ((example-block export-block) (org-edit-src-code))
20301 (fixed-width (org-edit-fixed-width-region))
20302 (otherwise
20303 ;; No notable element at point. Though, we may be at a link,
20304 ;; which is an object. Thus, scan deeper.
20305 (if (eq (org-element-type (org-element-context element)) 'link)
20306 (call-interactively 'ffap)
20307 (user-error "No special environment to edit here"))))))
20309 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20310 (defun org-ctrl-c-ctrl-c (&optional arg)
20311 "Set tags in headline, or update according to changed information at point.
20313 This command does many different things, depending on context:
20315 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20316 this is what we do.
20318 - If the cursor is on a statistics cookie, update it.
20320 - If the cursor is in a headline, prompt for tags and insert them
20321 into the current line, aligned to `org-tags-column'. When called
20322 with prefix arg, realign all tags in the current buffer.
20324 - If the cursor is in one of the special #+KEYWORD lines, this
20325 triggers scanning the buffer for these lines and updating the
20326 information.
20328 - If the cursor is inside a table, realign the table. This command
20329 works even if the automatic table editor has been turned off.
20331 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20332 the entire table.
20334 - If the cursor is at a footnote reference or definition, jump to
20335 the corresponding definition or references, respectively.
20337 - If the cursor is a the beginning of a dynamic block, update it.
20339 - If the current buffer is a capture buffer, close note and file it.
20341 - If the cursor is on a <<<target>>>, update radio targets and
20342 corresponding links in this buffer.
20344 - If the cursor is on a numbered item in a plain list, renumber the
20345 ordered list.
20347 - If the cursor is on a checkbox, toggle it.
20349 - If the cursor is on a code block, evaluate it. The variable
20350 `org-confirm-babel-evaluate' can be used to control prompting
20351 before code block evaluation, by default every code block
20352 evaluation requires confirmation. Code block evaluation can be
20353 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20354 (interactive "P")
20355 (cond
20356 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20357 org-occur-highlights
20358 org-latex-fragment-image-overlays)
20359 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20360 (org-remove-occur-highlights)
20361 (org-remove-latex-fragment-image-overlays)
20362 (message "Temporary highlights/overlays removed from current buffer"))
20363 ((and (local-variable-p 'org-finish-function (current-buffer))
20364 (fboundp org-finish-function))
20365 (funcall org-finish-function))
20366 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20368 (let* ((context (org-element-context)) (type (org-element-type context)))
20369 ;; Test if point is within a blank line.
20370 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20371 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20372 (user-error "C-c C-c can do nothing useful at this location"))
20373 (case type
20374 ;; When at a link, act according to the parent instead.
20375 (link (setq context (org-element-property :parent context))
20376 (setq type (org-element-type context)))
20377 ;; Unsupported object types: check parent element instead.
20378 ((bold code entity export-snippet inline-babel-call inline-src-block
20379 italic latex-fragment line-break macro strike-through subscript
20380 superscript underline verbatim)
20381 (while (and (setq context (org-element-property :parent context))
20382 (not (memq (setq type (org-element-type context))
20383 '(paragraph verse-block)))))))
20384 ;; For convenience: at the first line of a paragraph on the
20385 ;; same line as an item, apply function on that item instead.
20386 (when (eq type 'paragraph)
20387 (let ((parent (org-element-property :parent context)))
20388 (when (and (eq (org-element-type parent) 'item)
20389 (= (point-at-bol) (org-element-property :begin parent)))
20390 (setq context parent type 'item))))
20391 ;; Act according to type of element or object at point.
20392 (case type
20393 (clock (org-clock-update-time-maybe))
20394 (dynamic-block
20395 (save-excursion
20396 (goto-char (org-element-property :post-affiliated context))
20397 (org-update-dblock)))
20398 (footnote-definition
20399 (goto-char (org-element-property :post-affiliated context))
20400 (call-interactively 'org-footnote-action))
20401 (footnote-reference (call-interactively 'org-footnote-action))
20402 ((headline inlinetask)
20403 (save-excursion (goto-char (org-element-property :begin context))
20404 (call-interactively 'org-set-tags)))
20405 (item
20406 ;; At an item: a double C-u set checkbox to "[-]"
20407 ;; unconditionally, whereas a single one will toggle its
20408 ;; presence. Without an universal argument, if the item
20409 ;; has a checkbox, toggle it. Otherwise repair the list.
20410 (let* ((box (org-element-property :checkbox context))
20411 (struct (org-element-property :structure context))
20412 (old-struct (copy-tree struct))
20413 (parents (org-list-parents-alist struct))
20414 (prevs (org-list-prevs-alist struct))
20415 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20416 (org-list-set-checkbox
20417 (org-element-property :begin context) struct
20418 (cond ((equal arg '(16)) "[-]")
20419 ((and (not box) (equal arg '(4))) "[ ]")
20420 ((or (not box) (equal arg '(4))) nil)
20421 ((eq box 'on) "[ ]")
20422 (t "[X]")))
20423 ;; Mimic `org-list-write-struct' but with grabbing
20424 ;; a return value from `org-list-struct-fix-box'.
20425 (org-list-struct-fix-ind struct parents 2)
20426 (org-list-struct-fix-item-end struct)
20427 (org-list-struct-fix-bul struct prevs)
20428 (org-list-struct-fix-ind struct parents)
20429 (let ((block-item
20430 (org-list-struct-fix-box struct parents prevs orderedp)))
20431 (if (and box (equal struct old-struct))
20432 (if (equal arg '(16))
20433 (message "Checkboxes already reset")
20434 (user-error "Cannot toggle this checkbox: %s"
20435 (if (eq box 'on)
20436 "all subitems checked"
20437 "unchecked subitems")))
20438 (org-list-struct-apply-struct struct old-struct)
20439 (org-update-checkbox-count-maybe))
20440 (when block-item
20441 (message "Checkboxes were removed due to empty box at line %d"
20442 (org-current-line block-item))))))
20443 (keyword
20444 (let ((org-inhibit-startup-visibility-stuff t)
20445 (org-startup-align-all-tables nil))
20446 (when (boundp 'org-table-coordinate-overlays)
20447 (mapc 'delete-overlay org-table-coordinate-overlays)
20448 (setq org-table-coordinate-overlays nil))
20449 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20450 (message "Local setup has been refreshed"))
20451 (plain-list
20452 ;; At a plain list, with a double C-u argument, set
20453 ;; checkboxes of each item to "[-]", whereas a single one
20454 ;; will toggle their presence according to the state of the
20455 ;; first item in the list. Without an argument, repair the
20456 ;; list.
20457 (let* ((begin (org-element-property :contents-begin context))
20458 (beginm (move-marker (make-marker) begin))
20459 (struct (org-element-property :structure context))
20460 (old-struct (copy-tree struct))
20461 (first-box (save-excursion
20462 (goto-char begin)
20463 (looking-at org-list-full-item-re)
20464 (match-string-no-properties 3)))
20465 (new-box (cond ((equal arg '(16)) "[-]")
20466 ((equal arg '(4)) (unless first-box "[ ]"))
20467 ((equal first-box "[X]") "[ ]")
20468 (t "[X]"))))
20469 (cond
20470 (arg
20471 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20472 (org-list-get-all-items
20473 begin struct (org-list-prevs-alist struct))))
20474 ((and first-box (eq (point) begin))
20475 ;; For convenience, when point is at bol on the first
20476 ;; item of the list and no argument is provided, simply
20477 ;; toggle checkbox of that item, if any.
20478 (org-list-set-checkbox begin struct new-box)))
20479 (org-list-write-struct
20480 struct (org-list-parents-alist struct) old-struct)
20481 (org-update-checkbox-count-maybe)
20482 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20483 ((property-drawer node-property)
20484 (call-interactively 'org-property-action))
20485 ((radio-target target)
20486 (call-interactively 'org-update-radio-target-regexp))
20487 (statistics-cookie
20488 (call-interactively 'org-update-statistics-cookies))
20489 ((table table-cell table-row)
20490 ;; At a table, recalculate every field and align it. Also
20491 ;; send the table if necessary. If the table has
20492 ;; a `table.el' type, just give up. At a table row or
20493 ;; cell, maybe recalculate line but always align table.
20494 (if (eq (org-element-property :type context) 'table.el)
20495 (message "Use C-c ' to edit table.el tables")
20496 (let ((org-enable-table-editor t))
20497 (if (or (eq type 'table)
20498 ;; Check if point is at a TBLFM line.
20499 (and (eq type 'table-row)
20500 (= (point) (org-element-property :end context))))
20501 (save-excursion
20502 (if (org-at-TBLFM-p)
20503 (progn (require 'org-table)
20504 (org-table-calc-current-TBLFM))
20505 (goto-char (org-element-property :contents-begin context))
20506 (org-call-with-arg 'org-table-recalculate (or arg t))
20507 (orgtbl-send-table 'maybe)))
20508 (org-table-maybe-eval-formula)
20509 (cond (arg (call-interactively 'org-table-recalculate))
20510 ((org-table-maybe-recalculate-line))
20511 (t (org-table-align)))))))
20512 (timestamp (org-timestamp-change 0 'day))
20513 (otherwise
20514 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20515 (user-error
20516 "C-c C-c can do nothing useful at this location")))))))))
20518 (defun org-mode-restart ()
20519 (interactive)
20520 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20521 (funcall major-mode)
20522 (hack-local-variables)
20523 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20524 (org-indent-mode -1)))
20525 (message "%s restarted" major-mode))
20527 (defun org-kill-note-or-show-branches ()
20528 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20529 (interactive)
20530 (if (not org-finish-function)
20531 (progn
20532 (hide-subtree)
20533 (call-interactively 'show-branches))
20534 (let ((org-note-abort t))
20535 (funcall org-finish-function))))
20537 (defun org-open-line (n)
20538 "Insert a new row in tables, call `open-line' elsewhere.
20539 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20540 (interactive "*p")
20541 (cond
20542 ((not org-special-ctrl-o)
20543 (open-line n))
20544 ((org-at-table-p)
20545 (org-table-insert-row))
20547 (open-line n))))
20549 (defun org-return (&optional indent)
20550 "Goto next table row or insert a newline.
20551 Calls `org-table-next-row' or `newline', depending on context.
20552 See the individual commands for more information."
20553 (interactive)
20554 (let (org-ts-what)
20555 (cond
20556 ((or (bobp) (org-in-src-block-p))
20557 (if indent (newline-and-indent) (newline)))
20558 ((org-at-table-p)
20559 (org-table-justify-field-maybe)
20560 (call-interactively 'org-table-next-row))
20561 ;; when `newline-and-indent' is called within a list, make sure
20562 ;; text moved stays inside the item.
20563 ((and (org-in-item-p) indent)
20564 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20565 (progn
20566 (save-match-data (newline))
20567 (org-indent-line-to (length (match-string 0))))
20568 (let ((ind (org-get-indentation)))
20569 (newline)
20570 (if (org-looking-back org-list-end-re)
20571 (org-indent-line)
20572 (org-indent-line-to ind)))))
20573 ((and org-return-follows-link
20574 (org-at-timestamp-p t)
20575 (not (eq org-ts-what 'after)))
20576 (org-follow-timestamp-link))
20577 ((and org-return-follows-link
20578 (let ((tprop (get-text-property (point) 'face)))
20579 (or (eq tprop 'org-link)
20580 (and (listp tprop) (memq 'org-link tprop)))))
20581 (call-interactively 'org-open-at-point))
20582 ((and (org-at-heading-p)
20583 (looking-at
20584 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20585 (org-show-entry)
20586 (end-of-line 1)
20587 (newline))
20588 (t (if indent (newline-and-indent) (newline))))))
20590 (defun org-return-indent ()
20591 "Goto next table row or insert a newline and indent.
20592 Calls `org-table-next-row' or `newline-and-indent', depending on
20593 context. See the individual commands for more information."
20594 (interactive)
20595 (org-return t))
20597 (defun org-ctrl-c-star ()
20598 "Compute table, or change heading status of lines.
20599 Calls `org-table-recalculate' or `org-toggle-heading',
20600 depending on context."
20601 (interactive)
20602 (cond
20603 ((org-at-table-p)
20604 (call-interactively 'org-table-recalculate))
20606 ;; Convert all lines in region to list items
20607 (call-interactively 'org-toggle-heading))))
20609 (defun org-ctrl-c-minus ()
20610 "Insert separator line in table or modify bullet status of line.
20611 Also turns a plain line or a region of lines into list items.
20612 Calls `org-table-insert-hline', `org-toggle-item', or
20613 `org-cycle-list-bullet', depending on context."
20614 (interactive)
20615 (cond
20616 ((org-at-table-p)
20617 (call-interactively 'org-table-insert-hline))
20618 ((org-region-active-p)
20619 (call-interactively 'org-toggle-item))
20620 ((org-in-item-p)
20621 (call-interactively 'org-cycle-list-bullet))
20623 (call-interactively 'org-toggle-item))))
20625 (defun org-toggle-item (arg)
20626 "Convert headings or normal lines to items, items to normal lines.
20627 If there is no active region, only the current line is considered.
20629 If the first non blank line in the region is a headline, convert
20630 all headlines to items, shifting text accordingly.
20632 If it is an item, convert all items to normal lines.
20634 If it is normal text, change region into a list of items.
20635 With a prefix argument ARG, change the region in a single item."
20636 (interactive "P")
20637 (let ((shift-text
20638 (function
20639 ;; Shift text in current section to IND, from point to END.
20640 ;; The function leaves point to END line.
20641 (lambda (ind end)
20642 (let ((min-i 1000) (end (copy-marker end)))
20643 ;; First determine the minimum indentation (MIN-I) of
20644 ;; the text.
20645 (save-excursion
20646 (catch 'exit
20647 (while (< (point) end)
20648 (let ((i (org-get-indentation)))
20649 (cond
20650 ;; Skip blank lines and inline tasks.
20651 ((looking-at "^[ \t]*$"))
20652 ((looking-at org-outline-regexp-bol))
20653 ;; We can't find less than 0 indentation.
20654 ((zerop i) (throw 'exit (setq min-i 0)))
20655 ((< i min-i) (setq min-i i))))
20656 (forward-line))))
20657 ;; Then indent each line so that a line indented to
20658 ;; MIN-I becomes indented to IND. Ignore blank lines
20659 ;; and inline tasks in the process.
20660 (let ((delta (- ind min-i)))
20661 (while (< (point) end)
20662 (unless (or (looking-at "^[ \t]*$")
20663 (looking-at org-outline-regexp-bol))
20664 (org-indent-line-to (+ (org-get-indentation) delta)))
20665 (forward-line)))))))
20666 (skip-blanks
20667 (function
20668 ;; Return beginning of first non-blank line, starting from
20669 ;; line at POS.
20670 (lambda (pos)
20671 (save-excursion
20672 (goto-char pos)
20673 (skip-chars-forward " \r\t\n")
20674 (point-at-bol)))))
20675 beg end)
20676 ;; Determine boundaries of changes.
20677 (if (org-region-active-p)
20678 (setq beg (funcall skip-blanks (region-beginning))
20679 end (copy-marker (region-end)))
20680 (setq beg (funcall skip-blanks (point-at-bol))
20681 end (copy-marker (point-at-eol))))
20682 ;; Depending on the starting line, choose an action on the text
20683 ;; between BEG and END.
20684 (org-with-limited-levels
20685 (save-excursion
20686 (goto-char beg)
20687 (cond
20688 ;; Case 1. Start at an item: de-itemize. Note that it only
20689 ;; happens when a region is active: `org-ctrl-c-minus'
20690 ;; would call `org-cycle-list-bullet' otherwise.
20691 ((org-at-item-p)
20692 (while (< (point) end)
20693 (when (org-at-item-p)
20694 (skip-chars-forward " \t")
20695 (delete-region (point) (match-end 0)))
20696 (forward-line)))
20697 ;; Case 2. Start at an heading: convert to items.
20698 ((org-at-heading-p)
20699 (let* ((bul (org-list-bullet-string "-"))
20700 (bul-len (length bul))
20701 (done (org-entry-is-done-p))
20702 (todo (org-entry-is-todo-p))
20703 ;; Indentation of the first heading. It should be
20704 ;; relative to the indentation of its parent, if any.
20705 (start-ind (save-excursion
20706 (cond
20707 ((not org-adapt-indentation) 0)
20708 ((not (outline-previous-heading)) 0)
20709 (t (length (match-string 0))))))
20710 ;; Level of first heading. Further headings will be
20711 ;; compared to it to determine hierarchy in the list.
20712 (ref-level (org-reduced-level (org-outline-level))))
20713 (when (or done todo) (org-todo ""))
20714 (while (< (point) end)
20715 (let* ((level (org-reduced-level (org-outline-level)))
20716 (delta (max 0 (- level ref-level))))
20717 ;; If current headline is less indented than the first
20718 ;; one, set it as reference, in order to preserve
20719 ;; subtrees.
20720 (when (< level ref-level) (setq ref-level level))
20721 (replace-match bul t t)
20722 (org-indent-line-to (+ start-ind (* delta bul-len)))
20723 (when (or done todo)
20724 (let* ((struct (org-list-struct))
20725 (old (copy-tree struct)))
20726 (org-list-set-checkbox (line-beginning-position)
20727 struct
20728 (if done "[X]" "[ ]"))
20729 (org-list-write-struct struct
20730 (org-list-parents-alist struct)
20731 old)))
20732 ;; Ensure all text down to END (or SECTION-END) belongs
20733 ;; to the newly created item.
20734 (let ((section-end (save-excursion
20735 (or (outline-next-heading) (point)))))
20736 (forward-line)
20737 (funcall shift-text
20738 (+ start-ind (* (1+ delta) bul-len))
20739 (min end section-end)))))))
20740 ;; Case 3. Normal line with ARG: make the first line of region
20741 ;; an item, and shift indentation of others lines to
20742 ;; set them as item's body.
20743 (arg (let* ((bul (org-list-bullet-string "-"))
20744 (bul-len (length bul))
20745 (ref-ind (org-get-indentation)))
20746 (skip-chars-forward " \t")
20747 (insert bul)
20748 (forward-line)
20749 (while (< (point) end)
20750 ;; Ensure that lines less indented than first one
20751 ;; still get included in item body.
20752 (funcall shift-text
20753 (+ ref-ind bul-len)
20754 (min end (save-excursion (or (outline-next-heading)
20755 (point)))))
20756 (forward-line))))
20757 ;; Case 4. Normal line without ARG: turn each non-item line
20758 ;; into an item.
20760 (while (< (point) end)
20761 (unless (or (org-at-heading-p) (org-at-item-p))
20762 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20763 (replace-match
20764 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20765 (forward-line))))))))
20767 (defun org-toggle-heading (&optional nstars)
20768 "Convert headings to normal text, or items or text to headings.
20769 If there is no active region, only convert the current line.
20771 With a \\[universal-argument] prefix, convert the whole list at
20772 point into heading.
20774 In a region:
20776 - If the first non blank line is a headline, remove the stars
20777 from all headlines in the region.
20779 - If it is a normal line, turn each and every normal line (i.e.,
20780 not an heading or an item) in the region into headings. If you
20781 want to convert only the first line of this region, use one
20782 universal prefix argument.
20784 - If it is a plain list item, turn all plain list items into headings.
20786 When converting a line into a heading, the number of stars is chosen
20787 such that the lines become children of the current entry. However,
20788 when a numeric prefix argument is given, its value determines the
20789 number of stars to add."
20790 (interactive "P")
20791 (let ((skip-blanks
20792 (function
20793 ;; Return beginning of first non-blank line, starting from
20794 ;; line at POS.
20795 (lambda (pos)
20796 (save-excursion
20797 (goto-char pos)
20798 (while (org-at-comment-p) (forward-line))
20799 (skip-chars-forward " \r\t\n")
20800 (point-at-bol)))))
20801 beg end toggled)
20802 ;; Determine boundaries of changes. If a universal prefix has
20803 ;; been given, put the list in a region. If region ends at a bol,
20804 ;; do not consider the last line to be in the region.
20806 (when (and current-prefix-arg (org-at-item-p))
20807 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20808 (org-mark-element))
20810 (if (org-region-active-p)
20811 (setq beg (funcall skip-blanks (region-beginning))
20812 end (copy-marker (save-excursion
20813 (goto-char (region-end))
20814 (if (bolp) (point) (point-at-eol)))))
20815 (setq beg (funcall skip-blanks (point-at-bol))
20816 end (copy-marker (point-at-eol))))
20817 ;; Ensure inline tasks don't count as headings.
20818 (org-with-limited-levels
20819 (save-excursion
20820 (goto-char beg)
20821 (cond
20822 ;; Case 1. Started at an heading: de-star headings.
20823 ((org-at-heading-p)
20824 (while (< (point) end)
20825 (when (org-at-heading-p t)
20826 (looking-at org-outline-regexp) (replace-match "")
20827 (setq toggled t))
20828 (forward-line)))
20829 ;; Case 2. Started at an item: change items into headlines.
20830 ;; One star will be added by `org-list-to-subtree'.
20831 ((org-at-item-p)
20832 (let* ((stars (make-string
20833 ;; subtract the star that will be added again by
20834 ;; `org-list-to-subtree'
20835 (if (numberp nstars) (1- nstars)
20836 (or (org-current-level) 0))
20837 ?*))
20838 (add-stars
20839 (cond (nstars "") ; stars from prefix only
20840 ((equal stars "") "") ; before first heading
20841 (org-odd-levels-only "*") ; inside heading, odd
20842 (t "")))) ; inside heading, oddeven
20843 (while (< (point) end)
20844 (when (org-at-item-p)
20845 ;; Pay attention to cases when region ends before list.
20846 (let* ((struct (org-list-struct))
20847 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20848 (save-restriction
20849 (narrow-to-region (point) list-end)
20850 (insert
20851 (org-list-to-subtree
20852 (org-list-parse-list t)
20853 '(:istart (concat stars add-stars (funcall get-stars depth))
20854 :icount (concat stars add-stars (funcall get-stars depth)))))))
20855 (setq toggled t))
20856 (forward-line))))
20857 ;; Case 3. Started at normal text: make every line an heading,
20858 ;; skipping headlines and items.
20859 (t (let* ((stars
20860 (make-string
20861 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20862 (add-stars
20863 (cond (nstars "") ; stars from prefix only
20864 ((equal stars "") "*") ; before first heading
20865 (org-odd-levels-only "**") ; inside heading, odd
20866 (t "*"))) ; inside heading, oddeven
20867 (rpl (concat stars add-stars " "))
20868 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20869 (while (< (point) (if (equal nstars '(4)) lend end))
20870 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20871 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20872 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20873 (forward-line)))))))
20874 (unless toggled (message "Cannot toggle heading from here"))))
20876 (defun org-meta-return (&optional arg)
20877 "Insert a new heading or wrap a region in a table.
20878 Calls `org-insert-heading' or `org-table-wrap-region', depending
20879 on context. See the individual commands for more information."
20880 (interactive "P")
20881 (org-check-before-invisible-edit 'insert)
20882 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20883 (let* ((element (org-element-at-point))
20884 (type (org-element-type element)))
20885 (when (eq type 'table-row)
20886 (setq element (org-element-property :parent element))
20887 (setq type 'table))
20888 (if (and (eq type 'table)
20889 (eq (org-element-property :type element) 'org)
20890 (>= (point) (org-element-property :contents-begin element))
20891 (< (point) (org-element-property :contents-end element)))
20892 (call-interactively 'org-table-wrap-region)
20893 (call-interactively 'org-insert-heading)))))
20895 ;;; Menu entries
20897 (defsubst org-in-subtree-not-table-p ()
20898 "Are we in a subtree and not in a table?"
20899 (and (not (org-before-first-heading-p))
20900 (not (org-at-table-p))))
20902 ;; Define the Org-mode menus
20903 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20904 '("Tbl"
20905 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20906 ["Next Field" org-cycle (org-at-table-p)]
20907 ["Previous Field" org-shifttab (org-at-table-p)]
20908 ["Next Row" org-return (org-at-table-p)]
20909 "--"
20910 ["Blank Field" org-table-blank-field (org-at-table-p)]
20911 ["Edit Field" org-table-edit-field (org-at-table-p)]
20912 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20913 "--"
20914 ("Column"
20915 ["Move Column Left" org-metaleft (org-at-table-p)]
20916 ["Move Column Right" org-metaright (org-at-table-p)]
20917 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20918 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20919 ("Row"
20920 ["Move Row Up" org-metaup (org-at-table-p)]
20921 ["Move Row Down" org-metadown (org-at-table-p)]
20922 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20923 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20924 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20925 "--"
20926 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20927 ("Rectangle"
20928 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20929 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20930 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20931 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20932 "--"
20933 ("Calculate"
20934 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20935 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20936 ["Edit Formulas" org-edit-special (org-at-table-p)]
20937 "--"
20938 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20939 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20940 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20941 "--"
20942 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20943 "--"
20944 ["Sum Column/Rectangle" org-table-sum
20945 (or (org-at-table-p) (org-region-active-p))]
20946 ["Which Column?" org-table-current-column (org-at-table-p)])
20947 ["Debug Formulas"
20948 org-table-toggle-formula-debugger
20949 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20950 ["Show Col/Row Numbers"
20951 org-table-toggle-coordinate-overlays
20952 :style toggle
20953 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20954 "--"
20955 ["Create" org-table-create (and (not (org-at-table-p))
20956 org-enable-table-editor)]
20957 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20958 ["Import from File" org-table-import (not (org-at-table-p))]
20959 ["Export to File" org-table-export (org-at-table-p)]
20960 "--"
20961 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20963 (easy-menu-define org-org-menu org-mode-map "Org menu"
20964 '("Org"
20965 ("Show/Hide"
20966 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20967 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20968 ["Sparse Tree..." org-sparse-tree t]
20969 ["Reveal Context" org-reveal t]
20970 ["Show All" show-all t]
20971 "--"
20972 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20973 "--"
20974 ["New Heading" org-insert-heading t]
20975 ("Navigate Headings"
20976 ["Up" outline-up-heading t]
20977 ["Next" outline-next-visible-heading t]
20978 ["Previous" outline-previous-visible-heading t]
20979 ["Next Same Level" outline-forward-same-level t]
20980 ["Previous Same Level" outline-backward-same-level t]
20981 "--"
20982 ["Jump" org-goto t])
20983 ("Edit Structure"
20984 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20985 "--"
20986 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20987 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20988 "--"
20989 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20990 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20991 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20992 "--"
20993 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20994 "--"
20995 ["Copy visible text" org-copy-visible t]
20996 "--"
20997 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20998 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20999 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21000 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21001 "--"
21002 ["Sort Region/Children" org-sort t]
21003 "--"
21004 ["Convert to odd levels" org-convert-to-odd-levels t]
21005 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21006 ("Editing"
21007 ["Emphasis..." org-emphasize t]
21008 ["Edit Source Example" org-edit-special t]
21009 "--"
21010 ["Footnote new/jump" org-footnote-action t]
21011 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21012 ("Archive"
21013 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21014 "--"
21015 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21016 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21017 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21019 "--"
21020 ("Hyperlinks"
21021 ["Store Link (Global)" org-store-link t]
21022 ["Find existing link to here" org-occur-link-in-agenda-files t]
21023 ["Insert Link" org-insert-link t]
21024 ["Follow Link" org-open-at-point t]
21025 "--"
21026 ["Next link" org-next-link t]
21027 ["Previous link" org-previous-link t]
21028 "--"
21029 ["Descriptive Links"
21030 org-toggle-link-display
21031 :style radio
21032 :selected org-descriptive-links
21034 ["Literal Links"
21035 org-toggle-link-display
21036 :style radio
21037 :selected (not org-descriptive-links)])
21038 "--"
21039 ("TODO Lists"
21040 ["TODO/DONE/-" org-todo t]
21041 ("Select keyword"
21042 ["Next keyword" org-shiftright (org-at-heading-p)]
21043 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21044 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21045 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21046 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21047 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21048 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21049 "--"
21050 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21051 :selected org-enforce-todo-dependencies :style toggle :active t]
21052 "Settings for tree at point"
21053 ["Do Children sequentially" org-toggle-ordered-property :style radio
21054 :selected (org-entry-get nil "ORDERED")
21055 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21056 ["Do Children parallel" org-toggle-ordered-property :style radio
21057 :selected (not (org-entry-get nil "ORDERED"))
21058 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21059 "--"
21060 ["Set Priority" org-priority t]
21061 ["Priority Up" org-shiftup t]
21062 ["Priority Down" org-shiftdown t]
21063 "--"
21064 ["Get news from all feeds" org-feed-update-all t]
21065 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21066 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21067 ("TAGS and Properties"
21068 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21069 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21070 "--"
21071 ["Set property" org-set-property (not (org-before-first-heading-p))]
21072 ["Column view of properties" org-columns t]
21073 ["Insert Column View DBlock" org-insert-columns-dblock t])
21074 ("Dates and Scheduling"
21075 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21076 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21077 ("Change Date"
21078 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21079 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21080 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21081 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21082 ["Compute Time Range" org-evaluate-time-range t]
21083 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21084 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21085 "--"
21086 ["Custom time format" org-toggle-time-stamp-overlays
21087 :style radio :selected org-display-custom-times]
21088 "--"
21089 ["Goto Calendar" org-goto-calendar t]
21090 ["Date from Calendar" org-date-from-calendar t]
21091 "--"
21092 ["Start/Restart Timer" org-timer-start t]
21093 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21094 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21095 ["Insert Timer String" org-timer t]
21096 ["Insert Timer Item" org-timer-item t])
21097 ("Logging work"
21098 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21099 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21100 ["Clock out" org-clock-out t]
21101 ["Clock cancel" org-clock-cancel t]
21102 "--"
21103 ["Mark as default task" org-clock-mark-default-task t]
21104 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21105 ["Goto running clock" org-clock-goto t]
21106 "--"
21107 ["Display times" org-clock-display t]
21108 ["Create clock table" org-clock-report t]
21109 "--"
21110 ["Record DONE time"
21111 (progn (setq org-log-done (not org-log-done))
21112 (message "Switching to %s will %s record a timestamp"
21113 (car org-done-keywords)
21114 (if org-log-done "automatically" "not")))
21115 :style toggle :selected org-log-done])
21116 "--"
21117 ["Agenda Command..." org-agenda t]
21118 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21119 ("File List for Agenda")
21120 ("Special views current file"
21121 ["TODO Tree" org-show-todo-tree t]
21122 ["Check Deadlines" org-check-deadlines t]
21123 ["Timeline" org-timeline t]
21124 ["Tags/Property tree" org-match-sparse-tree t])
21125 "--"
21126 ["Export/Publish..." org-export-dispatch t]
21127 ("LaTeX"
21128 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21129 :selected org-cdlatex-mode]
21130 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21131 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21132 ["Modify math symbol" org-cdlatex-math-modify
21133 (org-inside-LaTeX-fragment-p)]
21134 ["Insert citation" org-reftex-citation t]
21135 "--"
21136 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21137 "--"
21138 ("MobileOrg"
21139 ["Push Files and Views" org-mobile-push t]
21140 ["Get Captured and Flagged" org-mobile-pull t]
21141 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21142 "--"
21143 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21144 "--"
21145 ("Documentation"
21146 ["Show Version" org-version t]
21147 ["Info Documentation" org-info t])
21148 ("Customize"
21149 ["Browse Org Group" org-customize t]
21150 "--"
21151 ["Expand This Menu" org-create-customize-menu
21152 (fboundp 'customize-menu-create)])
21153 ["Send bug report" org-submit-bug-report t]
21154 "--"
21155 ("Refresh/Reload"
21156 ["Refresh setup current buffer" org-mode-restart t]
21157 ["Reload Org (after update)" org-reload t]
21158 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21161 (defun org-info (&optional node)
21162 "Read documentation for Org-mode in the info system.
21163 With optional NODE, go directly to that node."
21164 (interactive)
21165 (info (format "(org)%s" (or node ""))))
21167 ;;;###autoload
21168 (defun org-submit-bug-report ()
21169 "Submit a bug report on Org-mode via mail.
21171 Don't hesitate to report any problems or inaccurate documentation.
21173 If you don't have setup sending mail from (X)Emacs, please copy the
21174 output buffer into your mail program, as it gives us important
21175 information about your Org-mode version and configuration."
21176 (interactive)
21177 (require 'reporter)
21178 (org-load-modules-maybe)
21179 (org-require-autoloaded-modules)
21180 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21181 (reporter-submit-bug-report
21182 "emacs-orgmode@gnu.org"
21183 (org-version nil 'full)
21184 (let (list)
21185 (save-window-excursion
21186 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21187 (delete-other-windows)
21188 (erase-buffer)
21189 (insert "You are about to submit a bug report to the Org-mode mailing list.
21191 We would like to add your full Org-mode and Outline configuration to the
21192 bug report. This greatly simplifies the work of the maintainer and
21193 other experts on the mailing list.
21195 HOWEVER, some variables you have customized may contain private
21196 information. The names of customers, colleagues, or friends, might
21197 appear in the form of file names, tags, todo states, or search strings.
21198 If you answer yes to the prompt, you might want to check and remove
21199 such private information before sending the email.")
21200 (add-text-properties (point-min) (point-max) '(face org-warning))
21201 (when (yes-or-no-p "Include your Org-mode configuration ")
21202 (mapatoms
21203 (lambda (v)
21204 (and (boundp v)
21205 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21206 (or (and (symbol-value v)
21207 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21208 (and
21209 (get v 'custom-type) (get v 'standard-value)
21210 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21211 (push v list)))))
21212 (kill-buffer (get-buffer "*Warn about privacy*"))
21213 list))
21214 nil nil
21215 "Remember to cover the basics, that is, what you expected to happen and
21216 what in fact did happen. You don't know how to make a good report? See
21218 http://orgmode.org/manual/Feedback.html#Feedback
21220 Your bug report will be posted to the Org-mode mailing list.
21221 ------------------------------------------------------------------------")
21222 (save-excursion
21223 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21224 (replace-match "\\1Bug: \\3 [\\2]")))))
21227 (defun org-install-agenda-files-menu ()
21228 (let ((bl (buffer-list)))
21229 (save-excursion
21230 (while bl
21231 (set-buffer (pop bl))
21232 (if (derived-mode-p 'org-mode) (setq bl nil)))
21233 (when (derived-mode-p 'org-mode)
21234 (easy-menu-change
21235 '("Org") "File List for Agenda"
21236 (append
21237 (list
21238 ["Edit File List" (org-edit-agenda-file-list) t]
21239 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21240 ["Remove Current File from List" org-remove-file t]
21241 ["Cycle through agenda files" org-cycle-agenda-files t]
21242 ["Occur in all agenda files" org-occur-in-agenda-files t]
21243 "--")
21244 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21246 ;;;; Documentation
21248 (defun org-require-autoloaded-modules ()
21249 (interactive)
21250 (mapc 'require
21251 '(org-agenda org-archive org-attach org-clock org-colview org-id
21252 org-table org-timer)))
21254 ;;;###autoload
21255 (defun org-reload (&optional uncompiled)
21256 "Reload all org lisp files.
21257 With prefix arg UNCOMPILED, load the uncompiled versions."
21258 (interactive "P")
21259 (require 'loadhist)
21260 (let* ((org-dir (org-find-library-dir "org"))
21261 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21262 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21263 (remove-re (mapconcat 'identity
21264 (mapcar (lambda (f) (concat "^" f "$"))
21265 (list (if (featurep 'xemacs)
21266 "org-colview"
21267 "org-colview-xemacs")
21268 "org" "org-loaddefs" "org-version"))
21269 "\\|"))
21270 (feats (delete-dups
21271 (mapcar 'file-name-sans-extension
21272 (mapcar 'file-name-nondirectory
21273 (delq nil
21274 (mapcar 'feature-file
21275 features))))))
21276 (lfeat (append
21277 (sort
21278 (setq feats
21279 (delq nil (mapcar
21280 (lambda (f)
21281 (if (and (string-match feature-re f)
21282 (not (string-match remove-re f)))
21283 f nil))
21284 feats)))
21285 'string-lessp)
21286 (list "org-version" "org")))
21287 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21288 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21289 load-uncore load-misses)
21290 (setq load-misses
21291 (delq 't
21292 (mapcar (lambda (f)
21293 (or (org-load-noerror-mustsuffix (concat org-dir f))
21294 (and (string= org-dir contrib-dir)
21295 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21296 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21297 (add-to-list 'load-uncore f 'append)
21300 lfeat)))
21301 (if load-uncore
21302 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21303 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21304 (if load-misses
21305 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21306 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21307 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21309 ;;;###autoload
21310 (defun org-customize ()
21311 "Call the customize function with org as argument."
21312 (interactive)
21313 (org-load-modules-maybe)
21314 (org-require-autoloaded-modules)
21315 (customize-browse 'org))
21317 (defun org-create-customize-menu ()
21318 "Create a full customization menu for Org-mode, insert it into the menu."
21319 (interactive)
21320 (org-load-modules-maybe)
21321 (org-require-autoloaded-modules)
21322 (if (fboundp 'customize-menu-create)
21323 (progn
21324 (easy-menu-change
21325 '("Org") "Customize"
21326 `(["Browse Org group" org-customize t]
21327 "--"
21328 ,(customize-menu-create 'org)
21329 ["Set" Custom-set t]
21330 ["Save" Custom-save t]
21331 ["Reset to Current" Custom-reset-current t]
21332 ["Reset to Saved" Custom-reset-saved t]
21333 ["Reset to Standard Settings" Custom-reset-standard t]))
21334 (message "\"Org\"-menu now contains full customization menu"))
21335 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21337 ;;;; Miscellaneous stuff
21339 ;;; Generally useful functions
21341 (defun org-get-at-bol (property)
21342 "Get text property PROPERTY at beginning of line."
21343 (get-text-property (point-at-bol) property))
21345 (defun org-find-text-property-in-string (prop s)
21346 "Return the first non-nil value of property PROP in string S."
21347 (or (get-text-property 0 prop s)
21348 (get-text-property (or (next-single-property-change 0 prop s) 0)
21349 prop s)))
21351 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21352 "Display the given MESSAGE as a warning."
21353 (if (fboundp 'display-warning)
21354 (display-warning 'org message
21355 (if (featurep 'xemacs) 'warning :warning))
21356 (let ((buf (get-buffer-create "*Org warnings*")))
21357 (with-current-buffer buf
21358 (goto-char (point-max))
21359 (insert "Warning (Org): " message)
21360 (unless (bolp)
21361 (newline)))
21362 (display-buffer buf)
21363 (sit-for 0))))
21365 (defun org-eval (form)
21366 "Eval FORM and return result."
21367 (condition-case error
21368 (eval form)
21369 (error (format "%%![Error: %s]" error))))
21371 (defun org-in-clocktable-p ()
21372 "Check if the cursor is in a clocktable."
21373 (let ((pos (point)) start)
21374 (save-excursion
21375 (end-of-line 1)
21376 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21377 (setq start (match-beginning 0))
21378 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21379 (>= (match-end 0) pos)
21380 start))))
21382 (defun org-in-commented-line ()
21383 "Is point in a line starting with `#'?"
21384 (equal (char-after (point-at-bol)) ?#))
21386 (defun org-in-indented-comment-line ()
21387 "Is point in a line starting with `#' after some white space?"
21388 (save-excursion
21389 (save-match-data
21390 (goto-char (point-at-bol))
21391 (looking-at "[ \t]*#"))))
21393 (defun org-in-verbatim-emphasis ()
21394 (save-match-data
21395 (and (org-in-regexp org-emph-re 2)
21396 (>= (point) (match-beginning 3))
21397 (<= (point) (match-end 4))
21398 (member (match-string 3) '("=" "~")))))
21400 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21401 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21402 (if (and marker (marker-buffer marker)
21403 (buffer-live-p (marker-buffer marker)))
21404 (progn
21405 (org-pop-to-buffer-same-window (marker-buffer marker))
21406 (if (or (> marker (point-max)) (< marker (point-min)))
21407 (widen))
21408 (goto-char marker)
21409 (org-show-context 'org-goto))
21410 (if bookmark
21411 (bookmark-jump bookmark)
21412 (error "Cannot find location"))))
21414 (defun org-quote-csv-field (s)
21415 "Quote field for inclusion in CSV material."
21416 (if (string-match "[\",]" s)
21417 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21420 (defun org-force-self-insert (N)
21421 "Needed to enforce self-insert under remapping."
21422 (interactive "p")
21423 (self-insert-command N))
21425 (defun org-string-width (s)
21426 "Compute width of string, ignoring invisible characters.
21427 This ignores character with invisibility property `org-link', and also
21428 characters with property `org-cwidth', because these will become invisible
21429 upon the next fontification round."
21430 (let (b l)
21431 (when (or (eq t buffer-invisibility-spec)
21432 (assq 'org-link buffer-invisibility-spec))
21433 (while (setq b (text-property-any 0 (length s)
21434 'invisible 'org-link s))
21435 (setq s (concat (substring s 0 b)
21436 (substring s (or (next-single-property-change
21437 b 'invisible s) (length s)))))))
21438 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21439 (setq s (concat (substring s 0 b)
21440 (substring s (or (next-single-property-change
21441 b 'org-cwidth s) (length s))))))
21442 (setq l (string-width s) b -1)
21443 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21444 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21447 (defun org-shorten-string (s maxlength)
21448 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21449 If the string is shorter or has length MAXLENGTH, just return the
21450 original string. If it is longer, the functions finds a space in the
21451 string, breaks this string off at that locations and adds three dots
21452 as ellipsis. Including the ellipsis, the string will not be longer
21453 than MAXLENGTH. If finding a good breaking point in the string does
21454 not work, the string is just chopped off in the middle of a word
21455 if necessary."
21456 (if (<= (length s) maxlength)
21458 (let* ((n (max (- maxlength 4) 1))
21459 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21460 (if (string-match re s)
21461 (concat (match-string 1 s) "...")
21462 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21464 (defun org-get-indentation (&optional line)
21465 "Get the indentation of the current line, interpreting tabs.
21466 When LINE is given, assume it represents a line and compute its indentation."
21467 (if line
21468 (if (string-match "^ *" (org-remove-tabs line))
21469 (match-end 0))
21470 (save-excursion
21471 (beginning-of-line 1)
21472 (skip-chars-forward " \t")
21473 (current-column))))
21475 (defun org-get-string-indentation (s)
21476 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21477 (let ((n -1) (i 0) (w tab-width) c)
21478 (catch 'exit
21479 (while (< (setq n (1+ n)) (length s))
21480 (setq c (aref s n))
21481 (cond ((= c ?\ ) (setq i (1+ i)))
21482 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21483 (t (throw 'exit t)))))
21486 (defun org-remove-tabs (s &optional width)
21487 "Replace tabulators in S with spaces.
21488 Assumes that s is a single line, starting in column 0."
21489 (setq width (or width tab-width))
21490 (while (string-match "\t" s)
21491 (setq s (replace-match
21492 (make-string
21493 (- (* width (/ (+ (match-beginning 0) width) width))
21494 (match-beginning 0)) ?\ )
21495 t t s)))
21498 (defun org-fix-indentation (line ind)
21499 "Fix indentation in LINE.
21500 IND is a cons cell with target and minimum indentation.
21501 If the current indentation in LINE is smaller than the minimum,
21502 leave it alone. If it is larger than ind, set it to the target."
21503 (let* ((l (org-remove-tabs line))
21504 (i (org-get-indentation l))
21505 (i1 (car ind)) (i2 (cdr ind)))
21506 (if (>= i i2) (setq l (substring line i2)))
21507 (if (> i1 0)
21508 (concat (make-string i1 ?\ ) l)
21509 l)))
21511 (defun org-remove-indentation (code &optional n)
21512 "Remove the maximum common indentation from the lines in CODE.
21513 N may optionally be the number of spaces to remove."
21514 (with-temp-buffer
21515 (insert code)
21516 (org-do-remove-indentation n)
21517 (buffer-string)))
21519 (defun org-do-remove-indentation (&optional n)
21520 "Remove the maximum common indentation from the buffer."
21521 (untabify (point-min) (point-max))
21522 (let ((min 10000) re)
21523 (if n
21524 (setq min n)
21525 (goto-char (point-min))
21526 (while (re-search-forward "^ *[^ \n]" nil t)
21527 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21528 (unless (or (= min 0) (= min 10000))
21529 (setq re (format "^ \\{%d\\}" min))
21530 (goto-char (point-min))
21531 (while (re-search-forward re nil t)
21532 (replace-match "")
21533 (end-of-line 1))
21534 min)))
21536 (defun org-fill-template (template alist)
21537 "Find each %key of ALIST in TEMPLATE and replace it."
21538 (let ((case-fold-search nil)
21539 entry key value)
21540 (setq alist (sort (copy-sequence alist)
21541 (lambda (a b) (< (length (car a)) (length (car b))))))
21542 (while (setq entry (pop alist))
21543 (setq template
21544 (replace-regexp-in-string
21545 (concat "%" (regexp-quote (car entry)))
21546 (or (cdr entry) "") template t t)))
21547 template))
21549 (defun org-base-buffer (buffer)
21550 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21551 (if (not buffer)
21552 buffer
21553 (or (buffer-base-buffer buffer)
21554 buffer)))
21556 (defun org-trim (s)
21557 "Remove whitespace at beginning and end of string."
21558 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21559 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21562 (defun org-wrap (string &optional width lines)
21563 "Wrap string to either a number of lines, or a width in characters.
21564 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21565 that costs. If there is a word longer than WIDTH, the text is actually
21566 wrapped to the length of that word.
21567 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21568 many lines, whatever width that takes.
21569 The return value is a list of lines, without newlines at the end."
21570 (let* ((words (org-split-string string "[ \t\n]+"))
21571 (maxword (apply 'max (mapcar 'org-string-width words)))
21572 w ll)
21573 (cond (width
21574 (org-do-wrap words (max maxword width)))
21575 (lines
21576 (setq w maxword)
21577 (setq ll (org-do-wrap words maxword))
21578 (if (<= (length ll) lines)
21580 (setq ll words)
21581 (while (> (length ll) lines)
21582 (setq w (1+ w))
21583 (setq ll (org-do-wrap words w)))
21584 ll))
21585 (t (error "Cannot wrap this")))))
21587 (defun org-do-wrap (words width)
21588 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21589 (let (lines line)
21590 (while words
21591 (setq line (pop words))
21592 (while (and words (< (+ (length line) (length (car words))) width))
21593 (setq line (concat line " " (pop words))))
21594 (setq lines (push line lines)))
21595 (nreverse lines)))
21597 (defun org-split-string (string &optional separators)
21598 "Splits STRING into substrings at SEPARATORS.
21599 No empty strings are returned if there are matches at the beginning
21600 and end of string."
21601 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21602 (start 0)
21603 notfirst
21604 (list nil))
21605 (while (and (string-match rexp string
21606 (if (and notfirst
21607 (= start (match-beginning 0))
21608 (< start (length string)))
21609 (1+ start) start))
21610 (< (match-beginning 0) (length string)))
21611 (setq notfirst t)
21612 (or (eq (match-beginning 0) 0)
21613 (and (eq (match-beginning 0) (match-end 0))
21614 (eq (match-beginning 0) start))
21615 (setq list
21616 (cons (substring string start (match-beginning 0))
21617 list)))
21618 (setq start (match-end 0)))
21619 (or (eq start (length string))
21620 (setq list
21621 (cons (substring string start)
21622 list)))
21623 (nreverse list)))
21625 (defun org-quote-vert (s)
21626 "Replace \"|\" with \"\\vert\"."
21627 (while (string-match "|" s)
21628 (setq s (replace-match "\\vert" t t s)))
21631 (defun org-uuidgen-p (s)
21632 "Is S an ID created by UUIDGEN?"
21633 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21635 (defun org-in-src-block-p (&optional inside)
21636 "Whether point is in a code source block.
21637 When INSIDE is non-nil, don't consider we are within a src block
21638 when point is at #+BEGIN_SRC or #+END_SRC."
21639 (let ((case-fold-search t) ov)
21640 (or (and (setq ov (overlays-at (point)))
21641 (memq 'org-block-background
21642 (overlay-properties (car ov))))
21643 (and (not inside)
21644 (save-match-data
21645 (save-excursion
21646 (beginning-of-line)
21647 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21649 (defun org-context ()
21650 "Return a list of contexts of the current cursor position.
21651 If several contexts apply, all are returned.
21652 Each context entry is a list with a symbol naming the context, and
21653 two positions indicating start and end of the context. Possible
21654 contexts are:
21656 :headline anywhere in a headline
21657 :headline-stars on the leading stars in a headline
21658 :todo-keyword on a TODO keyword (including DONE) in a headline
21659 :tags on the TAGS in a headline
21660 :priority on the priority cookie in a headline
21661 :item on the first line of a plain list item
21662 :item-bullet on the bullet/number of a plain list item
21663 :checkbox on the checkbox in a plain list item
21664 :table in an org-mode table
21665 :table-special on a special filed in a table
21666 :table-table in a table.el table
21667 :clocktable in a clocktable
21668 :src-block in a source block
21669 :link on a hyperlink
21670 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21671 :target on a <<target>>
21672 :radio-target on a <<<radio-target>>>
21673 :latex-fragment on a LaTeX fragment
21674 :latex-preview on a LaTeX fragment with overlaid preview image
21676 This function expects the position to be visible because it uses font-lock
21677 faces as a help to recognize the following contexts: :table-special, :link,
21678 and :keyword."
21679 (let* ((f (get-text-property (point) 'face))
21680 (faces (if (listp f) f (list f)))
21681 (case-fold-search t)
21682 (p (point)) clist o)
21683 ;; First the large context
21684 (cond
21685 ((org-at-heading-p t)
21686 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21687 (when (progn
21688 (beginning-of-line 1)
21689 (looking-at org-todo-line-tags-regexp))
21690 (push (org-point-in-group p 1 :headline-stars) clist)
21691 (push (org-point-in-group p 2 :todo-keyword) clist)
21692 (push (org-point-in-group p 4 :tags) clist))
21693 (goto-char p)
21694 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21695 (if (looking-at "\\[#[A-Z0-9]\\]")
21696 (push (org-point-in-group p 0 :priority) clist)))
21698 ((org-at-item-p)
21699 (push (org-point-in-group p 2 :item-bullet) clist)
21700 (push (list :item (point-at-bol)
21701 (save-excursion (org-end-of-item) (point)))
21702 clist)
21703 (and (org-at-item-checkbox-p)
21704 (push (org-point-in-group p 0 :checkbox) clist)))
21706 ((org-at-table-p)
21707 (push (list :table (org-table-begin) (org-table-end)) clist)
21708 (if (memq 'org-formula faces)
21709 (push (list :table-special
21710 (previous-single-property-change p 'face)
21711 (next-single-property-change p 'face)) clist)))
21712 ((org-at-table-p 'any)
21713 (push (list :table-table) clist)))
21714 (goto-char p)
21716 (let ((case-fold-search t))
21717 ;; New the "medium" contexts: clocktables, source blocks
21718 (cond ((org-in-clocktable-p)
21719 (push (list :clocktable
21720 (and (or (looking-at "#\\+BEGIN: clocktable")
21721 (search-backward "#+BEGIN: clocktable" nil t))
21722 (match-beginning 0))
21723 (and (re-search-forward "#\\+END:?" nil t)
21724 (match-end 0))) clist))
21725 ((org-in-src-block-p)
21726 (push (list :src-block
21727 (and (or (looking-at "#\\+BEGIN_SRC")
21728 (search-backward "#+BEGIN_SRC" nil t))
21729 (match-beginning 0))
21730 (and (search-forward "#+END_SRC" nil t)
21731 (match-beginning 0))) clist))))
21732 (goto-char p)
21734 ;; Now the small context
21735 (cond
21736 ((org-at-timestamp-p)
21737 (push (org-point-in-group p 0 :timestamp) clist))
21738 ((memq 'org-link faces)
21739 (push (list :link
21740 (previous-single-property-change p 'face)
21741 (next-single-property-change p 'face)) clist))
21742 ((memq 'org-special-keyword faces)
21743 (push (list :keyword
21744 (previous-single-property-change p 'face)
21745 (next-single-property-change p 'face)) clist))
21746 ((org-at-target-p)
21747 (push (org-point-in-group p 0 :target) clist)
21748 (goto-char (1- (match-beginning 0)))
21749 (if (looking-at org-radio-target-regexp)
21750 (push (org-point-in-group p 0 :radio-target) clist))
21751 (goto-char p))
21752 ((setq o (car (delq nil
21753 (mapcar
21754 (lambda (x)
21755 (if (memq x org-latex-fragment-image-overlays) x))
21756 (overlays-at (point))))))
21757 (push (list :latex-fragment
21758 (overlay-start o) (overlay-end o)) clist)
21759 (push (list :latex-preview
21760 (overlay-start o) (overlay-end o)) clist))
21761 ((org-inside-LaTeX-fragment-p)
21762 ;; FIXME: positions wrong.
21763 (push (list :latex-fragment (point) (point)) clist)))
21765 (setq clist (nreverse (delq nil clist)))
21766 clist))
21768 ;; FIXME: Compare with at-regexp-p Do we need both?
21769 (defun org-in-regexp (re &optional nlines visually)
21770 "Check if point is inside a match of regexp.
21771 Normally only the current line is checked, but you can include NLINES extra
21772 lines both before and after point into the search.
21773 If VISUALLY is set, require that the cursor is not after the match but
21774 really on, so that the block visually is on the match."
21775 (catch 'exit
21776 (let ((pos (point))
21777 (eol (point-at-eol (+ 1 (or nlines 0))))
21778 (inc (if visually 1 0)))
21779 (save-excursion
21780 (beginning-of-line (- 1 (or nlines 0)))
21781 (while (re-search-forward re eol t)
21782 (if (and (<= (match-beginning 0) pos)
21783 (>= (+ inc (match-end 0)) pos))
21784 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21786 (defun org-at-regexp-p (regexp)
21787 "Is point inside a match of REGEXP in the current line?"
21788 (catch 'exit
21789 (save-excursion
21790 (let ((pos (point)) (end (point-at-eol)))
21791 (beginning-of-line 1)
21792 (while (re-search-forward regexp end t)
21793 (if (and (<= (match-beginning 0) pos)
21794 (>= (match-end 0) pos))
21795 (throw 'exit t)))
21796 nil))))
21798 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21799 "Non-nil when point is between matches of START-RE and END-RE.
21801 Also return a non-nil value when point is on one of the matches.
21803 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21804 buffer positions. Default values are the positions of headlines
21805 surrounding the point.
21807 The functions returns a cons cell whose car (resp. cdr) is the
21808 position before START-RE (resp. after END-RE)."
21809 (save-match-data
21810 (let ((pos (point))
21811 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21812 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21813 beg end)
21814 (save-excursion
21815 ;; Point is on a block when on START-RE or if START-RE can be
21816 ;; found before it...
21817 (and (or (org-at-regexp-p start-re)
21818 (re-search-backward start-re limit-up t))
21819 (setq beg (match-beginning 0))
21820 ;; ... and END-RE after it...
21821 (goto-char (match-end 0))
21822 (re-search-forward end-re limit-down t)
21823 (> (setq end (match-end 0)) pos)
21824 ;; ... without another START-RE in-between.
21825 (goto-char (match-beginning 0))
21826 (not (re-search-backward start-re (1+ beg) t))
21827 ;; Return value.
21828 (cons beg end))))))
21830 (defun org-in-block-p (names)
21831 "Non-nil when point belongs to a block whose name belongs to NAMES.
21833 NAMES is a list of strings containing names of blocks.
21835 Return first block name matched, or nil. Beware that in case of
21836 nested blocks, the returned name may not belong to the closest
21837 block from point."
21838 (save-match-data
21839 (catch 'exit
21840 (let ((case-fold-search t)
21841 (lim-up (save-excursion (outline-previous-heading)))
21842 (lim-down (save-excursion (outline-next-heading))))
21843 (mapc (lambda (name)
21844 (let ((n (regexp-quote name)))
21845 (when (org-between-regexps-p
21846 (concat "^[ \t]*#\\+begin_" n)
21847 (concat "^[ \t]*#\\+end_" n)
21848 lim-up lim-down)
21849 (throw 'exit n))))
21850 names))
21851 nil)))
21853 (defun org-in-drawer-p ()
21854 "Non-nil if point is within a drawer.
21855 If point is within a drawer, return it, as parsed data."
21856 (let ((element (save-match-data (org-element-at-point))))
21857 (while (and element (not (memq (org-element-type element)
21858 '(drawer property-drawer))))
21859 (setq element (org-element-property :parent element)))
21860 element))
21862 (defun org-occur-in-agenda-files (regexp &optional nlines)
21863 "Call `multi-occur' with buffers for all agenda files."
21864 (interactive "sOrg-files matching: \np")
21865 (let* ((files (org-agenda-files))
21866 (tnames (mapcar 'file-truename files))
21867 (extra org-agenda-text-search-extra-files)
21869 (when (eq (car extra) 'agenda-archives)
21870 (setq extra (cdr extra))
21871 (setq files (org-add-archive-files files)))
21872 (while (setq f (pop extra))
21873 (unless (member (file-truename f) tnames)
21874 (add-to-list 'files f 'append)
21875 (add-to-list 'tnames (file-truename f) 'append)))
21876 (multi-occur
21877 (mapcar (lambda (x)
21878 (with-current-buffer
21879 (or (get-file-buffer x) (find-file-noselect x))
21880 (widen)
21881 (current-buffer)))
21882 files)
21883 regexp)))
21885 (if (boundp 'occur-mode-find-occurrence-hook)
21886 ;; Emacs 23
21887 (add-hook 'occur-mode-find-occurrence-hook
21888 (lambda ()
21889 (when (derived-mode-p 'org-mode)
21890 (org-reveal))))
21891 ;; Emacs 22
21892 (defadvice occur-mode-goto-occurrence
21893 (after org-occur-reveal activate)
21894 (and (derived-mode-p 'org-mode) (org-reveal)))
21895 (defadvice occur-mode-goto-occurrence-other-window
21896 (after org-occur-reveal activate)
21897 (and (derived-mode-p 'org-mode) (org-reveal)))
21898 (defadvice occur-mode-display-occurrence
21899 (after org-occur-reveal activate)
21900 (when (derived-mode-p 'org-mode)
21901 (let ((pos (occur-mode-find-occurrence)))
21902 (with-current-buffer (marker-buffer pos)
21903 (save-excursion
21904 (goto-char pos)
21905 (org-reveal)))))))
21907 (defun org-occur-link-in-agenda-files ()
21908 "Create a link and search for it in the agendas.
21909 The link is not stored in `org-stored-links', it is just created
21910 for the search purpose."
21911 (interactive)
21912 (let ((link (condition-case nil
21913 (org-store-link nil)
21914 (error "Unable to create a link to here"))))
21915 (org-occur-in-agenda-files (regexp-quote link))))
21917 (defun org-reverse-string (string)
21918 "Return the reverse of STRING."
21919 (apply 'string (reverse (string-to-list string))))
21921 (defun org-uniquify-alist (alist)
21922 "Merge elements of ALIST with the same key.
21924 For example, in this alist:
21926 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21927 => '((a 1 3) (b 2))
21929 merge (a 1) and (a 3) into (a 1 3).
21931 The function returns the new ALIST."
21932 (let (rtn)
21933 (mapc
21934 (lambda (e)
21935 (let (n)
21936 (if (not (assoc (car e) rtn))
21937 (push e rtn)
21938 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21939 (setq rtn (assq-delete-all (car e) rtn))
21940 (push n rtn))))
21941 alist)
21942 rtn))
21944 (defun org-delete-all (elts list)
21945 "Remove all elements in ELTS from LIST."
21946 (while elts
21947 (setq list (delete (pop elts) list)))
21948 list)
21950 (defun org-count (cl-item cl-seq)
21951 "Count the number of occurrences of ITEM in SEQ.
21952 Taken from `count' in cl-seq.el with all keyword arguments removed."
21953 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21954 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21955 (while (< cl-start cl-end)
21956 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21957 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21958 (setq cl-start (1+ cl-start)))
21959 cl-count))
21961 (defun org-remove-if (predicate seq)
21962 "Remove everything from SEQ that fulfills PREDICATE."
21963 (let (res e)
21964 (while seq
21965 (setq e (pop seq))
21966 (if (not (funcall predicate e)) (push e res)))
21967 (nreverse res)))
21969 (defun org-remove-if-not (predicate seq)
21970 "Remove everything from SEQ that does not fulfill PREDICATE."
21971 (let (res e)
21972 (while seq
21973 (setq e (pop seq))
21974 (if (funcall predicate e) (push e res)))
21975 (nreverse res)))
21977 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21978 "Reduce two-argument FUNCTION across SEQ.
21979 Taken from `reduce' in cl-seq.el with all keyword arguments but
21980 \":initial-value\" removed."
21981 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21982 (cadr (memq :initial-value cl-keys)))
21983 (cl-seq (pop cl-seq))
21984 (t (funcall cl-func)))))
21985 (while cl-seq
21986 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21987 cl-accum))
21989 (defun org-every (pred seq)
21990 "Return true if PREDICATE is true of every element of SEQ.
21991 Adapted from `every' in cl.el."
21992 (catch 'org-every
21993 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21996 (defun org-some (pred seq)
21997 "Return true if PREDICATE is true of any element of SEQ.
21998 Adapted from `some' in cl.el."
21999 (catch 'org-some
22000 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22001 nil))
22003 (defun org-back-over-empty-lines ()
22004 "Move backwards over whitespace, to the beginning of the first empty line.
22005 Returns the number of empty lines passed."
22006 (let ((pos (point)))
22007 (if (cdr (assoc 'heading org-blank-before-new-entry))
22008 (skip-chars-backward " \t\n\r")
22009 (unless (eobp)
22010 (forward-line -1)))
22011 (beginning-of-line 2)
22012 (goto-char (min (point) pos))
22013 (count-lines (point) pos)))
22015 (defun org-skip-whitespace ()
22016 (skip-chars-forward " \t\n\r"))
22018 (defun org-point-in-group (point group &optional context)
22019 "Check if POINT is in match-group GROUP.
22020 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22021 match. If the match group does not exist or point is not inside it,
22022 return nil."
22023 (and (match-beginning group)
22024 (>= point (match-beginning group))
22025 (<= point (match-end group))
22026 (if context
22027 (list context (match-beginning group) (match-end group))
22028 t)))
22030 (defun org-switch-to-buffer-other-window (&rest args)
22031 "Switch to buffer in a second window on the current frame.
22032 In particular, do not allow pop-up frames.
22033 Returns the newly created buffer."
22034 (org-no-popups
22035 (apply 'switch-to-buffer-other-window args)))
22037 (defun org-combine-plists (&rest plists)
22038 "Create a single property list from all plists in PLISTS.
22039 The process starts by copying the first list, and then setting properties
22040 from the other lists. Settings in the last list are the most significant
22041 ones and overrule settings in the other lists."
22042 (let ((rtn (copy-sequence (pop plists)))
22043 p v ls)
22044 (while plists
22045 (setq ls (pop plists))
22046 (while ls
22047 (setq p (pop ls) v (pop ls))
22048 (setq rtn (plist-put rtn p v))))
22049 rtn))
22051 (defun org-replace-escapes (string table)
22052 "Replace %-escapes in STRING with values in TABLE.
22053 TABLE is an association list with keys like \"%a\" and string values.
22054 The sequences in STRING may contain normal field width and padding information,
22055 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22056 so values can contain further %-escapes if they are define later in TABLE."
22057 (let ((tbl (copy-alist table))
22058 (case-fold-search nil)
22059 (pchg 0)
22060 e re rpl)
22061 (while (setq e (pop tbl))
22062 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22063 (when (and (cdr e) (string-match re (cdr e)))
22064 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22065 (safe "SREF"))
22066 (add-text-properties 0 3 (list 'sref sref) safe)
22067 (setcdr e (replace-match safe t t (cdr e)))))
22068 (while (string-match re string)
22069 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22070 (cdr e)))
22071 (setq string (replace-match rpl t t string))))
22072 (while (setq pchg (next-property-change pchg string))
22073 (let ((sref (get-text-property pchg 'sref string)))
22074 (when (and sref (string-match "SREF" string pchg))
22075 (setq string (replace-match sref t t string)))))
22076 string))
22078 (defun org-sublist (list start end)
22079 "Return a section of LIST, from START to END.
22080 Counting starts at 1."
22081 (let (rtn (c start))
22082 (setq list (nthcdr (1- start) list))
22083 (while (and list (<= c end))
22084 (push (pop list) rtn)
22085 (setq c (1+ c)))
22086 (nreverse rtn)))
22088 (defun org-find-base-buffer-visiting (file)
22089 "Like `find-buffer-visiting' but always return the base buffer and
22090 not an indirect buffer."
22091 (let ((buf (or (get-file-buffer file)
22092 (find-buffer-visiting file))))
22093 (if buf
22094 (or (buffer-base-buffer buf) buf)
22095 nil)))
22097 (defun org-image-file-name-regexp (&optional extensions)
22098 "Return regexp matching the file names of images.
22099 If EXTENSIONS is given, only match these."
22100 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22101 (image-file-name-regexp)
22102 (let ((image-file-name-extensions
22103 (or extensions
22104 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22105 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22106 (concat "\\."
22107 (regexp-opt (nconc (mapcar 'upcase
22108 image-file-name-extensions)
22109 image-file-name-extensions)
22111 "\\'"))))
22113 (defun org-file-image-p (file &optional extensions)
22114 "Return non-nil if FILE is an image."
22115 (save-match-data
22116 (string-match (org-image-file-name-regexp extensions) file)))
22118 (defun org-get-cursor-date (&optional with-time)
22119 "Return the date at cursor in as a time.
22120 This works in the calendar and in the agenda, anywhere else it just
22121 returns the current time.
22122 If WITH-TIME is non-nil, returns the time of the event at point (in
22123 the agenda) or the current time of the day."
22124 (let (date day defd tp tm hod mod)
22125 (when with-time
22126 (setq tp (get-text-property (point) 'time))
22127 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22128 (setq hod (string-to-number (match-string 1 tp))
22129 mod (string-to-number (match-string 2 tp))))
22130 (or tp (setq hod (nth 2 (decode-time (current-time)))
22131 mod (nth 1 (decode-time (current-time))))))
22132 (cond
22133 ((eq major-mode 'calendar-mode)
22134 (setq date (calendar-cursor-to-date)
22135 defd (encode-time 0 (or mod 0) (or hod 0)
22136 (nth 1 date) (nth 0 date) (nth 2 date))))
22137 ((eq major-mode 'org-agenda-mode)
22138 (setq day (get-text-property (point) 'day))
22139 (if day
22140 (setq date (calendar-gregorian-from-absolute day)
22141 defd (encode-time 0 (or mod 0) (or hod 0)
22142 (nth 1 date) (nth 0 date) (nth 2 date))))))
22143 (or defd (current-time))))
22145 (defun org-mark-subtree (&optional up)
22146 "Mark the current subtree.
22147 This puts point at the start of the current subtree, and mark at
22148 the end. If a numeric prefix UP is given, move up into the
22149 hierarchy of headlines by UP levels before marking the subtree."
22150 (interactive "P")
22151 (org-with-limited-levels
22152 (cond ((org-at-heading-p) (beginning-of-line))
22153 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22154 (t (outline-previous-visible-heading 1))))
22155 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22156 (if (org-called-interactively-p 'any)
22157 (call-interactively 'org-mark-element)
22158 (org-mark-element)))
22161 ;;; Indentation
22163 (defun org-indent-line ()
22164 "Indent line depending on context."
22165 (interactive)
22166 (let* ((pos (point))
22167 (itemp (org-at-item-p))
22168 (case-fold-search t)
22169 (org-drawer-regexp (or org-drawer-regexp "\000"))
22170 (inline-task-p (and (featurep 'org-inlinetask)
22171 (org-inlinetask-in-task-p)))
22172 (inline-re (and inline-task-p
22173 (org-inlinetask-outline-regexp)))
22174 column)
22175 (if (and orgstruct-is-++ (eq pos (point)))
22176 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22177 (indent-according-to-mode))
22178 (beginning-of-line 1)
22179 (cond
22180 ;; Headings
22181 ((looking-at org-outline-regexp) (setq column 0))
22182 ;; Footnote definition
22183 ((looking-at org-footnote-definition-re) (setq column 0))
22184 ;; Literal examples
22185 ((looking-at "[ \t]*:\\( \\|$\\)")
22186 (setq column (org-get-indentation))) ; do nothing
22187 ;; Lists
22188 ((ignore-errors (goto-char (org-in-item-p)))
22189 (setq column (if itemp
22190 (org-get-indentation)
22191 (org-list-item-body-column (point))))
22192 (goto-char pos))
22193 ;; Drawers
22194 ((and (looking-at "[ \t]*:END:")
22195 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22196 (save-excursion
22197 (goto-char (1- (match-beginning 1)))
22198 (setq column (current-column))))
22199 ;; Special blocks
22200 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22201 (save-excursion
22202 (re-search-backward
22203 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22204 (setq column (org-get-indentation (match-string 0))))
22205 ((and (not (looking-at "[ \t]*#\\+begin_"))
22206 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22207 (save-excursion
22208 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22209 (setq column
22210 (cond ((equal (downcase (match-string 1)) "src")
22211 ;; src blocks: let `org-edit-src-exit' handle them
22212 (org-get-indentation))
22213 ((equal (downcase (match-string 1)) "example")
22214 (max (org-get-indentation)
22215 (org-get-indentation (match-string 0))))
22217 (org-get-indentation (match-string 0))))))
22218 ;; This line has nothing special, look at the previous relevant
22219 ;; line to compute indentation
22221 (beginning-of-line 0)
22222 (while (and (not (bobp))
22223 (not (looking-at org-table-line-regexp))
22224 (not (looking-at org-drawer-regexp))
22225 ;; When point started in an inline task, do not move
22226 ;; above task starting line.
22227 (not (and inline-task-p (looking-at inline-re)))
22228 ;; Skip drawers, blocks, empty lines, verbatim,
22229 ;; comments, tables, footnotes definitions, lists,
22230 ;; inline tasks.
22231 (or (and (looking-at "[ \t]*:END:")
22232 (re-search-backward org-drawer-regexp nil t))
22233 (and (looking-at "[ \t]*#\\+end_")
22234 (re-search-backward "[ \t]*#\\+begin_"nil t))
22235 (looking-at "[ \t]*[\n:#|]")
22236 (looking-at org-footnote-definition-re)
22237 (and (not inline-task-p)
22238 (featurep 'org-inlinetask)
22239 (org-inlinetask-in-task-p)
22240 (or (org-inlinetask-goto-beginning) t))))
22241 (beginning-of-line 0))
22242 (cond
22243 ;; There was a list item above.
22244 ((ignore-errors (goto-char (org-in-item-p)))
22245 (goto-char (org-list-get-top-point (org-list-struct)))
22246 (setq column (org-get-indentation)))
22247 ;; There was an heading above.
22248 ((looking-at "\\*+[ \t]+")
22249 (if (not org-adapt-indentation)
22250 (setq column 0)
22251 (goto-char (match-end 0))
22252 (setq column (current-column))))
22253 ;; A drawer had started and is unfinished
22254 ((looking-at org-drawer-regexp)
22255 (goto-char (1- (match-beginning 1)))
22256 (setq column (current-column)))
22257 ;; Else, nothing noticeable found: get indentation and go on.
22258 (t (setq column (org-get-indentation))))))
22259 ;; Now apply indentation and move cursor accordingly
22260 (goto-char pos)
22261 (if (<= (current-column) (current-indentation))
22262 (org-indent-line-to column)
22263 (save-excursion (org-indent-line-to column)))
22264 ;; Special polishing for properties, see `org-property-format'
22265 (setq column (current-column))
22266 (beginning-of-line 1)
22267 (if (looking-at org-property-re)
22268 (replace-match (concat (match-string 4)
22269 (format org-property-format
22270 (match-string 1) (match-string 3)))
22271 t t))
22272 (org-move-to-column column))))
22274 (defun org-indent-drawer ()
22275 "Indent the drawer at point."
22276 (interactive)
22277 (let ((p (point))
22278 (e (and (save-excursion (re-search-forward ":END:" nil t))
22279 (match-end 0)))
22280 (folded
22281 (save-excursion
22282 (end-of-line)
22283 (when (overlays-at (point))
22284 (member 'invisible (overlay-properties
22285 (car (overlays-at (point)))))))))
22286 (when folded (org-cycle))
22287 (indent-for-tab-command)
22288 (while (and (move-beginning-of-line 2) (< (point) e))
22289 (indent-for-tab-command))
22290 (goto-char p)
22291 (when folded (org-cycle)))
22292 (message "Drawer at point indented"))
22294 (defun org-indent-block ()
22295 "Indent the block at point."
22296 (interactive)
22297 (let ((p (point))
22298 (case-fold-search t)
22299 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22300 (match-end 0)))
22301 (folded
22302 (save-excursion
22303 (end-of-line)
22304 (when (overlays-at (point))
22305 (member 'invisible (overlay-properties
22306 (car (overlays-at (point)))))))))
22307 (when folded (org-cycle))
22308 (indent-for-tab-command)
22309 (while (and (move-beginning-of-line 2) (< (point) e))
22310 (indent-for-tab-command))
22311 (goto-char p)
22312 (when folded (org-cycle)))
22313 (message "Block at point indented"))
22315 (defun org-indent-region (start end)
22316 "Indent region."
22317 (interactive "r")
22318 (save-excursion
22319 (let ((line-end (org-current-line end)))
22320 (goto-char start)
22321 (while (< (org-current-line) line-end)
22322 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22323 (t (call-interactively 'org-indent-line)))
22324 (move-beginning-of-line 2)))))
22327 ;;; Filling
22329 ;; We use our own fill-paragraph and auto-fill functions.
22331 ;; `org-fill-paragraph' relies on adaptive filling and context
22332 ;; checking. Appropriate `fill-prefix' is computed with
22333 ;; `org-adaptive-fill-function'.
22335 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22336 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22337 ;; `org-adaptive-fill-function' value. Internally,
22338 ;; `org-comment-line-break-function' breaks the line.
22340 ;; `org-setup-filling' installs filling and auto-filling related
22341 ;; variables during `org-mode' initialization.
22343 (defvar org-element-paragraph-separate) ; org-element.el
22344 (defun org-setup-filling ()
22345 (require 'org-element)
22346 ;; Prevent auto-fill from inserting unwanted new items.
22347 (when (boundp 'fill-nobreak-predicate)
22348 (org-set-local
22349 'fill-nobreak-predicate
22350 (org-uniquify
22351 (append fill-nobreak-predicate
22352 '(org-fill-line-break-nobreak-p
22353 org-fill-paragraph-with-timestamp-nobreak-p)))))
22354 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22355 (org-set-local 'paragraph-start paragraph-ending)
22356 (org-set-local 'paragraph-separate paragraph-ending))
22357 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22358 (org-set-local 'auto-fill-inhibit-regexp nil)
22359 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22360 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22361 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22363 (defun org-fill-line-break-nobreak-p ()
22364 "Non-nil when a new line at point would create an Org line break."
22365 (save-excursion
22366 (skip-chars-backward "[ \t]")
22367 (skip-chars-backward "\\\\")
22368 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22370 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22371 "Non-nil when a new line at point would split a timestamp."
22372 (and (org-at-timestamp-p t)
22373 (not (looking-at org-ts-regexp-both))))
22375 (declare-function message-in-body-p "message" ())
22376 (defvar orgtbl-line-start-regexp) ; From org-table.el
22377 (defun org-adaptive-fill-function ()
22378 "Compute a fill prefix for the current line.
22379 Return fill prefix, as a string, or nil if current line isn't
22380 meant to be filled. For convenience, if `adaptive-fill-regexp'
22381 matches in paragraphs or comments, use it."
22382 (catch 'exit
22383 (when (derived-mode-p 'message-mode)
22384 (save-excursion
22385 (beginning-of-line)
22386 (cond ((or (not (message-in-body-p))
22387 (looking-at orgtbl-line-start-regexp))
22388 (throw 'exit nil))
22389 ((looking-at message-cite-prefix-regexp)
22390 (throw 'exit (match-string-no-properties 0)))
22391 ((looking-at org-outline-regexp)
22392 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22393 (org-with-wide-buffer
22394 (let* ((p (line-beginning-position))
22395 (element (save-excursion
22396 (beginning-of-line)
22397 (or (ignore-errors (org-element-at-point))
22398 (user-error "An element cannot be parsed line %d"
22399 (line-number-at-pos (point))))))
22400 (type (org-element-type element))
22401 (post-affiliated (org-element-property :post-affiliated element)))
22402 (unless (and post-affiliated (< p post-affiliated))
22403 (case type
22404 (comment
22405 (save-excursion
22406 (beginning-of-line)
22407 (looking-at "[ \t]*")
22408 (concat (match-string 0) "# ")))
22409 (footnote-definition "")
22410 ((item plain-list)
22411 (make-string (org-list-item-body-column
22412 (or post-affiliated
22413 (org-element-property :begin element)))
22414 ? ))
22415 (paragraph
22416 ;; Fill prefix is usually the same as the current line,
22417 ;; unless the paragraph is at the beginning of an item.
22418 (let ((parent (org-element-property :parent element)))
22419 (save-excursion
22420 (beginning-of-line)
22421 (cond ((eq (org-element-type parent) 'item)
22422 (make-string (org-list-item-body-column
22423 (org-element-property :begin parent))
22424 ? ))
22425 ((and adaptive-fill-regexp
22426 ;; Locally disable
22427 ;; `adaptive-fill-function' to let
22428 ;; `fill-context-prefix' handle
22429 ;; `adaptive-fill-regexp' variable.
22430 (let (adaptive-fill-function)
22431 (fill-context-prefix
22432 post-affiliated
22433 (org-element-property :end element)))))
22434 ((looking-at "[ \t]+") (match-string 0))
22435 (t "")))))
22436 (comment-block
22437 ;; Only fill contents if P is within block boundaries.
22438 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22439 (forward-line)
22440 (point)))
22441 (cend (save-excursion
22442 (goto-char (org-element-property :end element))
22443 (skip-chars-backward " \r\t\n")
22444 (line-beginning-position))))
22445 (when (and (>= p cbeg) (< p cend))
22446 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22447 (match-string 0)
22448 ""))))))))))
22450 (declare-function message-goto-body "message" ())
22451 (defvar message-cite-prefix-regexp) ; From message.el
22452 (defun org-fill-paragraph (&optional justify)
22453 "Fill element at point, when applicable.
22455 This function only applies to comment blocks, comments, example
22456 blocks and paragraphs. Also, as a special case, re-align table
22457 when point is at one.
22459 If JUSTIFY is non-nil (interactively, with prefix argument),
22460 justify as well. If `sentence-end-double-space' is non-nil, then
22461 period followed by one space does not end a sentence, so don't
22462 break a line there. The variable `fill-column' controls the
22463 width for filling.
22465 For convenience, when point is at a plain list, an item or
22466 a footnote definition, try to fill the first paragraph within."
22467 (interactive)
22468 (if (and (derived-mode-p 'message-mode)
22469 (or (not (message-in-body-p))
22470 (save-excursion (move-beginning-of-line 1)
22471 (looking-at message-cite-prefix-regexp))))
22472 ;; First ensure filling is correct in message-mode.
22473 (let ((fill-paragraph-function
22474 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22475 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22476 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22477 (paragraph-separate
22478 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22479 (fill-paragraph nil))
22480 (with-syntax-table org-mode-transpose-word-syntax-table
22481 ;; Move to end of line in order to get the first paragraph
22482 ;; within a plain list or a footnote definition.
22483 (let ((element (save-excursion
22484 (end-of-line)
22485 (or (ignore-errors (org-element-at-point))
22486 (user-error "An element cannot be parsed line %d"
22487 (line-number-at-pos (point)))))))
22488 ;; First check if point is in a blank line at the beginning of
22489 ;; the buffer. In that case, ignore filling.
22490 (case (org-element-type element)
22491 ;; Use major mode filling function is src blocks.
22492 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22493 ;; Align Org tables, leave table.el tables as-is.
22494 (table-row (org-table-align) t)
22495 (table
22496 (when (eq (org-element-property :type element) 'org)
22497 (save-excursion
22498 (goto-char (org-element-property :post-affiliated element))
22499 (org-table-align)))
22501 (paragraph
22502 ;; Paragraphs may contain `line-break' type objects.
22503 (let ((beg (max (point-min)
22504 (org-element-property :contents-begin element)))
22505 (end (min (point-max)
22506 (org-element-property :contents-end element))))
22507 ;; Do nothing if point is at an affiliated keyword.
22508 (if (< (line-end-position) beg) t
22509 (when (derived-mode-p 'message-mode)
22510 ;; In `message-mode', do not fill following citation
22511 ;; in current paragraph nor text before message body.
22512 (let ((body-start (save-excursion (message-goto-body))))
22513 (when body-start (setq beg (max body-start beg))))
22514 (when (save-excursion
22515 (re-search-forward
22516 (concat "^" message-cite-prefix-regexp) end t))
22517 (setq end (match-beginning 0))))
22518 ;; Fill paragraph, taking line breaks into account.
22519 ;; For that, slice the paragraph using line breaks as
22520 ;; separators, and fill the parts in reverse order to
22521 ;; avoid messing with markers.
22522 (save-excursion
22523 (goto-char end)
22524 (mapc
22525 (lambda (pos)
22526 (fill-region-as-paragraph pos (point) justify)
22527 (goto-char pos))
22528 ;; Find the list of ending positions for line breaks
22529 ;; in the current paragraph. Add paragraph
22530 ;; beginning to include first slice.
22531 (nreverse
22532 (cons beg
22533 (org-element-map
22534 (org-element--parse-objects
22535 beg end nil (org-element-restriction 'paragraph))
22536 'line-break
22537 (lambda (lb) (org-element-property :end lb)))))))
22538 t)))
22539 ;; Contents of `comment-block' type elements should be
22540 ;; filled as plain text, but only if point is within block
22541 ;; markers.
22542 (comment-block
22543 (let* ((case-fold-search t)
22544 (beg (save-excursion
22545 (goto-char (org-element-property :begin element))
22546 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22547 (forward-line)
22548 (point)))
22549 (end (save-excursion
22550 (goto-char (org-element-property :end element))
22551 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22552 (line-beginning-position))))
22553 (if (or (< (point) beg) (> (point) end)) t
22554 (fill-region-as-paragraph
22555 (save-excursion (end-of-line)
22556 (re-search-backward "^[ \t]*$" beg 'move)
22557 (line-beginning-position))
22558 (save-excursion (beginning-of-line)
22559 (re-search-forward "^[ \t]*$" end 'move)
22560 (line-beginning-position))
22561 justify))))
22562 ;; Fill comments.
22563 (comment
22564 (let ((begin (org-element-property :post-affiliated element))
22565 (end (org-element-property :end element)))
22566 (when (and (>= (point) begin) (<= (point) end))
22567 (let ((begin (save-excursion
22568 (end-of-line)
22569 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22570 (progn (forward-line) (point))
22571 begin)))
22572 (end (save-excursion
22573 (end-of-line)
22574 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22575 (1- (line-beginning-position))
22576 (skip-chars-backward " \r\t\n")
22577 (line-end-position)))))
22578 ;; Do not fill comments when at a blank line.
22579 (when (> end begin)
22580 (let ((fill-prefix
22581 (save-excursion
22582 (beginning-of-line)
22583 (looking-at "[ \t]*#")
22584 (let ((comment-prefix (match-string 0)))
22585 (goto-char (match-end 0))
22586 (if (looking-at adaptive-fill-regexp)
22587 (concat comment-prefix (match-string 0))
22588 (concat comment-prefix " "))))))
22589 (save-excursion
22590 (fill-region-as-paragraph begin end justify))))))
22592 ;; Ignore every other element.
22593 (otherwise t))))))
22595 (defun org-auto-fill-function ()
22596 "Auto-fill function."
22597 ;; Check if auto-filling is meaningful.
22598 (let ((fc (current-fill-column)))
22599 (when (and fc (> (current-column) fc))
22600 (let* ((fill-prefix (org-adaptive-fill-function))
22601 ;; Enforce empty fill prefix, if required. Otherwise, it
22602 ;; will be computed again.
22603 (adaptive-fill-mode (not (equal fill-prefix ""))))
22604 (when fill-prefix (do-auto-fill))))))
22606 (defun org-comment-line-break-function (&optional soft)
22607 "Break line at point and indent, continuing comment if within one.
22608 The inserted newline is marked hard if variable
22609 `use-hard-newlines' is true, unless optional argument SOFT is
22610 non-nil."
22611 (if soft (insert-and-inherit ?\n) (newline 1))
22612 (save-excursion (forward-char -1) (delete-horizontal-space))
22613 (delete-horizontal-space)
22614 (indent-to-left-margin)
22615 (insert-before-markers-and-inherit fill-prefix))
22618 ;;; Comments
22620 ;; Org comments syntax is quite complex. It requires the entire line
22621 ;; to be just a comment. Also, even with the right syntax at the
22622 ;; beginning of line, some some elements (i.e. verse-block or
22623 ;; example-block) don't accept comments. Usual Emacs comment commands
22624 ;; cannot cope with those requirements. Therefore, Org replaces them.
22626 ;; Org still relies on `comment-dwim', but cannot trust
22627 ;; `comment-only-p'. So, `comment-region-function' and
22628 ;; `uncomment-region-function' both point
22629 ;; to`org-comment-or-uncomment-region'. Eventually,
22630 ;; `org-insert-comment' takes care of insertion of comments at the
22631 ;; beginning of line.
22633 ;; `org-setup-comments-handling' install comments related variables
22634 ;; during `org-mode' initialization.
22636 (defun org-setup-comments-handling ()
22637 (interactive)
22638 (org-set-local 'comment-use-syntax nil)
22639 (org-set-local 'comment-start "# ")
22640 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22641 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22642 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22643 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22645 (defun org-insert-comment ()
22646 "Insert an empty comment above current line.
22647 If the line is empty, insert comment at its beginning. When
22648 point is within a source block, comment according to the related
22649 major mode."
22650 (if (let ((element (org-element-at-point)))
22651 (and (eq (org-element-type element) 'src-block)
22652 (< (save-excursion
22653 (goto-char (org-element-property :post-affiliated element))
22654 (line-end-position))
22655 (point))
22656 (> (save-excursion
22657 (goto-char (org-element-property :end element))
22658 (skip-chars-backward " \r\t\n")
22659 (line-beginning-position))
22660 (point))))
22661 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22662 (beginning-of-line)
22663 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22664 (open-line 1))
22665 (org-indent-line)
22666 (insert "# ")))
22668 (defvar comment-empty-lines) ; From newcomment.el.
22669 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22670 "Comment or uncomment each non-blank line in the region.
22671 Uncomment each non-blank line between BEG and END if it only
22672 contains commented lines. Otherwise, comment them. If region is
22673 strictly within a source block, use appropriate comment syntax."
22674 (if (let ((element (org-element-at-point)))
22675 (and (eq (org-element-type element) 'src-block)
22676 (< (save-excursion
22677 (goto-char (org-element-property :post-affiliated element))
22678 (line-end-position))
22679 beg)
22680 (>= (save-excursion
22681 (goto-char (org-element-property :end element))
22682 (skip-chars-backward " \r\t\n")
22683 (line-beginning-position))
22684 end)))
22685 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22686 (save-restriction
22687 ;; Restrict region
22688 (narrow-to-region (save-excursion (goto-char beg)
22689 (skip-chars-forward " \r\t\n" end)
22690 (line-beginning-position))
22691 (save-excursion (goto-char end)
22692 (skip-chars-backward " \r\t\n" beg)
22693 (line-end-position)))
22694 (let ((uncommentp
22695 ;; UNCOMMENTP is non-nil when every non blank line between
22696 ;; BEG and END is a comment.
22697 (save-excursion
22698 (goto-char (point-min))
22699 (while (and (not (eobp))
22700 (let ((element (org-element-at-point)))
22701 (and (eq (org-element-type element) 'comment)
22702 (goto-char (min (point-max)
22703 (org-element-property
22704 :end element)))))))
22705 (eobp))))
22706 (if uncommentp
22707 ;; Only blank lines and comments in region: uncomment it.
22708 (save-excursion
22709 (goto-char (point-min))
22710 (while (not (eobp))
22711 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22712 (replace-match "" nil nil nil 1))
22713 (forward-line)))
22714 ;; Comment each line in region.
22715 (let ((min-indent (point-max)))
22716 ;; First find the minimum indentation across all lines.
22717 (save-excursion
22718 (goto-char (point-min))
22719 (while (and (not (eobp)) (not (zerop min-indent)))
22720 (unless (looking-at "[ \t]*$")
22721 (setq min-indent (min min-indent (current-indentation))))
22722 (forward-line)))
22723 ;; Then loop over all lines.
22724 (save-excursion
22725 (goto-char (point-min))
22726 (while (not (eobp))
22727 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22728 ;; Don't get fooled by invisible text (e.g. link path)
22729 ;; when moving to column MIN-INDENT.
22730 (let ((buffer-invisibility-spec nil))
22731 (org-move-to-column min-indent t))
22732 (insert comment-start))
22733 (forward-line)))))))))
22735 (defun org-comment-dwim (arg)
22736 (interactive "*P")
22737 "Call `comment-dwim' within a source edit buffer if needed."
22738 (if (org-in-src-block-p)
22739 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22740 (call-interactively #'comment-dwim)))
22743 ;;; Planning
22745 ;; This section contains tools to operate on timestamp objects, as
22746 ;; returned by, e.g. `org-element-context'.
22748 (defun org-timestamp-has-time-p (timestamp)
22749 "Non-nil when TIMESTAMP has a time specified."
22750 (org-element-property :hour-start timestamp))
22752 (defun org-timestamp-format (timestamp format &optional end utc)
22753 "Format a TIMESTAMP element into a string.
22755 FORMAT is a format specifier to be passed to
22756 `format-time-string'.
22758 When optional argument END is non-nil, use end of date-range or
22759 time-range, if possible.
22761 When optional argument UTC is non-nil, time will be expressed as
22762 Universal Time."
22763 (format-time-string
22764 format
22765 (apply 'encode-time
22766 (cons 0
22767 (mapcar
22768 (lambda (prop) (or (org-element-property prop timestamp) 0))
22769 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22770 '(:minute-start :hour-start :day-start :month-start
22771 :year-start)))))
22772 utc))
22774 (defun org-timestamp-split-range (timestamp &optional end)
22775 "Extract a timestamp object from a date or time range.
22777 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22778 the end of the range. Otherwise, extract its start.
22780 Return a new timestamp object sharing the same parent as
22781 TIMESTAMP."
22782 (let ((type (org-element-property :type timestamp)))
22783 (if (memq type '(active inactive diary)) timestamp
22784 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22785 ;; Set new type.
22786 (org-element-put-property
22787 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22788 ;; Copy start properties over end properties if END is
22789 ;; non-nil. Otherwise, copy end properties over `start' ones.
22790 (let ((p-alist '((:minute-start . :minute-end)
22791 (:hour-start . :hour-end)
22792 (:day-start . :day-end)
22793 (:month-start . :month-end)
22794 (:year-start . :year-end))))
22795 (dolist (p-cell p-alist)
22796 (org-element-put-property
22797 split-ts
22798 (funcall (if end 'car 'cdr) p-cell)
22799 (org-element-property
22800 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22801 ;; Eventually refresh `:raw-value'.
22802 (org-element-put-property split-ts :raw-value nil)
22803 (org-element-put-property
22804 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22806 (defun org-timestamp-translate (timestamp &optional boundary)
22807 "Apply `org-translate-time' on a TIMESTAMP object.
22808 When optional argument BOUNDARY is non-nil, it is either the
22809 symbol `start' or `end'. In this case, only translate the
22810 starting or ending part of TIMESTAMP if it is a date or time
22811 range. Otherwise, translate both parts."
22812 (if (and (not boundary)
22813 (memq (org-element-property :type timestamp)
22814 '(active-range inactive-range)))
22815 (concat
22816 (org-translate-time
22817 (org-element-property :raw-value
22818 (org-timestamp-split-range timestamp)))
22819 "--"
22820 (org-translate-time
22821 (org-element-property :raw-value
22822 (org-timestamp-split-range timestamp t))))
22823 (org-translate-time
22824 (org-element-property
22825 :raw-value
22826 (if (not boundary) timestamp
22827 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22831 ;;; Other stuff.
22833 (defun org-reftex-citation ()
22834 "Use reftex-citation to insert a citation into the buffer.
22835 This looks for a line like
22837 #+BIBLIOGRAPHY: foo plain option:-d
22839 and derives from it that foo.bib is the bibliography file relevant
22840 for this document. It then installs the necessary environment for RefTeX
22841 to work in this buffer and calls `reftex-citation' to insert a citation
22842 into the buffer.
22844 Export of such citations to both LaTeX and HTML is handled by the contributed
22845 package ox-bibtex by Taru Karttunen."
22846 (interactive)
22847 (let ((reftex-docstruct-symbol 'rds)
22848 (reftex-cite-format "\\cite{%l}")
22849 rds bib)
22850 (save-excursion
22851 (save-restriction
22852 (widen)
22853 (let ((case-fold-search t)
22854 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22855 (if (not (save-excursion
22856 (or (re-search-forward re nil t)
22857 (re-search-backward re nil t))))
22858 (error "No bibliography defined in file")
22859 (setq bib (concat (match-string 1) ".bib")
22860 rds (list (list 'bib bib)))))))
22861 (call-interactively 'reftex-citation)))
22863 ;;;; Functions extending outline functionality
22865 (defun org-beginning-of-line (&optional arg)
22866 "Go to the beginning of the current line. If that is invisible, continue
22867 to a visible line beginning. This makes the function of C-a more intuitive.
22868 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22869 first attempt, and only move to after the tags when the cursor is already
22870 beyond the end of the headline."
22871 (interactive "P")
22872 (let ((pos (point))
22873 (special (if (consp org-special-ctrl-a/e)
22874 (car org-special-ctrl-a/e)
22875 org-special-ctrl-a/e))
22876 deactivate-mark refpos)
22877 (if (org-bound-and-true-p visual-line-mode)
22878 (beginning-of-visual-line 1)
22879 (beginning-of-line 1))
22880 (if (and arg (fboundp 'move-beginning-of-line))
22881 (call-interactively 'move-beginning-of-line)
22882 (if (bobp)
22884 (backward-char 1)
22885 (if (org-truely-invisible-p)
22886 (while (and (not (bobp)) (org-truely-invisible-p))
22887 (backward-char 1)
22888 (beginning-of-line 1))
22889 (forward-char 1))))
22890 (when special
22891 (cond
22892 ((and (looking-at org-complex-heading-regexp)
22893 (= (char-after (match-end 1)) ?\ ))
22894 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22895 (point-at-eol)))
22896 (goto-char
22897 (if (eq special t)
22898 (cond ((> pos refpos) refpos)
22899 ((= pos (point)) refpos)
22900 (t (point)))
22901 (cond ((> pos (point)) (point))
22902 ((not (eq last-command this-command)) (point))
22903 (t refpos)))))
22904 ((org-at-item-p)
22905 ;; Being at an item and not looking at an the item means point
22906 ;; was previously moved to beginning of a visual line, which
22907 ;; doesn't contain the item. Therefore, do nothing special,
22908 ;; just stay here.
22909 (when (looking-at org-list-full-item-re)
22910 ;; Set special position at first white space character after
22911 ;; bullet, and check-box, if any.
22912 (let ((after-bullet
22913 (let ((box (match-end 3)))
22914 (if (not box) (match-end 1)
22915 (let ((after (char-after box)))
22916 (if (and after (= after ? )) (1+ box) box))))))
22917 ;; Special case: Move point to special position when
22918 ;; currently after it or at beginning of line.
22919 (if (eq special t)
22920 (when (or (> pos after-bullet) (= (point) pos))
22921 (goto-char after-bullet))
22922 ;; Reversed case: Move point to special position when
22923 ;; point was already at beginning of line and command is
22924 ;; repeated.
22925 (when (and (= (point) pos) (eq last-command this-command))
22926 (goto-char after-bullet))))))))
22927 (org-no-warnings
22928 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22929 (setq disable-point-adjustment
22930 (or (not (invisible-p (point)))
22931 (not (invisible-p (max (point-min) (1- (point))))))))
22933 (defun org-end-of-line (&optional arg)
22934 "Go to the end of the line.
22935 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22936 tags on the first attempt, and only move to after the tags when
22937 the cursor is already beyond the end of the headline."
22938 (interactive "P")
22939 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22940 org-special-ctrl-a/e))
22941 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22942 'end-of-visual-line)
22943 ((fboundp 'move-end-of-line) 'move-end-of-line)
22944 (t 'end-of-line)))
22945 deactivate-mark)
22946 (if (or (not special) arg) (call-interactively move-fun)
22947 (let* ((element (save-excursion (beginning-of-line)
22948 (org-element-at-point)))
22949 (type (org-element-type element)))
22950 (cond
22951 ((memq type '(headline inlinetask))
22952 (let ((pos (point)))
22953 (beginning-of-line 1)
22954 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22955 (if (eq special t)
22956 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22957 (goto-char (match-beginning 1))
22958 (goto-char (match-end 0)))
22959 (if (or (< pos (match-end 0))
22960 (not (eq this-command last-command)))
22961 (goto-char (match-end 0))
22962 (goto-char (match-beginning 1))))
22963 (call-interactively move-fun))))
22964 ((outline-invisible-p (line-end-position))
22965 ;; If element is hidden, `move-end-of-line' would put point
22966 ;; after it. Use `end-of-line' to stay on current line.
22967 (call-interactively 'end-of-line))
22968 (t (call-interactively move-fun)))))
22969 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22970 (setq disable-point-adjustment
22971 (or (not (invisible-p (point)))
22972 (not (invisible-p (max (point-min) (1- (point))))))))
22974 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22975 (define-key org-mode-map "\C-e" 'org-end-of-line)
22977 (defun org-backward-sentence (&optional arg)
22978 "Go to beginning of sentence, or beginning of table field.
22979 This will call `backward-sentence' or `org-table-beginning-of-field',
22980 depending on context."
22981 (interactive "P")
22982 (cond
22983 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22984 (t (call-interactively 'backward-sentence))))
22986 (defun org-forward-sentence (&optional arg)
22987 "Go to end of sentence, or end of table field.
22988 This will call `forward-sentence' or `org-table-end-of-field',
22989 depending on context."
22990 (interactive "P")
22991 (cond
22992 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22993 (t (call-interactively 'forward-sentence))))
22995 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22996 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22998 (defun org-kill-line (&optional arg)
22999 "Kill line, to tags or end of line."
23000 (interactive "P")
23001 (cond
23002 ((or (not org-special-ctrl-k)
23003 (bolp)
23004 (not (org-at-heading-p)))
23005 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23006 org-ctrl-k-protect-subtree)
23007 (if (or (eq org-ctrl-k-protect-subtree 'error)
23008 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23009 (user-error "C-k aborted as it would kill a hidden subtree")))
23010 (call-interactively
23011 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23012 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23013 (kill-region (point) (match-beginning 1))
23014 (org-set-tags nil t))
23015 (t (kill-region (point) (point-at-eol)))))
23017 (define-key org-mode-map "\C-k" 'org-kill-line)
23019 (defun org-yank (&optional arg)
23020 "Yank. If the kill is a subtree, treat it specially.
23021 This command will look at the current kill and check if is a single
23022 subtree, or a series of subtrees[1]. If it passes the test, and if the
23023 cursor is at the beginning of a line or after the stars of a currently
23024 empty headline, then the yank is handled specially. How exactly depends
23025 on the value of the following variables, both set by default.
23027 org-yank-folded-subtrees
23028 When set, the subtree(s) will be folded after insertion, but only
23029 if doing so would now swallow text after the yanked text.
23031 org-yank-adjusted-subtrees
23032 When set, the subtree will be promoted or demoted in order to
23033 fit into the local outline tree structure, which means that the level
23034 will be adjusted so that it becomes the smaller one of the two
23035 *visible* surrounding headings.
23037 Any prefix to this command will cause `yank' to be called directly with
23038 no special treatment. In particular, a simple \\[universal-argument] prefix \
23039 will just
23040 plainly yank the text as it is.
23042 \[1] The test checks if the first non-white line is a heading
23043 and if there are no other headings with fewer stars."
23044 (interactive "P")
23045 (org-yank-generic 'yank arg))
23047 (defun org-yank-generic (command arg)
23048 "Perform some yank-like command.
23050 This function implements the behavior described in the `org-yank'
23051 documentation. However, it has been generalized to work for any
23052 interactive command with similar behavior."
23054 ;; pretend to be command COMMAND
23055 (setq this-command command)
23057 (if arg
23058 (call-interactively command)
23060 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23061 (and (org-kill-is-subtree-p)
23062 (or (bolp)
23063 (and (looking-at "[ \t]*$")
23064 (string-match
23065 "\\`\\*+\\'"
23066 (buffer-substring (point-at-bol) (point)))))))
23067 swallowp)
23068 (cond
23069 ((and subtreep org-yank-folded-subtrees)
23070 (let ((beg (point))
23071 end)
23072 (if (and subtreep org-yank-adjusted-subtrees)
23073 (org-paste-subtree nil nil 'for-yank)
23074 (call-interactively command))
23076 (setq end (point))
23077 (goto-char beg)
23078 (when (and (bolp) subtreep
23079 (not (setq swallowp
23080 (org-yank-folding-would-swallow-text beg end))))
23081 (org-with-limited-levels
23082 (or (looking-at org-outline-regexp)
23083 (re-search-forward org-outline-regexp-bol end t))
23084 (while (and (< (point) end) (looking-at org-outline-regexp))
23085 (hide-subtree)
23086 (org-cycle-show-empty-lines 'folded)
23087 (condition-case nil
23088 (outline-forward-same-level 1)
23089 (error (goto-char end))))))
23090 (when swallowp
23091 (message
23092 "Inserted text not folded because that would swallow text"))
23094 (goto-char end)
23095 (skip-chars-forward " \t\n\r")
23096 (beginning-of-line 1)
23097 (push-mark beg 'nomsg)))
23098 ((and subtreep org-yank-adjusted-subtrees)
23099 (let ((beg (point-at-bol)))
23100 (org-paste-subtree nil nil 'for-yank)
23101 (push-mark beg 'nomsg)))
23103 (call-interactively command))))))
23105 (defun org-yank-folding-would-swallow-text (beg end)
23106 "Would hide-subtree at BEG swallow any text after END?"
23107 (let (level)
23108 (org-with-limited-levels
23109 (save-excursion
23110 (goto-char beg)
23111 (when (or (looking-at org-outline-regexp)
23112 (re-search-forward org-outline-regexp-bol end t))
23113 (setq level (org-outline-level)))
23114 (goto-char end)
23115 (skip-chars-forward " \t\r\n\v\f")
23116 (if (or (eobp)
23117 (and (bolp) (looking-at org-outline-regexp)
23118 (<= (org-outline-level) level)))
23119 nil ; Nothing would be swallowed
23120 t))))) ; something would swallow
23122 (define-key org-mode-map "\C-y" 'org-yank)
23124 (defun org-truely-invisible-p ()
23125 "Check if point is at a character currently not visible.
23126 This version does not only check the character property, but also
23127 `visible-mode'."
23128 ;; Early versions of noutline don't have `outline-invisible-p'.
23129 (if (org-bound-and-true-p visible-mode)
23131 (outline-invisible-p)))
23133 (defun org-invisible-p2 ()
23134 "Check if point is at a character currently not visible."
23135 (save-excursion
23136 (if (and (eolp) (not (bobp))) (backward-char 1))
23137 ;; Early versions of noutline don't have `outline-invisible-p'.
23138 (outline-invisible-p)))
23140 (defun org-back-to-heading (&optional invisible-ok)
23141 "Call `outline-back-to-heading', but provide a better error message."
23142 (condition-case nil
23143 (outline-back-to-heading invisible-ok)
23144 (error (error "Before first headline at position %d in buffer %s"
23145 (point) (current-buffer)))))
23147 (defun org-before-first-heading-p ()
23148 "Before first heading?"
23149 (save-excursion
23150 (end-of-line)
23151 (null (re-search-backward org-outline-regexp-bol nil t))))
23153 (defun org-at-heading-p (&optional ignored)
23154 (outline-on-heading-p t))
23155 ;; Compatibility alias with Org versions < 7.8.03
23156 (defalias 'org-on-heading-p 'org-at-heading-p)
23158 (defun org-at-comment-p nil
23159 "Is cursor in a line starting with a # character?"
23160 (save-excursion
23161 (beginning-of-line)
23162 (looking-at "^#")))
23164 (defun org-at-drawer-p nil
23165 "Is cursor at a drawer keyword?"
23166 (save-excursion
23167 (move-beginning-of-line 1)
23168 (looking-at org-drawer-regexp)))
23170 (defun org-at-block-p nil
23171 "Is cursor at a block keyword?"
23172 (save-excursion
23173 (move-beginning-of-line 1)
23174 (looking-at org-block-regexp)))
23176 (defun org-point-at-end-of-empty-headline ()
23177 "If point is at the end of an empty headline, return t, else nil.
23178 If the heading only contains a TODO keyword, it is still still considered
23179 empty."
23180 (and (looking-at "[ \t]*$")
23181 (when org-todo-line-regexp
23182 (save-excursion
23183 (beginning-of-line 1)
23184 (let ((case-fold-search nil))
23185 (looking-at org-todo-line-regexp)
23186 (string= (match-string 3) ""))))))
23188 (defun org-at-heading-or-item-p ()
23189 (or (org-at-heading-p) (org-at-item-p)))
23191 (defun org-at-target-p ()
23192 (or (org-in-regexp org-radio-target-regexp)
23193 (org-in-regexp org-target-regexp)))
23194 ;; Compatibility alias with Org versions < 7.8.03
23195 (defalias 'org-on-target-p 'org-at-target-p)
23197 (defun org-up-heading-all (arg)
23198 "Move to the heading line of which the present line is a subheading.
23199 This function considers both visible and invisible heading lines.
23200 With argument, move up ARG levels."
23201 (if (fboundp 'outline-up-heading-all)
23202 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23203 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23205 (defun org-up-heading-safe ()
23206 "Move to the heading line of which the present line is a subheading.
23207 This version will not throw an error. It will return the level of the
23208 headline found, or nil if no higher level is found.
23210 Also, this function will be a lot faster than `outline-up-heading',
23211 because it relies on stars being the outline starters. This can really
23212 make a significant difference in outlines with very many siblings."
23213 (let (start-level re)
23214 (org-back-to-heading t)
23215 (setq start-level (funcall outline-level))
23216 (if (equal start-level 1)
23218 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23219 (if (re-search-backward re nil t)
23220 (funcall outline-level)))))
23222 (defun org-first-sibling-p ()
23223 "Is this heading the first child of its parents?"
23224 (interactive)
23225 (let ((re org-outline-regexp-bol)
23226 level l)
23227 (unless (org-at-heading-p t)
23228 (user-error "Not at a heading"))
23229 (setq level (funcall outline-level))
23230 (save-excursion
23231 (if (not (re-search-backward re nil t))
23233 (setq l (funcall outline-level))
23234 (< l level)))))
23236 (defun org-goto-sibling (&optional previous)
23237 "Goto the next sibling, even if it is invisible.
23238 When PREVIOUS is set, go to the previous sibling instead. Returns t
23239 when a sibling was found. When none is found, return nil and don't
23240 move point."
23241 (let ((fun (if previous 're-search-backward 're-search-forward))
23242 (pos (point))
23243 (re org-outline-regexp-bol)
23244 level l)
23245 (when (condition-case nil (org-back-to-heading t) (error nil))
23246 (setq level (funcall outline-level))
23247 (catch 'exit
23248 (or previous (forward-char 1))
23249 (while (funcall fun re nil t)
23250 (setq l (funcall outline-level))
23251 (when (< l level) (goto-char pos) (throw 'exit nil))
23252 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23253 (goto-char pos)
23254 nil))))
23256 (defun org-show-siblings ()
23257 "Show all siblings of the current headline."
23258 (save-excursion
23259 (while (org-goto-sibling) (org-flag-heading nil)))
23260 (save-excursion
23261 (while (org-goto-sibling 'previous)
23262 (org-flag-heading nil))))
23264 (defun org-goto-first-child ()
23265 "Goto the first child, even if it is invisible.
23266 Return t when a child was found. Otherwise don't move point and
23267 return nil."
23268 (let (level (pos (point)) (re org-outline-regexp-bol))
23269 (when (condition-case nil (org-back-to-heading t) (error nil))
23270 (setq level (outline-level))
23271 (forward-char 1)
23272 (if (and (re-search-forward re nil t) (> (outline-level) level))
23273 (progn (goto-char (match-beginning 0)) t)
23274 (goto-char pos) nil))))
23276 (defun org-show-hidden-entry ()
23277 "Show an entry where even the heading is hidden."
23278 (save-excursion
23279 (org-show-entry)))
23281 (defun org-flag-heading (flag &optional entry)
23282 "Flag the current heading. FLAG non-nil means make invisible.
23283 When ENTRY is non-nil, show the entire entry."
23284 (save-excursion
23285 (org-back-to-heading t)
23286 ;; Check if we should show the entire entry
23287 (if entry
23288 (progn
23289 (org-show-entry)
23290 (save-excursion
23291 (and (outline-next-heading)
23292 (org-flag-heading nil))))
23293 (outline-flag-region (max (point-min) (1- (point)))
23294 (save-excursion (outline-end-of-heading) (point))
23295 flag))))
23297 (defun org-get-next-sibling ()
23298 "Move to next heading of the same level, and return point.
23299 If there is no such heading, return nil.
23300 This is like outline-next-sibling, but invisible headings are ok."
23301 (let ((level (funcall outline-level)))
23302 (outline-next-heading)
23303 (while (and (not (eobp)) (> (funcall outline-level) level))
23304 (outline-next-heading))
23305 (if (or (eobp) (< (funcall outline-level) level))
23307 (point))))
23309 (defun org-get-last-sibling ()
23310 "Move to previous heading of the same level, and return point.
23311 If there is no such heading, return nil."
23312 (let ((opoint (point))
23313 (level (funcall outline-level)))
23314 (outline-previous-heading)
23315 (when (and (/= (point) opoint) (outline-on-heading-p t))
23316 (while (and (> (funcall outline-level) level)
23317 (not (bobp)))
23318 (outline-previous-heading))
23319 (if (< (funcall outline-level) level)
23321 (point)))))
23323 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23324 "Goto to the end of a subtree."
23325 ;; This contains an exact copy of the original function, but it uses
23326 ;; `org-back-to-heading', to make it work also in invisible
23327 ;; trees. And is uses an invisible-ok argument.
23328 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23329 ;; Furthermore, when used inside Org, finding the end of a large subtree
23330 ;; with many children and grandchildren etc, this can be much faster
23331 ;; than the outline version.
23332 (org-back-to-heading invisible-ok)
23333 (let ((first t)
23334 (level (funcall outline-level)))
23335 (if (and (derived-mode-p 'org-mode) (< level 1000))
23336 ;; A true heading (not a plain list item), in Org-mode
23337 ;; This means we can easily find the end by looking
23338 ;; only for the right number of stars. Using a regexp to do
23339 ;; this is so much faster than using a Lisp loop.
23340 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23341 (forward-char 1)
23342 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23343 ;; something else, do it the slow way
23344 (while (and (not (eobp))
23345 (or first (> (funcall outline-level) level)))
23346 (setq first nil)
23347 (outline-next-heading)))
23348 (unless to-heading
23349 (if (memq (preceding-char) '(?\n ?\^M))
23350 (progn
23351 ;; Go to end of line before heading
23352 (forward-char -1)
23353 (if (memq (preceding-char) '(?\n ?\^M))
23354 ;; leave blank line before heading
23355 (forward-char -1))))))
23356 (point))
23358 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23359 "Use Org version in org-mode, for dramatic speed-up."
23360 (if (derived-mode-p 'org-mode)
23361 (progn
23362 (org-end-of-subtree nil t)
23363 (unless (eobp) (backward-char 1)))
23364 ad-do-it))
23366 (defun org-end-of-meta-data-and-drawers ()
23367 "Jump to the first text after meta data and drawers in the current entry.
23368 This will move over empty lines, lines with planning time stamps,
23369 clocking lines, and drawers."
23370 (org-back-to-heading t)
23371 (let ((end (save-excursion (outline-next-heading) (point)))
23372 (re (concat "\\(" org-drawer-regexp "\\)"
23373 "\\|" "[ \t]*" org-keyword-time-regexp)))
23374 (forward-line 1)
23375 (while (re-search-forward re end t)
23376 (if (not (match-end 1))
23377 ;; empty or planning line
23378 (forward-line 1)
23379 ;; a drawer, find the end
23380 (re-search-forward "^[ \t]*:END:" end 'move)
23381 (forward-line 1)))
23382 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23383 (point)))
23385 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23386 "Move forward to the ARG'th subheading at same level as this one.
23387 Stop at the first and last subheadings of a superior heading.
23388 Normally this only looks at visible headings, but when INVISIBLE-OK is
23389 non-nil it will also look at invisible ones."
23390 (interactive "p")
23391 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23392 (if (and arg (< arg 0))
23393 (goto-char (point-min))
23394 (outline-next-heading))
23395 (org-at-heading-p)
23396 (let ((level (- (match-end 0) (match-beginning 0) 1))
23397 (f (if (and arg (< arg 0))
23398 're-search-backward
23399 're-search-forward))
23400 (count (if arg (abs arg) 1))
23401 (result (point)))
23402 (while (and (prog1 (> count 0)
23403 (forward-char (if (and arg (< arg 0)) -1 1)))
23404 (funcall f org-outline-regexp-bol nil 'move))
23405 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23406 (cond ((< l level) (setq count 0))
23407 ((and (= l level)
23408 (or invisible-ok
23409 (progn
23410 (goto-char (line-beginning-position))
23411 (not (outline-invisible-p)))))
23412 (setq count (1- count))
23413 (when (eq l level)
23414 (setq result (point)))))))
23415 (goto-char result))
23416 (beginning-of-line 1)))
23418 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23419 "Move backward to the ARG'th subheading at same level as this one.
23420 Stop at the first and last subheadings of a superior heading."
23421 (interactive "p")
23422 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23424 (defun org-next-block (arg &optional backward block-regexp)
23425 "Jump to the next block.
23426 With a prefix argument ARG, jump forward ARG many source blocks.
23427 When BACKWARD is non-nil, jump to the previous block.
23428 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23429 (interactive "p")
23430 (let ((re (or block-regexp org-block-regexp))
23431 (re-search-fn (or (and backward 're-search-backward)
23432 're-search-forward)))
23433 (if (looking-at re) (forward-char 1))
23434 (condition-case nil
23435 (funcall re-search-fn re nil nil arg)
23436 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23437 (goto-char (match-beginning 0)) (org-show-context)))
23439 (defun org-previous-block (arg &optional block-regexp)
23440 "Jump to the previous block.
23441 With a prefix argument ARG, jump backward ARG many source blocks.
23442 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23443 (interactive "p")
23444 (org-next-block arg t block-regexp))
23446 (defun org-forward-paragraph ()
23447 "Move forward to beginning of next paragraph or equivalent.
23449 The function moves point to the beginning of the next visible
23450 structural element, which can be a paragraph, a table, a list
23451 item, etc. It also provides some special moves for convenience:
23453 - On an affiliated keyword, jump to the beginning of the
23454 relative element.
23455 - On an item or a footnote definition, move to the second
23456 element inside, if any.
23457 - On a table or a property drawer, jump after it.
23458 - On a verse or source block, stop after blank lines."
23459 (interactive)
23460 (when (eobp) (user-error "Cannot move further down"))
23461 (let* ((deactivate-mark nil)
23462 (element (org-element-at-point))
23463 (type (org-element-type element))
23464 (post-affiliated (org-element-property :post-affiliated element))
23465 (contents-begin (org-element-property :contents-begin element))
23466 (contents-end (org-element-property :contents-end element))
23467 (end (let ((end (org-element-property :end element)) (parent element))
23468 (while (and (setq parent (org-element-property :parent parent))
23469 (= (org-element-property :contents-end parent) end))
23470 (setq end (org-element-property :end parent)))
23471 end)))
23472 (cond ((not element)
23473 (skip-chars-forward " \r\t\n")
23474 (or (eobp) (beginning-of-line)))
23475 ;; On affiliated keywords, move to element's beginning.
23476 ((and post-affiliated (< (point) post-affiliated))
23477 (goto-char post-affiliated))
23478 ;; At a table row, move to the end of the table. Similarly,
23479 ;; at a node property, move to the end of the property
23480 ;; drawer.
23481 ((memq type '(node-property table-row))
23482 (goto-char (org-element-property
23483 :end (org-element-property :parent element))))
23484 ((memq type '(property-drawer table)) (goto-char end))
23485 ;; Consider blank lines as separators in verse and source
23486 ;; blocks to ease editing.
23487 ((memq type '(src-block verse-block))
23488 (when (eq type 'src-block)
23489 (setq contents-end
23490 (save-excursion (goto-char end)
23491 (skip-chars-backward " \r\t\n")
23492 (line-beginning-position))))
23493 (beginning-of-line)
23494 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23495 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23496 (goto-char end)
23497 (skip-chars-forward " \r\t\n")
23498 (if (= (point) contents-end) (goto-char end)
23499 (beginning-of-line))))
23500 ;; With no contents, just skip element.
23501 ((not contents-begin) (goto-char end))
23502 ;; If contents are invisible, skip the element altogether.
23503 ((outline-invisible-p (line-end-position))
23504 (case type
23505 (headline
23506 (org-with-limited-levels (outline-next-visible-heading 1)))
23507 ;; At a plain list, make sure we move to the next item
23508 ;; instead of skipping the whole list.
23509 (plain-list (forward-char)
23510 (org-forward-paragraph))
23511 (otherwise (goto-char end))))
23512 ((>= (point) contents-end) (goto-char end))
23513 ((>= (point) contents-begin)
23514 ;; This can only happen on paragraphs and plain lists.
23515 (case type
23516 (paragraph (goto-char end))
23517 ;; At a plain list, try to move to second element in
23518 ;; first item, if possible.
23519 (plain-list (end-of-line)
23520 (org-forward-paragraph))))
23521 ;; When contents start on the middle of a line (e.g. in
23522 ;; items and footnote definitions), try to reach first
23523 ;; element starting after current line.
23524 ((> (line-end-position) contents-begin)
23525 (end-of-line)
23526 (org-forward-paragraph))
23527 (t (goto-char contents-begin)))))
23529 (defun org-backward-paragraph ()
23530 "Move backward to start of previous paragraph or equivalent.
23532 The function moves point to the beginning of the current
23533 structural element, which can be a paragraph, a table, a list
23534 item, etc., or to the beginning of the previous visible one if
23535 point is already there. It also provides some special moves for
23536 convenience:
23538 - On an affiliated keyword, jump to the first one.
23539 - On a table or a property drawer, move to its beginning.
23540 - On a verse or source block, stop before blank lines."
23541 (interactive)
23542 (when (bobp) (user-error "Cannot move further up"))
23543 (let* ((deactivate-mark nil)
23544 (element (org-element-at-point))
23545 (type (org-element-type element))
23546 (contents-begin (org-element-property :contents-begin element))
23547 (contents-end (org-element-property :contents-end element))
23548 (post-affiliated (org-element-property :post-affiliated element))
23549 (begin (org-element-property :begin element)))
23550 (cond
23551 ((not element) (goto-char (point-min)))
23552 ((= (point) begin)
23553 (backward-char)
23554 (org-backward-paragraph))
23555 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23556 ((memq type '(node-property table-row))
23557 (goto-char (org-element-property
23558 :post-affiliated (org-element-property :parent element))))
23559 ((memq type '(property-drawer table)) (goto-char begin))
23560 ((memq type '(src-block verse-block))
23561 (when (eq type 'src-block)
23562 (setq contents-begin
23563 (save-excursion (goto-char begin) (forward-line) (point))))
23564 (if (= (point) contents-begin) (goto-char post-affiliated)
23565 ;; Inside a verse block, see blank lines as paragraph
23566 ;; separators.
23567 (let ((origin (point)))
23568 (skip-chars-backward " \r\t\n" contents-begin)
23569 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23570 (skip-chars-forward " \r\t\n" origin)
23571 (if (= (point) origin) (goto-char contents-begin)
23572 (beginning-of-line))))))
23573 ((not contents-begin) (goto-char (or post-affiliated begin)))
23574 ((eq type 'paragraph)
23575 (goto-char contents-begin)
23576 ;; When at first paragraph in an item or a footnote definition,
23577 ;; move directly to beginning of line.
23578 (let ((parent-contents
23579 (org-element-property
23580 :contents-begin (org-element-property :parent element))))
23581 (when (and parent-contents (= parent-contents contents-begin))
23582 (beginning-of-line))))
23583 ;; At the end of a greater element, move to the beginning of the
23584 ;; last element within.
23585 ((>= (point) contents-end)
23586 (goto-char (1- contents-end))
23587 (org-backward-paragraph))
23588 (t (goto-char (or post-affiliated begin))))
23589 ;; Ensure we never leave point invisible.
23590 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23592 (defun org-forward-element ()
23593 "Move forward by one element.
23594 Move to the next element at the same level, when possible."
23595 (interactive)
23596 (cond ((eobp) (user-error "Cannot move further down"))
23597 ((org-with-limited-levels (org-at-heading-p))
23598 (let ((origin (point)))
23599 (goto-char (org-end-of-subtree nil t))
23600 (unless (org-with-limited-levels (org-at-heading-p))
23601 (goto-char origin)
23602 (user-error "Cannot move further down"))))
23604 (let* ((elem (org-element-at-point))
23605 (end (org-element-property :end elem))
23606 (parent (org-element-property :parent elem)))
23607 (cond ((and parent (= (org-element-property :contents-end parent) end))
23608 (goto-char (org-element-property :end parent)))
23609 ((integer-or-marker-p end) (goto-char end))
23610 (t (message "No element at point")))))))
23612 (defun org-backward-element ()
23613 "Move backward by one element.
23614 Move to the previous element at the same level, when possible."
23615 (interactive)
23616 (cond ((bobp) (user-error "Cannot move further up"))
23617 ((org-with-limited-levels (org-at-heading-p))
23618 ;; At a headline, move to the previous one, if any, or stay
23619 ;; here.
23620 (let ((origin (point)))
23621 (org-with-limited-levels (org-backward-heading-same-level 1))
23622 ;; When current headline has no sibling above, move to its
23623 ;; parent.
23624 (when (= (point) origin)
23625 (or (org-with-limited-levels (org-up-heading-safe))
23626 (progn (goto-char origin)
23627 (user-error "Cannot move further up"))))))
23629 (let* ((elem (org-element-at-point))
23630 (beg (org-element-property :begin elem)))
23631 (cond
23632 ;; Move to beginning of current element if point isn't
23633 ;; there already.
23634 ((null beg) (message "No element at point"))
23635 ((/= (point) beg) (goto-char beg))
23636 (t (goto-char beg)
23637 (skip-chars-backward " \r\t\n")
23638 (unless (bobp)
23639 (let ((prev (org-element-at-point)))
23640 (goto-char (org-element-property :begin prev))
23641 (while (and (setq prev (org-element-property :parent prev))
23642 (<= (org-element-property :end prev) beg))
23643 (goto-char (org-element-property :begin prev)))))))))))
23645 (defun org-up-element ()
23646 "Move to upper element."
23647 (interactive)
23648 (if (org-with-limited-levels (org-at-heading-p))
23649 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23650 (let* ((elem (org-element-at-point))
23651 (parent (org-element-property :parent elem)))
23652 (if parent (goto-char (org-element-property :begin parent))
23653 (if (org-with-limited-levels (org-before-first-heading-p))
23654 (user-error "No surrounding element")
23655 (org-with-limited-levels (org-back-to-heading)))))))
23657 (defvar org-element-greater-elements)
23658 (defun org-down-element ()
23659 "Move to inner element."
23660 (interactive)
23661 (let ((element (org-element-at-point)))
23662 (cond
23663 ((memq (org-element-type element) '(plain-list table))
23664 (goto-char (org-element-property :contents-begin element))
23665 (forward-char))
23666 ((memq (org-element-type element) org-element-greater-elements)
23667 ;; If contents are hidden, first disclose them.
23668 (when (outline-invisible-p (line-end-position)) (org-cycle))
23669 (goto-char (or (org-element-property :contents-begin element)
23670 (user-error "No content for this element"))))
23671 (t (user-error "No inner element")))))
23673 (defun org-drag-element-backward ()
23674 "Move backward element at point."
23675 (interactive)
23676 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23677 (let* ((elem (org-element-at-point))
23678 (prev-elem
23679 (save-excursion
23680 (goto-char (org-element-property :begin elem))
23681 (skip-chars-backward " \r\t\n")
23682 (unless (bobp)
23683 (let* ((beg (org-element-property :begin elem))
23684 (prev (org-element-at-point))
23685 (up prev))
23686 (while (and (setq up (org-element-property :parent up))
23687 (<= (org-element-property :end prev) beg))
23688 (setq prev up))
23689 prev)))))
23690 ;; Error out if no previous element or previous element is
23691 ;; a parent of the current one.
23692 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23693 (user-error "Cannot drag element backward")
23694 (let ((pos (point)))
23695 (org-element-swap-A-B prev-elem elem)
23696 (goto-char (+ (org-element-property :begin prev-elem)
23697 (- pos (org-element-property :begin elem)))))))))
23699 (defun org-drag-element-forward ()
23700 "Move forward element at point."
23701 (interactive)
23702 (let* ((pos (point))
23703 (elem (org-element-at-point)))
23704 (when (= (point-max) (org-element-property :end elem))
23705 (user-error "Cannot drag element forward"))
23706 (goto-char (org-element-property :end elem))
23707 (let ((next-elem (org-element-at-point)))
23708 (when (or (org-element-nested-p elem next-elem)
23709 (and (eq (org-element-type next-elem) 'headline)
23710 (not (eq (org-element-type elem) 'headline))))
23711 (goto-char pos)
23712 (user-error "Cannot drag element forward"))
23713 ;; Compute new position of point: it's shifted by NEXT-ELEM
23714 ;; body's length (without final blanks) and by the length of
23715 ;; blanks between ELEM and NEXT-ELEM.
23716 (let ((size-next (- (save-excursion
23717 (goto-char (org-element-property :end next-elem))
23718 (skip-chars-backward " \r\t\n")
23719 (forward-line)
23720 ;; Small correction if buffer doesn't end
23721 ;; with a newline character.
23722 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23723 (org-element-property :begin next-elem)))
23724 (size-blank (- (org-element-property :end elem)
23725 (save-excursion
23726 (goto-char (org-element-property :end elem))
23727 (skip-chars-backward " \r\t\n")
23728 (forward-line)
23729 (point)))))
23730 (org-element-swap-A-B elem next-elem)
23731 (goto-char (+ pos size-next size-blank))))))
23733 (defun org-drag-line-forward (arg)
23734 "Drag the line at point ARG lines forward."
23735 (interactive "p")
23736 (dotimes (n (abs arg))
23737 (let ((c (current-column)))
23738 (if (< 0 arg)
23739 (progn
23740 (beginning-of-line 2)
23741 (transpose-lines 1)
23742 (beginning-of-line 0))
23743 (transpose-lines 1)
23744 (beginning-of-line -1))
23745 (org-move-to-column c))))
23747 (defun org-drag-line-backward (arg)
23748 "Drag the line at point ARG lines backward."
23749 (interactive "p")
23750 (org-drag-line-forward (- arg)))
23752 (defun org-mark-element ()
23753 "Put point at beginning of this element, mark at end.
23755 Interactively, if this command is repeated or (in Transient Mark
23756 mode) if the mark is active, it marks the next element after the
23757 ones already marked."
23758 (interactive)
23759 (let (deactivate-mark)
23760 (if (and (org-called-interactively-p 'any)
23761 (or (and (eq last-command this-command) (mark t))
23762 (and transient-mark-mode mark-active)))
23763 (set-mark
23764 (save-excursion
23765 (goto-char (mark))
23766 (goto-char (org-element-property :end (org-element-at-point)))))
23767 (let ((element (org-element-at-point)))
23768 (end-of-line)
23769 (push-mark (org-element-property :end element) t t)
23770 (goto-char (org-element-property :begin element))))))
23772 (defun org-narrow-to-element ()
23773 "Narrow buffer to current element."
23774 (interactive)
23775 (let ((elem (org-element-at-point)))
23776 (cond
23777 ((eq (car elem) 'headline)
23778 (narrow-to-region
23779 (org-element-property :begin elem)
23780 (org-element-property :end elem)))
23781 ((memq (car elem) org-element-greater-elements)
23782 (narrow-to-region
23783 (org-element-property :contents-begin elem)
23784 (org-element-property :contents-end elem)))
23786 (narrow-to-region
23787 (org-element-property :begin elem)
23788 (org-element-property :end elem))))))
23790 (defun org-transpose-element ()
23791 "Transpose current and previous elements, keeping blank lines between.
23792 Point is moved after both elements."
23793 (interactive)
23794 (org-skip-whitespace)
23795 (let ((end (org-element-property :end (org-element-at-point))))
23796 (org-drag-element-backward)
23797 (goto-char end)))
23799 (defun org-unindent-buffer ()
23800 "Un-indent the visible part of the buffer.
23801 Relative indentation (between items, inside blocks, etc.) isn't
23802 modified."
23803 (interactive)
23804 (unless (eq major-mode 'org-mode)
23805 (user-error "Cannot un-indent a buffer not in Org mode"))
23806 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23807 unindent-tree ; For byte-compiler.
23808 (unindent-tree
23809 (function
23810 (lambda (contents)
23811 (mapc
23812 (lambda (element)
23813 (if (memq (org-element-type element) '(headline section))
23814 (funcall unindent-tree (org-element-contents element))
23815 (save-excursion
23816 (save-restriction
23817 (narrow-to-region
23818 (org-element-property :begin element)
23819 (org-element-property :end element))
23820 (org-do-remove-indentation)))))
23821 (reverse contents))))))
23822 (funcall unindent-tree (org-element-contents parse-tree))))
23824 (defun org-show-subtree ()
23825 "Show everything after this heading at deeper levels."
23826 (interactive)
23827 (outline-flag-region
23828 (point)
23829 (save-excursion
23830 (org-end-of-subtree t t))
23831 nil))
23833 (defun org-show-entry ()
23834 "Show the body directly following this heading.
23835 Show the heading too, if it is currently invisible."
23836 (interactive)
23837 (save-excursion
23838 (condition-case nil
23839 (progn
23840 (org-back-to-heading t)
23841 (outline-flag-region
23842 (max (point-min) (1- (point)))
23843 (save-excursion
23844 (if (re-search-forward
23845 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23846 (match-beginning 1)
23847 (point-max)))
23848 nil)
23849 (org-cycle-hide-drawers 'children))
23850 (error nil))))
23852 (defun org-make-options-regexp (kwds &optional extra)
23853 "Make a regular expression for keyword lines."
23854 (concat
23855 "^#\\+\\("
23856 (mapconcat 'regexp-quote kwds "\\|")
23857 (if extra (concat "\\|" extra))
23858 "\\):[ \t]*\\(.*\\)"))
23860 ;; Make isearch reveal the necessary context
23861 (defun org-isearch-end ()
23862 "Reveal context after isearch exits."
23863 (when isearch-success ; only if search was successful
23864 (if (featurep 'xemacs)
23865 ;; Under XEmacs, the hook is run in the correct place,
23866 ;; we directly show the context.
23867 (org-show-context 'isearch)
23868 ;; In Emacs the hook runs *before* restoring the overlays.
23869 ;; So we have to use a one-time post-command-hook to do this.
23870 ;; (Emacs 22 has a special variable, see function `org-mode')
23871 (unless (and (boundp 'isearch-mode-end-hook-quit)
23872 isearch-mode-end-hook-quit)
23873 ;; Only when the isearch was not quitted.
23874 (org-add-hook 'post-command-hook 'org-isearch-post-command
23875 'append 'local)))
23876 (org-fix-ellipsis-at-bol)))
23878 (defun org-isearch-post-command ()
23879 "Remove self from hook, and show context."
23880 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23881 (org-show-context 'isearch))
23884 ;;;; Integration with and fixes for other packages
23886 ;;; Imenu support
23888 (defvar org-imenu-markers nil
23889 "All markers currently used by Imenu.")
23890 (make-variable-buffer-local 'org-imenu-markers)
23892 (defun org-imenu-new-marker (&optional pos)
23893 "Return a new marker for use by Imenu, and remember the marker."
23894 (let ((m (make-marker)))
23895 (move-marker m (or pos (point)))
23896 (push m org-imenu-markers)
23899 (defun org-imenu-get-tree ()
23900 "Produce the index for Imenu."
23901 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23902 (setq org-imenu-markers nil)
23903 (let* ((n org-imenu-depth)
23904 (re (concat "^" (org-get-limited-outline-regexp)))
23905 (subs (make-vector (1+ n) nil))
23906 (last-level 0)
23907 m level head0 head)
23908 (save-excursion
23909 (save-restriction
23910 (widen)
23911 (goto-char (point-max))
23912 (while (re-search-backward re nil t)
23913 (setq level (org-reduced-level (funcall outline-level)))
23914 (when (and (<= level n)
23915 (looking-at org-complex-heading-regexp)
23916 (setq head0 (org-match-string-no-properties 4)))
23917 (setq head (org-link-display-format head0)
23918 m (org-imenu-new-marker))
23919 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23920 (if (>= level last-level)
23921 (push (cons head m) (aref subs level))
23922 (push (cons head (aref subs (1+ level))) (aref subs level))
23923 (loop for i from (1+ level) to n do (aset subs i nil)))
23924 (setq last-level level)))))
23925 (aref subs 1)))
23927 (eval-after-load "imenu"
23928 '(progn
23929 (add-hook 'imenu-after-jump-hook
23930 (lambda ()
23931 (if (derived-mode-p 'org-mode)
23932 (org-show-context 'org-goto))))))
23934 (defun org-link-display-format (link)
23935 "Replace a link with its the description.
23936 If there is no description, use the link target."
23937 (save-match-data
23938 (if (string-match org-bracket-link-analytic-regexp link)
23939 (replace-match (if (match-end 5)
23940 (match-string 5 link)
23941 (concat (match-string 1 link)
23942 (match-string 3 link)))
23943 nil t link)
23944 link)))
23946 (defun org-toggle-link-display ()
23947 "Toggle the literal or descriptive display of links."
23948 (interactive)
23949 (if org-descriptive-links
23950 (progn (org-remove-from-invisibility-spec '(org-link))
23951 (org-restart-font-lock)
23952 (setq org-descriptive-links nil))
23953 (progn (add-to-invisibility-spec '(org-link))
23954 (org-restart-font-lock)
23955 (setq org-descriptive-links t))))
23957 ;; Speedbar support
23959 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23960 "Overlay marking the agenda restriction line in speedbar.")
23961 (overlay-put org-speedbar-restriction-lock-overlay
23962 'face 'org-agenda-restriction-lock)
23963 (overlay-put org-speedbar-restriction-lock-overlay
23964 'help-echo "Agendas are currently limited to this item.")
23965 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23967 (defun org-speedbar-set-agenda-restriction ()
23968 "Restrict future agenda commands to the location at point in speedbar.
23969 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23970 (interactive)
23971 (require 'org-agenda)
23972 (let (p m tp np dir txt)
23973 (cond
23974 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23975 'org-imenu t))
23976 (setq m (get-text-property p 'org-imenu-marker))
23977 (with-current-buffer (marker-buffer m)
23978 (goto-char m)
23979 (org-agenda-set-restriction-lock 'subtree)))
23980 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23981 'speedbar-function 'speedbar-find-file))
23982 (setq tp (previous-single-property-change
23983 (1+ p) 'speedbar-function)
23984 np (next-single-property-change
23985 tp 'speedbar-function)
23986 dir (speedbar-line-directory)
23987 txt (buffer-substring-no-properties (or tp (point-min))
23988 (or np (point-max))))
23989 (with-current-buffer (find-file-noselect
23990 (let ((default-directory dir))
23991 (expand-file-name txt)))
23992 (unless (derived-mode-p 'org-mode)
23993 (user-error "Cannot restrict to non-Org-mode file"))
23994 (org-agenda-set-restriction-lock 'file)))
23995 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23996 (move-overlay org-speedbar-restriction-lock-overlay
23997 (point-at-bol) (point-at-eol))
23998 (setq current-prefix-arg nil)
23999 (org-agenda-maybe-redo)))
24001 (defvar speedbar-file-key-map)
24002 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24003 (eval-after-load "speedbar"
24004 '(progn
24005 (speedbar-add-supported-extension ".org")
24006 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24007 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24008 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24009 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24010 (add-hook 'speedbar-visiting-tag-hook
24011 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24013 ;;; Fixes and Hacks for problems with other packages
24015 (defun org-mode-flyspell-verify ()
24016 "Function used for `flyspell-generic-check-word-predicate'."
24017 (if (org-at-heading-p)
24018 ;; At a headline or an inlinetask, check title only. This is
24019 ;; faster than relying on `org-element-at-point'.
24020 (and (save-excursion (beginning-of-line)
24021 (and (let ((case-fold-search t))
24022 (not (looking-at "\\*+ END[ \t]*$")))
24023 (looking-at org-complex-heading-regexp)))
24024 (match-beginning 4)
24025 (>= (point) (match-beginning 4))
24026 (or (not (match-beginning 5))
24027 (< (point) (match-beginning 5))))
24028 (let* ((element (org-element-at-point))
24029 (post-affiliated (org-element-property :post-affiliated element))
24030 (object-check
24031 (function
24032 ;; Non-nil if checks can be done for object at point.
24033 (lambda ()
24034 (let ((object (save-excursion
24035 (when (org-looking-at-p "\\>") (backward-char))
24036 (org-element-context element))))
24037 (case (org-element-type object)
24038 ;; Prevent checks in links due to keybinding conflict
24039 ;; with Flyspell.
24040 ((code entity export-snippet inline-babel-call
24041 inline-src-block line-break latex-fragment link macro
24042 statistics-cookie target timestamp verbatim)
24043 nil)
24044 (footnote-reference
24045 ;; Only in inline footnotes, within the definition.
24046 (and (eq (org-element-property :type object) 'inline)
24047 (< (save-excursion
24048 (goto-char (org-element-property :begin object))
24049 (search-forward ":" nil t 2))
24050 (point))))
24051 (otherwise t)))))))
24052 (cond
24053 ;; Ignore checks in all affiliated keywords but captions.
24054 ((and post-affiliated (< (point) post-affiliated))
24055 (and (save-excursion
24056 (beginning-of-line)
24057 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24058 (> (point) (match-end 0))
24059 (funcall object-check)))
24060 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24061 ((and org-log-into-drawer
24062 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24063 (parent element))
24064 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24065 (setq parent (org-element-property :parent parent)))
24066 (and parent
24067 (eq (compare-strings
24068 log nil nil
24069 (org-element-property :drawer-name parent) nil nil t)
24070 t))))
24071 nil)
24073 (case (org-element-type element)
24074 ((comment quote-section) t)
24075 (comment-block
24076 ;; Allow checks between block markers, not on them.
24077 (and (> (line-beginning-position)
24078 (org-element-property :post-affiliated element))
24079 (save-excursion
24080 (end-of-line)
24081 (skip-chars-forward " \r\t\n")
24082 (< (point) (org-element-property :end element)))))
24083 ;; Arbitrary list of keywords where checks are meaningful.
24084 ;; Make sure point is on the value part of the element.
24085 (keyword
24086 (and (member (org-element-property :key element)
24087 '("DESCRIPTION" "TITLE"))
24088 (< (save-excursion
24089 (beginning-of-line) (search-forward ":") (point))
24090 (point))))
24091 ;; Check is globally allowed in paragraphs verse blocks and
24092 ;; table rows (after affiliated keywords) but some objects
24093 ;; must not be affected.
24094 ((paragraph table-row verse-block)
24095 (and (>= (point) (org-element-property :contents-begin element))
24096 (< (point) (org-element-property :contents-end element))
24097 (funcall object-check)))))))))
24098 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24100 (defun org-remove-flyspell-overlays-in (beg end)
24101 "Remove flyspell overlays in region."
24102 (and (org-bound-and-true-p flyspell-mode)
24103 (fboundp 'flyspell-delete-region-overlays)
24104 (flyspell-delete-region-overlays beg end)))
24106 (defvar flyspell-delayed-commands)
24107 (eval-after-load "flyspell"
24108 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24110 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24111 (eval-after-load "bookmark"
24112 '(if (boundp 'bookmark-after-jump-hook)
24113 ;; We can use the hook
24114 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24115 ;; Hook not available, use advice
24116 (defadvice bookmark-jump (after org-make-visible activate)
24117 "Make the position visible."
24118 (org-bookmark-jump-unhide))))
24120 ;; Make sure saveplace shows the location if it was hidden
24121 (eval-after-load "saveplace"
24122 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24123 "Make the position visible."
24124 (org-bookmark-jump-unhide)))
24126 ;; Make sure ecb shows the location if it was hidden
24127 (eval-after-load "ecb"
24128 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24129 "Make hierarchy visible when jumping into location from ECB tree buffer."
24130 (if (derived-mode-p 'org-mode)
24131 (org-show-context))))
24133 (defun org-bookmark-jump-unhide ()
24134 "Unhide the current position, to show the bookmark location."
24135 (and (derived-mode-p 'org-mode)
24136 (or (outline-invisible-p)
24137 (save-excursion (goto-char (max (point-min) (1- (point))))
24138 (outline-invisible-p)))
24139 (org-show-context 'bookmark-jump)))
24141 ;; Make session.el ignore our circular variable
24142 (defvar session-globals-exclude)
24143 (eval-after-load "session"
24144 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24146 ;;;; Finish up
24148 (provide 'org)
24150 (run-hooks 'org-load-hook)
24152 ;;; org.el ends here