Merge branch 'maint'
[org-mode.git] / lisp / org.el
blobd237c7c375a7e39fb6f0290cb8ca9ac2709fc23d
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" shell)
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.
301 Interactively, or when MESSAGE is non-nil, show it in echo area.
302 With prefix argument, or when HERE is non-nil, insert it at point.
303 In non-interactive uses, a reduced version string is output unless
304 FULL is given."
305 (interactive (list current-prefix-arg t (not current-prefix-arg)))
306 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
307 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
308 (load-suffixes (list ".el"))
309 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
310 (org-trash (or
311 (and (fboundp 'org-release) (fboundp 'org-git-version))
312 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
313 (load-suffixes save-load-suffixes)
314 (org-version (org-release))
315 (git-version (org-git-version))
316 (version (format "Org-mode version %s (%s @ %s)"
317 org-version
318 git-version
319 (if org-install-dir
320 (if (string= org-dir org-install-dir)
321 org-install-dir
322 (concat "mixed installation! " org-install-dir " and " org-dir))
323 "org-loaddefs.el can not be found!")))
324 (version1 (if full version org-version)))
325 (when here (insert version1))
326 (when message (message "%s" version1))
327 version1))
329 (defconst org-version (org-version))
332 ;;; Syntax Constants
334 ;;;; Block
336 (defconst org-block-regexp
337 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
338 "Regular expression for hiding blocks.")
340 (defconst org-dblock-start-re
341 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
342 "Matches the start line of a dynamic block, with parameters.")
344 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
345 "Matches the end of a dynamic block.")
347 ;;;; Clock and Planning
349 (defconst org-clock-string "CLOCK:"
350 "String used as prefix for timestamps clocking work hours on an item.")
352 (defconst org-closed-string "CLOSED:"
353 "String used as the prefix for timestamps logging closing a TODO entry.")
355 (defconst org-deadline-string "DEADLINE:"
356 "String to mark deadline entries.
357 A deadline is this string, followed by a time stamp. Should be a word,
358 terminated by a colon. You can insert a schedule keyword and
359 a timestamp with \\[org-deadline].")
361 (defconst org-scheduled-string "SCHEDULED:"
362 "String to mark scheduled TODO entries.
363 A schedule is this string, followed by a time stamp. Should be a word,
364 terminated by a colon. You can insert a schedule keyword and
365 a timestamp with \\[org-schedule].")
367 (defconst org-planning-or-clock-line-re
368 (concat "^[ \t]*"
369 (regexp-opt
370 (list org-clock-string org-closed-string org-deadline-string
371 org-scheduled-string)
373 "Matches a line with planning or clock info.
374 Matched keyword is in group 1.")
376 ;;;; Drawer
378 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
379 "Matches first or last line of a hidden block.
380 Group 1 contains drawer's name or \"END\".")
382 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
383 "Regular expression matching the first line of a property drawer.")
385 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
386 "Regular expression matching the last line of a property drawer.")
388 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
389 "Regular expression matching the first line of a clock drawer.")
391 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
392 "Regular expression matching the last line of a clock drawer.")
394 (defconst org-property-drawer-re
395 (concat "\\(" org-property-start-re "\\)[^\000]*?\\("
396 org-property-end-re "\\)\n?")
397 "Matches an entire property drawer.")
399 (defconst org-clock-drawer-re
400 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
401 org-clock-drawer-end-re "\\)\n?")
402 "Matches an entire clock drawer.")
404 ;;;; Headline
406 (defconst org-heading-keyword-regexp-format
407 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
408 "Printf format for a regexp matching a headline with some keyword.
409 This regexp will match the headline of any node which has the
410 exact keyword that is put into the format. The keyword isn't in
411 any group by default, but the stars and the body are.")
413 (defconst org-heading-keyword-maybe-regexp-format
414 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
415 "Printf format for a regexp matching a headline, possibly with some keyword.
416 This regexp can match any headline with the specified keyword, or
417 without a keyword. The keyword isn't in any group by default,
418 but the stars and the body are.")
420 (defconst org-archive-tag "ARCHIVE"
421 "The tag that marks a subtree as archived.
422 An archived subtree does not open during visibility cycling, and does
423 not contribute to the agenda listings.")
425 (defconst org-comment-string "COMMENT"
426 "Entries starting with this keyword will never be exported.
427 An entry can be toggled between COMMENT and normal with
428 \\[org-toggle-comment].")
431 ;;;; LaTeX Environments and Fragments
433 (defconst org-latex-regexps
434 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
435 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
436 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
437 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
438 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
439 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
440 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
441 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
442 "Regular expressions for matching embedded LaTeX.")
444 ;;;; Node Property
446 (defconst org-effort-property "Effort"
447 "The property that is being used to keep track of effort estimates.
448 Effort estimates given in this property need to have the format H:MM.")
450 ;;;; Table
452 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
453 "Detect an org-type or table-type table.")
455 (defconst org-table-line-regexp "^[ \t]*|"
456 "Detect an org-type table line.")
458 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
459 "Detect an org-type table line.")
461 (defconst org-table-hline-regexp "^[ \t]*|-"
462 "Detect an org-type table hline.")
464 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
465 "Detect a table-type table hline.")
467 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
468 "Detect the first line outside a table when searching from within it.
469 This works for both table types.")
471 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
472 "Detect a #+TBLFM line.")
474 ;;;; Timestamp
476 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
477 "Regular expression for fast time stamp matching.")
479 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
480 "Regular expression for fast time stamp matching.")
482 (defconst org-ts-regexp0
483 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
484 "Regular expression matching time strings for analysis.
485 This one does not require the space after the date, so it can be used
486 on a string that terminates immediately after the date.")
488 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
489 "Regular expression matching time strings for analysis.")
491 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
492 "Regular expression matching time stamps, with groups.")
494 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
495 "Regular expression matching time stamps (also [..]), with groups.")
497 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
498 "Regular expression matching a time stamp range.")
500 (defconst org-tr-regexp-both
501 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
502 "Regular expression matching a time stamp range.")
504 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
505 org-ts-regexp "\\)?")
506 "Regular expression matching a time stamp or time stamp range.")
508 (defconst org-tsr-regexp-both
509 (concat org-ts-regexp-both "\\(--?-?"
510 org-ts-regexp-both "\\)?")
511 "Regular expression matching a time stamp or time stamp range.
512 The time stamps may be either active or inactive.")
514 (defconst org-repeat-re
515 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
516 "Regular expression for specifying repeated events.
517 After a match, group 1 contains the repeat expression.")
519 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
520 "Formats for `format-time-string' which are used for time stamps.")
523 ;;; The custom variables
525 (defgroup org nil
526 "Outline-based notes management and organizer."
527 :tag "Org"
528 :group 'outlines
529 :group 'calendar)
531 (defcustom org-mode-hook nil
532 "Mode hook for Org-mode, run after the mode was turned on."
533 :group 'org
534 :type 'hook)
536 (defcustom org-load-hook nil
537 "Hook that is run after org.el has been loaded."
538 :group 'org
539 :type 'hook)
541 (defcustom org-log-buffer-setup-hook nil
542 "Hook that is run after an Org log buffer is created."
543 :group 'org
544 :version "24.1"
545 :type 'hook)
547 (defvar org-modules) ; defined below
548 (defvar org-modules-loaded nil
549 "Have the modules been loaded already?")
551 (defun org-load-modules-maybe (&optional force)
552 "Load all extensions listed in `org-modules'."
553 (when (or force (not org-modules-loaded))
554 (mapc (lambda (ext)
555 (condition-case nil (require ext)
556 (error (message "Problems while trying to load feature `%s'" ext))))
557 org-modules)
558 (setq org-modules-loaded t)))
560 (defun org-set-modules (var value)
561 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
562 (set var value)
563 (when (featurep 'org)
564 (org-load-modules-maybe 'force)
565 (org-element-cache-reset 'all)))
567 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
568 "Modules that should always be loaded together with org.el.
570 If a description starts with <C>, the file is not part of Emacs
571 and loading it will require that you have downloaded and properly
572 installed the Org mode distribution.
574 You can also use this system to load external packages (i.e. neither Org
575 core modules, nor modules from the CONTRIB directory). Just add symbols
576 to the end of the list. If the package is called org-xyz.el, then you need
577 to add the symbol `xyz', and the package must have a call to:
579 \(provide 'org-xyz)
581 For export specific modules, see also `org-export-backends'."
582 :group 'org
583 :set 'org-set-modules
584 :version "24.4"
585 :package-version '(Org . "8.0")
586 :type
587 '(set :greedy t
588 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
589 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
590 (const :tag " crypt: Encryption of subtrees" org-crypt)
591 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
592 (const :tag " docview: Links to doc-view buffers" org-docview)
593 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
594 (const :tag " habit: Track your consistency with habits" org-habit)
595 (const :tag " id: Global IDs for identifying entries" org-id)
596 (const :tag " info: Links to Info nodes" org-info)
597 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
598 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
599 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
600 (const :tag " mouse: Additional mouse support" org-mouse)
601 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
602 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
603 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
605 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
606 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
607 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
608 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
609 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
610 (const :tag "C collector: Collect properties into tables" org-collector)
611 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
612 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
613 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
614 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
615 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
616 (const :tag "C eval: Include command output as text" org-eval)
617 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
618 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
619 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
620 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
621 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
622 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
623 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
624 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
625 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
626 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
627 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
628 (const :tag "C mew: Links to Mew folders/messages" org-mew)
629 (const :tag "C mtags: Support for muse-like tags" org-mtags)
630 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
631 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
632 (const :tag "C registry: A registry for Org-mode links" org-registry)
633 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
634 (const :tag "C secretary: Team management with org-mode" org-secretary)
635 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
636 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
637 (const :tag "C track: Keep up with Org-mode development" org-track)
638 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
639 (const :tag "C vm: Links to VM folders/messages" org-vm)
640 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
641 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
642 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
644 (defvar org-export--registered-backends) ; From ox.el.
645 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
646 (declare-function org-export-backend-name "ox" (backend))
647 (defcustom org-export-backends '(ascii html icalendar latex)
648 "List of export back-ends that should be always available.
650 If a description starts with <C>, the file is not part of Emacs
651 and loading it will require that you have downloaded and properly
652 installed the Org mode distribution.
654 Unlike to `org-modules', libraries in this list will not be
655 loaded along with Org, but only once the export framework is
656 needed.
658 This variable needs to be set before org.el is loaded. If you
659 need to make a change while Emacs is running, use the customize
660 interface or run the following code, where VAL stands for the new
661 value of the variable, after updating it:
663 \(progn
664 \(setq org-export--registered-backends
665 \(org-remove-if-not
666 \(lambda (backend)
667 \(let ((name (org-export-backend-name backend)))
668 \(or (memq name val)
669 \(catch 'parentp
670 \(dolist (b val)
671 \(and (org-export-derived-backend-p b name)
672 \(throw 'parentp t)))))))
673 org-export--registered-backends))
674 \(let ((new-list (mapcar 'org-export-backend-name
675 org-export--registered-backends)))
676 \(dolist (backend val)
677 \(cond
678 \((not (load (format \"ox-%s\" backend) t t))
679 \(message \"Problems while trying to load export back-end `%s'\"
680 backend))
681 \((not (memq backend new-list)) (push backend new-list))))
682 \(set-default 'org-export-backends new-list)))
684 Adding a back-end to this list will also pull the back-end it
685 depends on, if any."
686 :group 'org
687 :group 'org-export
688 :version "24.4"
689 :package-version '(Org . "8.0")
690 :initialize 'custom-initialize-set
691 :set (lambda (var val)
692 (if (not (featurep 'ox)) (set-default var val)
693 ;; Any back-end not required anymore (not present in VAL and not
694 ;; a parent of any back-end in the new value) is removed from the
695 ;; list of registered back-ends.
696 (setq org-export--registered-backends
697 (org-remove-if-not
698 (lambda (backend)
699 (let ((name (org-export-backend-name backend)))
700 (or (memq name val)
701 (catch 'parentp
702 (dolist (b val)
703 (and (org-export-derived-backend-p b name)
704 (throw 'parentp t)))))))
705 org-export--registered-backends))
706 ;; Now build NEW-LIST of both new back-ends and required
707 ;; parents.
708 (let ((new-list (mapcar 'org-export-backend-name
709 org-export--registered-backends)))
710 (dolist (backend val)
711 (cond
712 ((not (load (format "ox-%s" backend) t t))
713 (message "Problems while trying to load export back-end `%s'"
714 backend))
715 ((not (memq backend new-list)) (push backend new-list))))
716 ;; Set VAR to that list with fixed dependencies.
717 (set-default var new-list))))
718 :type '(set :greedy t
719 (const :tag " ascii Export buffer to ASCII format" ascii)
720 (const :tag " beamer Export buffer to Beamer presentation" beamer)
721 (const :tag " html Export buffer to HTML format" html)
722 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
723 (const :tag " latex Export buffer to LaTeX format" latex)
724 (const :tag " man Export buffer to MAN format" man)
725 (const :tag " md Export buffer to Markdown format" md)
726 (const :tag " odt Export buffer to ODT format" odt)
727 (const :tag " org Export buffer to Org format" org)
728 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
729 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
730 (const :tag "C deck Export buffer to deck.js presentations" deck)
731 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
732 (const :tag "C groff Export buffer to Groff format" groff)
733 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
734 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
735 (const :tag "C s5 Export buffer to s5 presentations" s5)
736 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
738 (eval-after-load 'ox
739 '(mapc
740 (lambda (backend)
741 (condition-case nil (require (intern (format "ox-%s" backend)))
742 (error (message "Problems while trying to load export back-end `%s'"
743 backend))))
744 org-export-backends))
746 (defcustom org-support-shift-select nil
747 "Non-nil means make shift-cursor commands select text when possible.
749 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
750 start selecting a region, or enlarge regions started in this way.
751 In Org-mode, in special contexts, these same keys are used for
752 other purposes, important enough to compete with shift selection.
753 Org tries to balance these needs by supporting `shift-select-mode'
754 outside these special contexts, under control of this variable.
756 The default of this variable is nil, to avoid confusing behavior. Shifted
757 cursor keys will then execute Org commands in the following contexts:
758 - on a headline, changing TODO state (left/right) and priority (up/down)
759 - on a time stamp, changing the time
760 - in a plain list item, changing the bullet type
761 - in a property definition line, switching between allowed values
762 - in the BEGIN line of a clock table (changing the time block).
763 Outside these contexts, the commands will throw an error.
765 When this variable is t and the cursor is not in a special
766 context, Org-mode will support shift-selection for making and
767 enlarging regions. To make this more effective, the bullet
768 cycling will no longer happen anywhere in an item line, but only
769 if the cursor is exactly on the bullet.
771 If you set this variable to the symbol `always', then the keys
772 will not be special in headlines, property lines, and item lines,
773 to make shift selection work there as well. If this is what you
774 want, you can use the following alternative commands: `C-c C-t'
775 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
776 can be used to switch TODO sets, `C-c -' to cycle item bullet
777 types, and properties can be edited by hand or in column view.
779 However, when the cursor is on a timestamp, shift-cursor commands
780 will still edit the time stamp - this is just too good to give up.
782 XEmacs user should have this variable set to nil, because
783 `shift-select-mode' is in Emacs 23 or later only."
784 :group 'org
785 :type '(choice
786 (const :tag "Never" nil)
787 (const :tag "When outside special context" t)
788 (const :tag "Everywhere except timestamps" always)))
790 (defcustom org-loop-over-headlines-in-active-region nil
791 "Shall some commands act upon headlines in the active region?
793 When set to `t', some commands will be performed in all headlines
794 within the active region.
796 When set to `start-level', some commands will be performed in all
797 headlines within the active region, provided that these headlines
798 are of the same level than the first one.
800 When set to a string, those commands will be performed on the
801 matching headlines within the active region. Such string must be
802 a tags/property/todo match as it is used in the agenda tags view.
804 The list of commands is: `org-schedule', `org-deadline',
805 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
806 `org-archive-to-archive-sibling'. The archiving commands skip
807 already archived entries."
808 :type '(choice (const :tag "Don't loop" nil)
809 (const :tag "All headlines in active region" t)
810 (const :tag "In active region, headlines at the same level than the first one" start-level)
811 (string :tag "Tags/Property/Todo matcher"))
812 :version "24.1"
813 :group 'org-todo
814 :group 'org-archive)
816 (defgroup org-startup nil
817 "Options concerning startup of Org-mode."
818 :tag "Org Startup"
819 :group 'org)
821 (defcustom org-startup-folded t
822 "Non-nil means entering Org-mode will switch to OVERVIEW.
823 This can also be configured on a per-file basis by adding one of
824 the following lines anywhere in the buffer:
826 #+STARTUP: fold (or `overview', this is equivalent)
827 #+STARTUP: nofold (or `showall', this is equivalent)
828 #+STARTUP: content
829 #+STARTUP: showeverything
831 By default, this option is ignored when Org opens agenda files
832 for the first time. If you want the agenda to honor the startup
833 option, set `org-agenda-inhibit-startup' to nil."
834 :group 'org-startup
835 :type '(choice
836 (const :tag "nofold: show all" nil)
837 (const :tag "fold: overview" t)
838 (const :tag "content: all headlines" content)
839 (const :tag "show everything, even drawers" showeverything)))
841 (defcustom org-startup-truncated t
842 "Non-nil means entering Org-mode will set `truncate-lines'.
843 This is useful since some lines containing links can be very long and
844 uninteresting. Also tables look terrible when wrapped."
845 :group 'org-startup
846 :type 'boolean)
848 (defcustom org-startup-indented nil
849 "Non-nil means turn on `org-indent-mode' on startup.
850 This can also be configured on a per-file basis by adding one of
851 the following lines anywhere in the buffer:
853 #+STARTUP: indent
854 #+STARTUP: noindent"
855 :group 'org-structure
856 :type '(choice
857 (const :tag "Not" nil)
858 (const :tag "Globally (slow on startup in large files)" t)))
860 (defcustom org-use-sub-superscripts t
861 "Non-nil means interpret \"_\" and \"^\" for display.
863 If you want to control how Org exports those characters, see
864 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
865 used to be an alias for `org-export-with-sub-superscripts' in
866 Org <8.0, it is not anymore.
868 When this option is turned on, you can use TeX-like syntax for
869 sub- and superscripts within the buffer. Several characters after
870 \"_\" or \"^\" will be considered as a single item - so grouping
871 with {} is normally not needed. For example, the following things
872 will be parsed as single sub- or superscripts:
874 10^24 or 10^tau several digits will be considered 1 item.
875 10^-12 or 10^-tau a leading sign with digits or a word
876 x^2-y^3 will be read as x^2 - y^3, because items are
877 terminated by almost any nonword/nondigit char.
878 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
880 Still, ambiguity is possible. So when in doubt, use {} to enclose
881 the sub/superscript. If you set this variable to the symbol `{}',
882 the braces are *required* in order to trigger interpretations as
883 sub/superscript. This can be helpful in documents that need \"_\"
884 frequently in plain text."
885 :group 'org-startup
886 :version "24.4"
887 :package-version '(Org . "8.0")
888 :type '(choice
889 (const :tag "Always interpret" t)
890 (const :tag "Only with braces" {})
891 (const :tag "Never interpret" nil)))
893 (defcustom org-startup-with-beamer-mode nil
894 "Non-nil means turn on `org-beamer-mode' on startup.
895 This can also be configured on a per-file basis by adding one of
896 the following lines anywhere in the buffer:
898 #+STARTUP: beamer"
899 :group 'org-startup
900 :version "24.1"
901 :type 'boolean)
903 (defcustom org-startup-align-all-tables nil
904 "Non-nil means align all tables when visiting a file.
905 This is useful when the column width in tables is forced with <N> cookies
906 in table fields. Such tables will look correct only after the first re-align.
907 This can also be configured on a per-file basis by adding one of
908 the following lines anywhere in the buffer:
909 #+STARTUP: align
910 #+STARTUP: noalign"
911 :group 'org-startup
912 :type 'boolean)
914 (defcustom org-startup-with-inline-images nil
915 "Non-nil means show inline images when loading a new Org file.
916 This can also be configured on a per-file basis by adding one of
917 the following lines anywhere in the buffer:
918 #+STARTUP: inlineimages
919 #+STARTUP: noinlineimages"
920 :group 'org-startup
921 :version "24.1"
922 :type 'boolean)
924 (defcustom org-startup-with-latex-preview nil
925 "Non-nil means preview LaTeX fragments when loading a new Org file.
927 This can also be configured on a per-file basis by adding one of
928 the following lines anywhere in the buffer:
929 #+STARTUP: latexpreview
930 #+STARTUP: nolatexpreview"
931 :group 'org-startup
932 :version "24.4"
933 :package-version '(Org . "8.0")
934 :type 'boolean)
936 (defcustom org-insert-mode-line-in-empty-file nil
937 "Non-nil means insert the first line setting Org-mode in empty files.
938 When the function `org-mode' is called interactively in an empty file, this
939 normally means that the file name does not automatically trigger Org-mode.
940 To ensure that the file will always be in Org-mode in the future, a
941 line enforcing Org-mode will be inserted into the buffer, if this option
942 has been set."
943 :group 'org-startup
944 :type 'boolean)
946 (defcustom org-replace-disputed-keys nil
947 "Non-nil means use alternative key bindings for some keys.
948 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
949 These keys are also used by other packages like shift-selection-mode'
950 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
951 If you want to use Org-mode together with one of these other modes,
952 or more generally if you would like to move some Org-mode commands to
953 other keys, set this variable and configure the keys with the variable
954 `org-disputed-keys'.
956 This option is only relevant at load-time of Org-mode, and must be set
957 *before* org.el is loaded. Changing it requires a restart of Emacs to
958 become effective."
959 :group 'org-startup
960 :type 'boolean)
962 (defcustom org-use-extra-keys nil
963 "Non-nil means use extra key sequence definitions for certain commands.
964 This happens automatically if you run XEmacs or if `window-system'
965 is nil. This variable lets you do the same manually. You must
966 set it before loading org.
968 Example: on Carbon Emacs 22 running graphically, with an external
969 keyboard on a Powerbook, the default way of setting M-left might
970 not work for either Alt or ESC. Setting this variable will make
971 it work for ESC."
972 :group 'org-startup
973 :type 'boolean)
975 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
977 (defcustom org-disputed-keys
978 '(([(shift up)] . [(meta p)])
979 ([(shift down)] . [(meta n)])
980 ([(shift left)] . [(meta -)])
981 ([(shift right)] . [(meta +)])
982 ([(control shift right)] . [(meta shift +)])
983 ([(control shift left)] . [(meta shift -)]))
984 "Keys for which Org-mode and other modes compete.
985 This is an alist, cars are the default keys, second element specifies
986 the alternative to use when `org-replace-disputed-keys' is t.
988 Keys can be specified in any syntax supported by `define-key'.
989 The value of this option takes effect only at Org-mode's startup,
990 therefore you'll have to restart Emacs to apply it after changing."
991 :group 'org-startup
992 :type 'alist)
994 (defun org-key (key)
995 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
996 Or return the original if not disputed.
997 Also apply the translations defined in `org-xemacs-key-equivalents'."
998 (when org-replace-disputed-keys
999 (let* ((nkey (key-description key))
1000 (x (org-find-if (lambda (x)
1001 (equal (key-description (car x)) nkey))
1002 org-disputed-keys)))
1003 (setq key (if x (cdr x) key))))
1004 (when (featurep 'xemacs)
1005 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1006 key)
1008 (defun org-find-if (predicate seq)
1009 (catch 'exit
1010 (while seq
1011 (if (funcall predicate (car seq))
1012 (throw 'exit (car seq))
1013 (pop seq)))))
1015 (defun org-defkey (keymap key def)
1016 "Define a key, possibly translated, as returned by `org-key'."
1017 (define-key keymap (org-key key) def))
1019 (defcustom org-ellipsis nil
1020 "The ellipsis to use in the Org-mode outline.
1021 When nil, just use the standard three dots.
1022 When a string, use that string instead.
1023 When a face, use the standard 3 dots, but with the specified face.
1024 The change affects only Org-mode (which will then use its own display table).
1025 Changing this requires executing `M-x org-mode RET' in a buffer to become
1026 effective."
1027 :group 'org-startup
1028 :type '(choice (const :tag "Default" nil)
1029 (face :tag "Face" :value org-warning)
1030 (string :tag "String" :value "...#")))
1032 (defvar org-display-table nil
1033 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1035 (defgroup org-keywords nil
1036 "Keywords in Org-mode."
1037 :tag "Org Keywords"
1038 :group 'org)
1040 (defcustom org-closed-keep-when-no-todo nil
1041 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1042 :group 'org-todo
1043 :group 'org-keywords
1044 :version "24.4"
1045 :package-version '(Org . "8.0")
1046 :type 'boolean)
1048 (defgroup org-structure nil
1049 "Options concerning the general structure of Org-mode files."
1050 :tag "Org Structure"
1051 :group 'org)
1053 (defgroup org-reveal-location nil
1054 "Options about how to make context of a location visible."
1055 :tag "Org Reveal Location"
1056 :group 'org-structure)
1058 (defconst org-context-choice
1059 '(choice
1060 (const :tag "Always" t)
1061 (const :tag "Never" nil)
1062 (repeat :greedy t :tag "Individual contexts"
1063 (cons
1064 (choice :tag "Context"
1065 (const agenda)
1066 (const org-goto)
1067 (const occur-tree)
1068 (const tags-tree)
1069 (const link-search)
1070 (const mark-goto)
1071 (const bookmark-jump)
1072 (const isearch)
1073 (const default))
1074 (boolean))))
1075 "Contexts for the reveal options.")
1077 (defcustom org-show-hierarchy-above '((default . t))
1078 "Non-nil means show full hierarchy when revealing a location.
1079 Org-mode often shows locations in an org-mode file which might have
1080 been invisible before. When this is set, the hierarchy of headings
1081 above the exposed location is shown.
1082 Turning this off for example for sparse trees makes them very compact.
1083 Instead of t, this can also be an alist specifying this option for different
1084 contexts. Valid contexts are
1085 agenda when exposing an entry from the agenda
1086 org-goto when using the command `org-goto' on key C-c C-j
1087 occur-tree when using the command `org-occur' on key C-c /
1088 tags-tree when constructing a sparse tree based on tags matches
1089 link-search when exposing search matches associated with a link
1090 mark-goto when exposing the jump goal of a mark
1091 bookmark-jump when exposing a bookmark location
1092 isearch when exiting from an incremental search
1093 default default for all contexts not set explicitly"
1094 :group 'org-reveal-location
1095 :type org-context-choice)
1097 (defcustom org-show-following-heading '((default . nil))
1098 "Non-nil means show following heading when revealing a location.
1099 Org-mode often shows locations in an org-mode file which might have
1100 been invisible before. When this is set, the heading following the
1101 match is shown.
1102 Turning this off for example for sparse trees makes them very compact,
1103 but makes it harder to edit the location of the match. In such a case,
1104 use the command \\[org-reveal] to show more context.
1105 Instead of t, this can also be an alist specifying this option for different
1106 contexts. See `org-show-hierarchy-above' for valid contexts."
1107 :group 'org-reveal-location
1108 :type org-context-choice)
1110 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
1111 "Non-nil means show all sibling heading when revealing a location.
1112 Org-mode often shows locations in an org-mode file which might have
1113 been invisible before. When this is set, the sibling of the current entry
1114 heading are all made visible. If `org-show-hierarchy-above' is t,
1115 the same happens on each level of the hierarchy above the current entry.
1117 By default this is on for the isearch context, off for all other contexts.
1118 Turning this off for example for sparse trees makes them very compact,
1119 but makes it harder to edit the location of the match. In such a case,
1120 use the command \\[org-reveal] to show more context.
1121 Instead of t, this can also be an alist specifying this option for different
1122 contexts. See `org-show-hierarchy-above' for valid contexts."
1123 :group 'org-reveal-location
1124 :type org-context-choice
1125 :version "24.4"
1126 :package-version '(Org . "8.0"))
1128 (defcustom org-show-entry-below '((default . nil))
1129 "Non-nil means show the entry below a headline when revealing a location.
1130 Org-mode often shows locations in an org-mode file which might have
1131 been invisible before. When this is set, the text below the headline that is
1132 exposed is also shown.
1134 By default this is off for all contexts.
1135 Instead of t, this can also be an alist specifying this option for different
1136 contexts. See `org-show-hierarchy-above' for valid contexts."
1137 :group 'org-reveal-location
1138 :type org-context-choice)
1140 (defcustom org-indirect-buffer-display 'other-window
1141 "How should indirect tree buffers be displayed?
1142 This applies to indirect buffers created with the commands
1143 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1144 Valid values are:
1145 current-window Display in the current window
1146 other-window Just display in another window.
1147 dedicated-frame Create one new frame, and re-use it each time.
1148 new-frame Make a new frame each time. Note that in this case
1149 previously-made indirect buffers are kept, and you need to
1150 kill these buffers yourself."
1151 :group 'org-structure
1152 :group 'org-agenda-windows
1153 :type '(choice
1154 (const :tag "In current window" current-window)
1155 (const :tag "In current frame, other window" other-window)
1156 (const :tag "Each time a new frame" new-frame)
1157 (const :tag "One dedicated frame" dedicated-frame)))
1159 (defcustom org-use-speed-commands nil
1160 "Non-nil means activate single letter commands at beginning of a headline.
1161 This may also be a function to test for appropriate locations where speed
1162 commands should be active.
1164 For example, to activate speed commands when the point is on any
1165 star at the beginning of the headline, you can do this:
1167 (setq org-use-speed-commands
1168 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1169 :group 'org-structure
1170 :type '(choice
1171 (const :tag "Never" nil)
1172 (const :tag "At beginning of headline stars" t)
1173 (function)))
1175 (defcustom org-speed-commands-user nil
1176 "Alist of additional speed commands.
1177 This list will be checked before `org-speed-commands-default'
1178 when the variable `org-use-speed-commands' is non-nil
1179 and when the cursor is at the beginning of a headline.
1180 The car if each entry is a string with a single letter, which must
1181 be assigned to `self-insert-command' in the global map.
1182 The cdr is either a command to be called interactively, a function
1183 to be called, or a form to be evaluated.
1184 An entry that is just a list with a single string will be interpreted
1185 as a descriptive headline that will be added when listing the speed
1186 commands in the Help buffer using the `?' speed command."
1187 :group 'org-structure
1188 :type '(repeat :value ("k" . ignore)
1189 (choice :value ("k" . ignore)
1190 (list :tag "Descriptive Headline" (string :tag "Headline"))
1191 (cons :tag "Letter and Command"
1192 (string :tag "Command letter")
1193 (choice
1194 (function)
1195 (sexp))))))
1197 (defcustom org-bookmark-names-plist
1198 '(:last-capture "org-capture-last-stored"
1199 :last-refile "org-refile-last-stored"
1200 :last-capture-marker "org-capture-last-stored-marker")
1201 "Names for bookmarks automatically set by some Org commands.
1202 This can provide strings as names for a number of bookmarks Org sets
1203 automatically. The following keys are currently implemented:
1204 :last-capture
1205 :last-capture-marker
1206 :last-refile
1207 When a key does not show up in the property list, the corresponding bookmark
1208 is not set."
1209 :group 'org-structure
1210 :type 'plist)
1212 (defgroup org-cycle nil
1213 "Options concerning visibility cycling in Org-mode."
1214 :tag "Org Cycle"
1215 :group 'org-structure)
1217 (defcustom org-cycle-skip-children-state-if-no-children t
1218 "Non-nil means skip CHILDREN state in entries that don't have any."
1219 :group 'org-cycle
1220 :type 'boolean)
1222 (defcustom org-cycle-max-level nil
1223 "Maximum level which should still be subject to visibility cycling.
1224 Levels higher than this will, for cycling, be treated as text, not a headline.
1225 When `org-odd-levels-only' is set, a value of N in this variable actually
1226 means 2N-1 stars as the limiting headline.
1227 When nil, cycle all levels.
1228 Note that the limiting level of cycling is also influenced by
1229 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1230 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1231 than its value."
1232 :group 'org-cycle
1233 :type '(choice
1234 (const :tag "No limit" nil)
1235 (integer :tag "Maximum level")))
1237 (defcustom org-hide-block-startup nil
1238 "Non-nil means entering Org-mode will fold all blocks.
1239 This can also be set in on a per-file basis with
1241 #+STARTUP: hideblocks
1242 #+STARTUP: showblocks"
1243 :group 'org-startup
1244 :group 'org-cycle
1245 :type 'boolean)
1247 (defcustom org-cycle-global-at-bob nil
1248 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1249 This makes it possible to do global cycling without having to use S-TAB or
1250 \\[universal-argument] TAB. For this special case to work, the first line
1251 of the buffer must not be a headline -- it may be empty or some other text.
1252 When used in this way, `org-cycle-hook' is disabled temporarily to make
1253 sure the cursor stays at the beginning of the buffer. When this option is
1254 nil, don't do anything special at the beginning of the buffer."
1255 :group 'org-cycle
1256 :type 'boolean)
1258 (defcustom org-cycle-level-after-item/entry-creation t
1259 "Non-nil means cycle entry level or item indentation in new empty entries.
1261 When the cursor is at the end of an empty headline, i.e., with only stars
1262 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1263 and then all possible ancestor states, before returning to the original state.
1264 This makes data entry extremely fast: M-RET to create a new headline,
1265 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1267 When the cursor is at the end of an empty plain list item, one TAB will
1268 make it a subitem, two or more tabs will back up to make this an item
1269 higher up in the item hierarchy."
1270 :group 'org-cycle
1271 :type 'boolean)
1273 (defcustom org-cycle-emulate-tab t
1274 "Where should `org-cycle' emulate TAB.
1275 nil Never
1276 white Only in completely white lines
1277 whitestart Only at the beginning of lines, before the first non-white char
1278 t Everywhere except in headlines
1279 exc-hl-bol Everywhere except at the start of a headline
1280 If TAB is used in a place where it does not emulate TAB, the current subtree
1281 visibility is cycled."
1282 :group 'org-cycle
1283 :type '(choice (const :tag "Never" nil)
1284 (const :tag "Only in completely white lines" white)
1285 (const :tag "Before first char in a line" whitestart)
1286 (const :tag "Everywhere except in headlines" t)
1287 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1289 (defcustom org-cycle-separator-lines 2
1290 "Number of empty lines needed to keep an empty line between collapsed trees.
1291 If you leave an empty line between the end of a subtree and the following
1292 headline, this empty line is hidden when the subtree is folded.
1293 Org-mode will leave (exactly) one empty line visible if the number of
1294 empty lines is equal or larger to the number given in this variable.
1295 So the default 2 means at least 2 empty lines after the end of a subtree
1296 are needed to produce free space between a collapsed subtree and the
1297 following headline.
1299 If the number is negative, and the number of empty lines is at least -N,
1300 all empty lines are shown.
1302 Special case: when 0, never leave empty lines in collapsed view."
1303 :group 'org-cycle
1304 :type 'integer)
1305 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1307 (defcustom org-pre-cycle-hook nil
1308 "Hook that is run before visibility cycling is happening.
1309 The function(s) in this hook must accept a single argument which indicates
1310 the new state that will be set right after running this hook. The
1311 argument is a symbol. Before a global state change, it can have the values
1312 `overview', `content', or `all'. Before a local state change, it can have
1313 the values `folded', `children', or `subtree'."
1314 :group 'org-cycle
1315 :type 'hook)
1317 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1318 org-cycle-hide-drawers
1319 org-cycle-hide-inline-tasks
1320 org-cycle-show-empty-lines
1321 org-optimize-window-after-visibility-change)
1322 "Hook that is run after `org-cycle' has changed the buffer visibility.
1323 The function(s) in this hook must accept a single argument which indicates
1324 the new state that was set by the most recent `org-cycle' command. The
1325 argument is a symbol. After a global state change, it can have the values
1326 `overview', `contents', or `all'. After a local state change, it can have
1327 the values `folded', `children', or `subtree'."
1328 :group 'org-cycle
1329 :type 'hook)
1331 (defgroup org-edit-structure nil
1332 "Options concerning structure editing in Org-mode."
1333 :tag "Org Edit Structure"
1334 :group 'org-structure)
1336 (defcustom org-odd-levels-only nil
1337 "Non-nil means skip even levels and only use odd levels for the outline.
1338 This has the effect that two stars are being added/taken away in
1339 promotion/demotion commands. It also influences how levels are
1340 handled by the exporters.
1341 Changing it requires restart of `font-lock-mode' to become effective
1342 for fontification also in regions already fontified.
1343 You may also set this on a per-file basis by adding one of the following
1344 lines to the buffer:
1346 #+STARTUP: odd
1347 #+STARTUP: oddeven"
1348 :group 'org-edit-structure
1349 :group 'org-appearance
1350 :type 'boolean)
1352 (defcustom org-adapt-indentation t
1353 "Non-nil means adapt indentation to outline node level.
1355 When this variable is set, Org assumes that you write outlines by
1356 indenting text in each node to align with the headline (after the stars).
1357 The following issues are influenced by this variable:
1359 - When this is set and the *entire* text in an entry is indented, the
1360 indentation is increased by one space in a demotion command, and
1361 decreased by one in a promotion command. If any line in the entry
1362 body starts with text at column 0, indentation is not changed at all.
1364 - Property drawers and planning information is inserted indented when
1365 this variable s set. When nil, they will not be indented.
1367 - TAB indents a line relative to context. The lines below a headline
1368 will be indented when this variable is set.
1370 Note that this is all about true indentation, by adding and removing
1371 space characters. See also `org-indent.el' which does level-dependent
1372 indentation in a virtual way, i.e. at display time in Emacs."
1373 :group 'org-edit-structure
1374 :type 'boolean)
1376 (defcustom org-special-ctrl-a/e nil
1377 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1379 When t, `C-a' will bring back the cursor to the beginning of the
1380 headline text, i.e. after the stars and after a possible TODO
1381 keyword. In an item, this will be the position after bullet and
1382 check-box, if any. When the cursor is already at that position,
1383 another `C-a' will bring it to the beginning of the line.
1385 `C-e' will jump to the end of the headline, ignoring the presence
1386 of tags in the headline. A second `C-e' will then jump to the
1387 true end of the line, after any tags. This also means that, when
1388 this variable is non-nil, `C-e' also will never jump beyond the
1389 end of the heading of a folded section, i.e. not after the
1390 ellipses.
1392 When set to the symbol `reversed', the first `C-a' or `C-e' works
1393 normally, going to the true line boundary first. Only a directly
1394 following, identical keypress will bring the cursor to the
1395 special positions.
1397 This may also be a cons cell where the behavior for `C-a' and
1398 `C-e' is set separately."
1399 :group 'org-edit-structure
1400 :type '(choice
1401 (const :tag "off" nil)
1402 (const :tag "on: after stars/bullet and before tags first" t)
1403 (const :tag "reversed: true line boundary first" reversed)
1404 (cons :tag "Set C-a and C-e separately"
1405 (choice :tag "Special C-a"
1406 (const :tag "off" nil)
1407 (const :tag "on: after stars/bullet first" t)
1408 (const :tag "reversed: before stars/bullet first" reversed))
1409 (choice :tag "Special C-e"
1410 (const :tag "off" nil)
1411 (const :tag "on: before tags first" t)
1412 (const :tag "reversed: after tags first" reversed)))))
1413 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1415 (defcustom org-special-ctrl-k nil
1416 "Non-nil means `C-k' will behave specially in headlines.
1417 When nil, `C-k' will call the default `kill-line' command.
1418 When t, the following will happen while the cursor is in the headline:
1420 - When the cursor is at the beginning of a headline, kill the entire
1421 line and possible the folded subtree below the line.
1422 - When in the middle of the headline text, kill the headline up to the tags.
1423 - When after the headline text, kill the tags."
1424 :group 'org-edit-structure
1425 :type 'boolean)
1427 (defcustom org-ctrl-k-protect-subtree nil
1428 "Non-nil means, do not delete a hidden subtree with C-k.
1429 When set to the symbol `error', simply throw an error when C-k is
1430 used to kill (part-of) a headline that has hidden text behind it.
1431 Any other non-nil value will result in a query to the user, if it is
1432 OK to kill that hidden subtree. When nil, kill without remorse."
1433 :group 'org-edit-structure
1434 :version "24.1"
1435 :type '(choice
1436 (const :tag "Do not protect hidden subtrees" nil)
1437 (const :tag "Protect hidden subtrees with a security query" t)
1438 (const :tag "Never kill a hidden subtree with C-k" error)))
1440 (defcustom org-special-ctrl-o t
1441 "Non-nil means, make `C-o' insert a row in tables."
1442 :group 'org-edit-structure
1443 :type 'boolean)
1445 (defcustom org-catch-invisible-edits nil
1446 "Check if in invisible region before inserting or deleting a character.
1447 Valid values are:
1449 nil Do not check, so just do invisible edits.
1450 error Throw an error and do nothing.
1451 show Make point visible, and do the requested edit.
1452 show-and-error Make point visible, then throw an error and abort the edit.
1453 smart Make point visible, and do insertion/deletion if it is
1454 adjacent to visible text and the change feels predictable.
1455 Never delete a previously invisible character or add in the
1456 middle or right after an invisible region. Basically, this
1457 allows insertion and backward-delete right before ellipses.
1458 FIXME: maybe in this case we should not even show?"
1459 :group 'org-edit-structure
1460 :version "24.1"
1461 :type '(choice
1462 (const :tag "Do not check" nil)
1463 (const :tag "Throw error when trying to edit" error)
1464 (const :tag "Unhide, but do not do the edit" show-and-error)
1465 (const :tag "Show invisible part and do the edit" show)
1466 (const :tag "Be smart and do the right thing" smart)))
1468 (defcustom org-yank-folded-subtrees t
1469 "Non-nil means when yanking subtrees, fold them.
1470 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1471 it starts with a heading and all other headings in it are either children
1472 or siblings, then fold all the subtrees. However, do this only if no
1473 text after the yank would be swallowed into a folded tree by this action."
1474 :group 'org-edit-structure
1475 :type 'boolean)
1477 (defcustom org-yank-adjusted-subtrees nil
1478 "Non-nil means when yanking subtrees, adjust the level.
1479 With this setting, `org-paste-subtree' is used to insert the subtree, see
1480 this function for details."
1481 :group 'org-edit-structure
1482 :type 'boolean)
1484 (defcustom org-M-RET-may-split-line '((default . t))
1485 "Non-nil means M-RET will split the line at the cursor position.
1486 When nil, it will go to the end of the line before making a
1487 new line.
1488 You may also set this option in a different way for different
1489 contexts. Valid contexts are:
1491 headline when creating a new headline
1492 item when creating a new item
1493 table in a table field
1494 default the value to be used for all contexts not explicitly
1495 customized"
1496 :group 'org-structure
1497 :group 'org-table
1498 :type '(choice
1499 (const :tag "Always" t)
1500 (const :tag "Never" nil)
1501 (repeat :greedy t :tag "Individual contexts"
1502 (cons
1503 (choice :tag "Context"
1504 (const headline)
1505 (const item)
1506 (const table)
1507 (const default))
1508 (boolean)))))
1511 (defcustom org-insert-heading-respect-content nil
1512 "Non-nil means insert new headings after the current subtree.
1513 When nil, the new heading is created directly after the current line.
1514 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1515 this variable on for the duration of the command."
1516 :group 'org-structure
1517 :type 'boolean)
1519 (defcustom org-blank-before-new-entry '((heading . auto)
1520 (plain-list-item . auto))
1521 "Should `org-insert-heading' leave a blank line before new heading/item?
1522 The value is an alist, with `heading' and `plain-list-item' as CAR,
1523 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1524 which case Org will look at the surrounding headings/items and try to
1525 make an intelligent decision whether to insert a blank line or not.
1527 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1528 the setting here is ignored and no empty line is inserted to avoid breaking
1529 the list structure."
1530 :group 'org-edit-structure
1531 :type '(list
1532 (cons (const heading)
1533 (choice (const :tag "Never" nil)
1534 (const :tag "Always" t)
1535 (const :tag "Auto" auto)))
1536 (cons (const plain-list-item)
1537 (choice (const :tag "Never" nil)
1538 (const :tag "Always" t)
1539 (const :tag "Auto" auto)))))
1541 (defcustom org-insert-heading-hook nil
1542 "Hook being run after inserting a new heading."
1543 :group 'org-edit-structure
1544 :type 'hook)
1546 (defcustom org-enable-fixed-width-editor t
1547 "Non-nil means lines starting with \":\" are treated as fixed-width.
1548 This currently only means they are never auto-wrapped.
1549 When nil, such lines will be treated like ordinary lines."
1550 :group 'org-edit-structure
1551 :type 'boolean)
1553 (defcustom org-goto-auto-isearch t
1554 "Non-nil means typing characters in `org-goto' starts incremental search.
1555 When nil, you can use these keybindings to navigate the buffer:
1557 q Quit the org-goto interface
1558 n Go to the next visible heading
1559 p Go to the previous visible heading
1560 f Go one heading forward on same level
1561 b Go one heading backward on same level
1562 u Go one heading up"
1563 :group 'org-edit-structure
1564 :type 'boolean)
1566 (defgroup org-sparse-trees nil
1567 "Options concerning sparse trees in Org-mode."
1568 :tag "Org Sparse Trees"
1569 :group 'org-structure)
1571 (defcustom org-highlight-sparse-tree-matches t
1572 "Non-nil means highlight all matches that define a sparse tree.
1573 The highlights will automatically disappear the next time the buffer is
1574 changed by an edit command."
1575 :group 'org-sparse-trees
1576 :type 'boolean)
1578 (defcustom org-remove-highlights-with-change t
1579 "Non-nil means any change to the buffer will remove temporary highlights.
1580 Such highlights are created by `org-occur' and `org-clock-display'.
1581 When nil, `C-c C-c needs to be used to get rid of the highlights.
1582 The highlights created by `org-preview-latex-fragment' always need
1583 `C-c C-c' to be removed."
1584 :group 'org-sparse-trees
1585 :group 'org-time
1586 :type 'boolean)
1589 (defcustom org-occur-hook '(org-first-headline-recenter)
1590 "Hook that is run after `org-occur' has constructed a sparse tree.
1591 This can be used to recenter the window to show as much of the structure
1592 as possible."
1593 :group 'org-sparse-trees
1594 :type 'hook)
1596 (defgroup org-imenu-and-speedbar nil
1597 "Options concerning imenu and speedbar in Org-mode."
1598 :tag "Org Imenu and Speedbar"
1599 :group 'org-structure)
1601 (defcustom org-imenu-depth 2
1602 "The maximum level for Imenu access to Org-mode headlines.
1603 This also applied for speedbar access."
1604 :group 'org-imenu-and-speedbar
1605 :type 'integer)
1607 (defgroup org-table nil
1608 "Options concerning tables in Org-mode."
1609 :tag "Org Table"
1610 :group 'org)
1612 (defcustom org-enable-table-editor 'optimized
1613 "Non-nil means lines starting with \"|\" are handled by the table editor.
1614 When nil, such lines will be treated like ordinary lines.
1616 When equal to the symbol `optimized', the table editor will be optimized to
1617 do the following:
1618 - Automatic overwrite mode in front of whitespace in table fields.
1619 This makes the structure of the table stay in tact as long as the edited
1620 field does not exceed the column width.
1621 - Minimize the number of realigns. Normally, the table is aligned each time
1622 TAB or RET are pressed to move to another field. With optimization this
1623 happens only if changes to a field might have changed the column width.
1624 Optimization requires replacing the functions `self-insert-command',
1625 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1626 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1627 very good at guessing when a re-align will be necessary, but you can always
1628 force one with \\[org-ctrl-c-ctrl-c].
1630 If you would like to use the optimized version in Org-mode, but the
1631 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1633 This variable can be used to turn on and off the table editor during a session,
1634 but in order to toggle optimization, a restart is required.
1636 See also the variable `org-table-auto-blank-field'."
1637 :group 'org-table
1638 :type '(choice
1639 (const :tag "off" nil)
1640 (const :tag "on" t)
1641 (const :tag "on, optimized" optimized)))
1643 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1644 (version<= emacs-version "24.1"))
1645 "Non-nil means cluster self-insert commands for undo when possible.
1646 If this is set, then, like in the Emacs command loop, 20 consecutive
1647 characters will be undone together.
1648 This is configurable, because there is some impact on typing performance."
1649 :group 'org-table
1650 :type 'boolean)
1652 (defcustom org-table-tab-recognizes-table.el t
1653 "Non-nil means TAB will automatically notice a table.el table.
1654 When it sees such a table, it moves point into it and - if necessary -
1655 calls `table-recognize-table'."
1656 :group 'org-table-editing
1657 :type 'boolean)
1659 (defgroup org-link nil
1660 "Options concerning links in Org-mode."
1661 :tag "Org Link"
1662 :group 'org)
1664 (defvar org-link-abbrev-alist-local nil
1665 "Buffer-local version of `org-link-abbrev-alist', which see.
1666 The value of this is taken from the #+LINK lines.")
1667 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1669 (defcustom org-link-abbrev-alist nil
1670 "Alist of link abbreviations.
1671 The car of each element is a string, to be replaced at the start of a link.
1672 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1673 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1675 [[linkkey:tag][description]]
1677 The 'linkkey' must be a word word, starting with a letter, followed
1678 by letters, numbers, '-' or '_'.
1680 If REPLACE is a string, the tag will simply be appended to create the link.
1681 If the string contains \"%s\", the tag will be inserted there. If the string
1682 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1683 at that point (see the function `url-hexify-string'). If the string contains
1684 the specifier \"%(my-function)\", then the custom function `my-function' will
1685 be invoked: this function takes the tag as its only argument and must return
1686 a string.
1688 REPLACE may also be a function that will be called with the tag as the
1689 only argument to create the link, which should be returned as a string.
1691 See the manual for examples."
1692 :group 'org-link
1693 :type '(repeat
1694 (cons
1695 (string :tag "Protocol")
1696 (choice
1697 (string :tag "Format")
1698 (function)))))
1700 (defcustom org-descriptive-links t
1701 "Non-nil means Org will display descriptive links.
1702 E.g. [[http://orgmode.org][Org website]] will be displayed as
1703 \"Org Website\", hiding the link itself and just displaying its
1704 description. When set to `nil', Org will display the full links
1705 literally.
1707 You can interactively set the value of this variable by calling
1708 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1709 :group 'org-link
1710 :type 'boolean)
1712 (defcustom org-link-file-path-type 'adaptive
1713 "How the path name in file links should be stored.
1714 Valid values are:
1716 relative Relative to the current directory, i.e. the directory of the file
1717 into which the link is being inserted.
1718 absolute Absolute path, if possible with ~ for home directory.
1719 noabbrev Absolute path, no abbreviation of home directory.
1720 adaptive Use relative path for files in the current directory and sub-
1721 directories of it. For other files, use an absolute path."
1722 :group 'org-link
1723 :type '(choice
1724 (const relative)
1725 (const absolute)
1726 (const noabbrev)
1727 (const adaptive)))
1729 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1730 "Types of links that should be activated in Org-mode files.
1731 This is a list of symbols, each leading to the activation of a certain link
1732 type. In principle, it does not hurt to turn on most link types - there may
1733 be a small gain when turning off unused link types. The types are:
1735 bracket The recommended [[link][description]] or [[link]] links with hiding.
1736 angle Links in angular brackets that may contain whitespace like
1737 <bbdb:Carsten Dominik>.
1738 plain Plain links in normal text, no whitespace, like http://google.com.
1739 radio Text that is matched by a radio target, see manual for details.
1740 tag Tag settings in a headline (link to tag search).
1741 date Time stamps (link to calendar).
1742 footnote Footnote labels.
1744 Changing this variable requires a restart of Emacs to become effective."
1745 :group 'org-link
1746 :type '(set :greedy t
1747 (const :tag "Double bracket links" bracket)
1748 (const :tag "Angular bracket links" angle)
1749 (const :tag "Plain text links" plain)
1750 (const :tag "Radio target matches" radio)
1751 (const :tag "Tags" tag)
1752 (const :tag "Timestamps" date)
1753 (const :tag "Footnotes" footnote)))
1755 (defcustom org-make-link-description-function nil
1756 "Function to use for generating link descriptions from links.
1757 When nil, the link location will be used. This function must take
1758 two parameters: the first one is the link, the second one is the
1759 description generated by `org-insert-link'. The function should
1760 return the description to use."
1761 :group 'org-link
1762 :type '(choice (const nil) (function)))
1764 (defgroup org-link-store nil
1765 "Options concerning storing links in Org-mode."
1766 :tag "Org Store Link"
1767 :group 'org-link)
1769 (defcustom org-url-hexify-p t
1770 "When non-nil, hexify URL when creating a link."
1771 :type 'boolean
1772 :version "24.3"
1773 :group 'org-link-store)
1775 (defcustom org-email-link-description-format "Email %c: %.30s"
1776 "Format of the description part of a link to an email or usenet message.
1777 The following %-escapes will be replaced by corresponding information:
1779 %F full \"From\" field
1780 %f name, taken from \"From\" field, address if no name
1781 %T full \"To\" field
1782 %t first name in \"To\" field, address if no name
1783 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1784 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1785 %s subject
1786 %d date
1787 %m message-id.
1789 You may use normal field width specification between the % and the letter.
1790 This is for example useful to limit the length of the subject.
1792 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1793 :group 'org-link-store
1794 :type 'string)
1796 (defcustom org-from-is-user-regexp
1797 (let (r1 r2)
1798 (when (and user-mail-address (not (string= user-mail-address "")))
1799 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1800 (when (and user-full-name (not (string= user-full-name "")))
1801 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1802 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1803 "Regexp matched against the \"From:\" header of an email or usenet message.
1804 It should match if the message is from the user him/herself."
1805 :group 'org-link-store
1806 :type 'regexp)
1808 (defcustom org-context-in-file-links t
1809 "Non-nil means file links from `org-store-link' contain context.
1810 A search string will be added to the file name with :: as separator and
1811 used to find the context when the link is activated by the command
1812 `org-open-at-point'. When this option is t, the entire active region
1813 will be placed in the search string of the file link. If set to a
1814 positive integer, only the first n lines of context will be stored.
1816 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1817 negates this setting for the duration of the command."
1818 :group 'org-link-store
1819 :type '(choice boolean integer))
1821 (defcustom org-keep-stored-link-after-insertion nil
1822 "Non-nil means keep link in list for entire session.
1824 The command `org-store-link' adds a link pointing to the current
1825 location to an internal list. These links accumulate during a session.
1826 The command `org-insert-link' can be used to insert links into any
1827 Org-mode file (offering completion for all stored links). When this
1828 option is nil, every link which has been inserted once using \\[org-insert-link]
1829 will be removed from the list, to make completing the unused links
1830 more efficient."
1831 :group 'org-link-store
1832 :type 'boolean)
1834 (defgroup org-link-follow nil
1835 "Options concerning following links in Org-mode."
1836 :tag "Org Follow Link"
1837 :group 'org-link)
1839 (defcustom org-link-translation-function nil
1840 "Function to translate links with different syntax to Org syntax.
1841 This can be used to translate links created for example by the Planner
1842 or emacs-wiki packages to Org syntax.
1843 The function must accept two parameters, a TYPE containing the link
1844 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1845 which is everything after the link protocol. It should return a cons
1846 with possibly modified values of type and path.
1847 Org contains a function for this, so if you set this variable to
1848 `org-translate-link-from-planner', you should be able follow many
1849 links created by planner."
1850 :group 'org-link-follow
1851 :type '(choice (const nil) (function)))
1853 (defcustom org-follow-link-hook nil
1854 "Hook that is run after a link has been followed."
1855 :group 'org-link-follow
1856 :type 'hook)
1858 (defcustom org-tab-follows-link nil
1859 "Non-nil means on links TAB will follow the link.
1860 Needs to be set before org.el is loaded.
1861 This really should not be used, it does not make sense, and the
1862 implementation is bad."
1863 :group 'org-link-follow
1864 :type 'boolean)
1866 (defcustom org-return-follows-link nil
1867 "Non-nil means on links RET will follow the link.
1868 In tables, the special behavior of RET has precedence."
1869 :group 'org-link-follow
1870 :type 'boolean)
1872 (defcustom org-mouse-1-follows-link
1873 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1874 "Non-nil means mouse-1 on a link will follow the link.
1875 A longer mouse click will still set point. Does not work on XEmacs.
1876 Needs to be set before org.el is loaded."
1877 :group 'org-link-follow
1878 :version "24.4"
1879 :package-version '(Org . "8.3")
1880 :type '(choice
1881 (const :tag "A double click follows the link" double)
1882 (const :tag "Unconditionally follow the link with mouse-1" t)
1883 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1885 (defcustom org-mark-ring-length 4
1886 "Number of different positions to be recorded in the ring.
1887 Changing this requires a restart of Emacs to work correctly."
1888 :group 'org-link-follow
1889 :type 'integer)
1891 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1892 "Non-nil means internal links in Org files must exactly match a headline.
1893 When nil, the link search tries to match a phrase with all words
1894 in the search text."
1895 :group 'org-link-follow
1896 :version "24.1"
1897 :type '(choice
1898 (const :tag "Use fuzzy text search" nil)
1899 (const :tag "Match only exact headline" t)
1900 (const :tag "Match exact headline or query to create it"
1901 query-to-create)))
1903 (defcustom org-link-frame-setup
1904 '((vm . vm-visit-folder-other-frame)
1905 (vm-imap . vm-visit-imap-folder-other-frame)
1906 (gnus . org-gnus-no-new-news)
1907 (file . find-file-other-window)
1908 (wl . wl-other-frame))
1909 "Setup the frame configuration for following links.
1910 When following a link with Emacs, it may often be useful to display
1911 this link in another window or frame. This variable can be used to
1912 set this up for the different types of links.
1913 For VM, use any of
1914 `vm-visit-folder'
1915 `vm-visit-folder-other-window'
1916 `vm-visit-folder-other-frame'
1917 For Gnus, use any of
1918 `gnus'
1919 `gnus-other-frame'
1920 `org-gnus-no-new-news'
1921 For FILE, use any of
1922 `find-file'
1923 `find-file-other-window'
1924 `find-file-other-frame'
1925 For Wanderlust use any of
1926 `wl'
1927 `wl-other-frame'
1928 For the calendar, use the variable `calendar-setup'.
1929 For BBDB, it is currently only possible to display the matches in
1930 another window."
1931 :group 'org-link-follow
1932 :type '(list
1933 (cons (const vm)
1934 (choice
1935 (const vm-visit-folder)
1936 (const vm-visit-folder-other-window)
1937 (const vm-visit-folder-other-frame)))
1938 (cons (const vm-imap)
1939 (choice
1940 (const vm-visit-imap-folder)
1941 (const vm-visit-imap-folder-other-window)
1942 (const vm-visit-imap-folder-other-frame)))
1943 (cons (const gnus)
1944 (choice
1945 (const gnus)
1946 (const gnus-other-frame)
1947 (const org-gnus-no-new-news)))
1948 (cons (const file)
1949 (choice
1950 (const find-file)
1951 (const find-file-other-window)
1952 (const find-file-other-frame)))
1953 (cons (const wl)
1954 (choice
1955 (const wl)
1956 (const wl-other-frame)))))
1958 (defcustom org-display-internal-link-with-indirect-buffer nil
1959 "Non-nil means use indirect buffer to display infile links.
1960 Activating internal links (from one location in a file to another location
1961 in the same file) normally just jumps to the location. When the link is
1962 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1963 is displayed in
1964 another window. When this option is set, the other window actually displays
1965 an indirect buffer clone of the current buffer, to avoid any visibility
1966 changes to the current buffer."
1967 :group 'org-link-follow
1968 :type 'boolean)
1970 (defcustom org-open-non-existing-files nil
1971 "Non-nil means `org-open-file' will open non-existing files.
1972 When nil, an error will be generated.
1973 This variable applies only to external applications because they
1974 might choke on non-existing files. If the link is to a file that
1975 will be opened in Emacs, the variable is ignored."
1976 :group 'org-link-follow
1977 :type 'boolean)
1979 (defcustom org-open-directory-means-index-dot-org nil
1980 "Non-nil means a link to a directory really means to index.org.
1981 When nil, following a directory link will run dired or open a finder/explorer
1982 window on that directory."
1983 :group 'org-link-follow
1984 :type 'boolean)
1986 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1987 "Function and arguments to call for following mailto links.
1988 This is a list with the first element being a Lisp function, and the
1989 remaining elements being arguments to the function. In string arguments,
1990 %a will be replaced by the address, and %s will be replaced by the subject
1991 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1992 :group 'org-link-follow
1993 :type '(choice
1994 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1995 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1996 (const :tag "message-mail" (message-mail "%a" "%s"))
1997 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1999 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2000 "Non-nil means ask for confirmation before executing shell links.
2001 Shell links can be dangerous: just think about a link
2003 [[shell:rm -rf ~/*][Google Search]]
2005 This link would show up in your Org-mode document as \"Google Search\",
2006 but really it would remove your entire home directory.
2007 Therefore we advise against setting this variable to nil.
2008 Just change it to `y-or-n-p' if you want to confirm with a
2009 single keystroke rather than having to type \"yes\"."
2010 :group 'org-link-follow
2011 :type '(choice
2012 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2013 (const :tag "with y-or-n (faster)" y-or-n-p)
2014 (const :tag "no confirmation (dangerous)" nil)))
2015 (put 'org-confirm-shell-link-function
2016 'safe-local-variable
2017 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2019 (defcustom org-confirm-shell-link-not-regexp ""
2020 "A regexp to skip confirmation for shell links."
2021 :group 'org-link-follow
2022 :version "24.1"
2023 :type 'regexp)
2025 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2026 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2027 Elisp links can be dangerous: just think about a link
2029 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2031 This link would show up in your Org-mode document as \"Google Search\",
2032 but really it would remove your entire home directory.
2033 Therefore we advise against setting this variable to nil.
2034 Just change it to `y-or-n-p' if you want to confirm with a
2035 single keystroke rather than having to type \"yes\"."
2036 :group 'org-link-follow
2037 :type '(choice
2038 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2039 (const :tag "with y-or-n (faster)" y-or-n-p)
2040 (const :tag "no confirmation (dangerous)" nil)))
2041 (put 'org-confirm-shell-link-function
2042 'safe-local-variable
2043 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2045 (defcustom org-confirm-elisp-link-not-regexp ""
2046 "A regexp to skip confirmation for Elisp links."
2047 :group 'org-link-follow
2048 :version "24.1"
2049 :type 'regexp)
2051 (defconst org-file-apps-defaults-gnu
2052 '((remote . emacs)
2053 (system . mailcap)
2054 (t . mailcap))
2055 "Default file applications on a UNIX or GNU/Linux system.
2056 See `org-file-apps'.")
2058 (defconst org-file-apps-defaults-macosx
2059 '((remote . emacs)
2060 (t . "open %s")
2061 (system . "open %s")
2062 ("ps.gz" . "gv %s")
2063 ("eps.gz" . "gv %s")
2064 ("dvi" . "xdvi %s")
2065 ("fig" . "xfig %s"))
2066 "Default file applications on a MacOS X system.
2067 The system \"open\" is known as a default, but we use X11 applications
2068 for some files for which the OS does not have a good default.
2069 See `org-file-apps'.")
2071 (defconst org-file-apps-defaults-windowsnt
2072 (list
2073 '(remote . emacs)
2074 (cons t
2075 (list (if (featurep 'xemacs)
2076 'mswindows-shell-execute
2077 'w32-shell-execute)
2078 "open" 'file))
2079 (cons 'system
2080 (list (if (featurep 'xemacs)
2081 'mswindows-shell-execute
2082 'w32-shell-execute)
2083 "open" 'file)))
2084 "Default file applications on a Windows NT system.
2085 The system \"open\" is used for most files.
2086 See `org-file-apps'.")
2088 (defcustom org-file-apps
2089 '((auto-mode . emacs)
2090 ("\\.mm\\'" . default)
2091 ("\\.x?html?\\'" . default)
2092 ("\\.pdf\\'" . default))
2093 "External applications for opening `file:path' items in a document.
2094 Org-mode uses system defaults for different file types, but
2095 you can use this variable to set the application for a given file
2096 extension. The entries in this list are cons cells where the car identifies
2097 files and the cdr the corresponding command. Possible values for the
2098 file identifier are
2099 \"string\" A string as a file identifier can be interpreted in different
2100 ways, depending on its contents:
2102 - Alphanumeric characters only:
2103 Match links with this file extension.
2104 Example: (\"pdf\" . \"evince %s\")
2105 to open PDFs with evince.
2107 - Regular expression: Match links where the
2108 filename matches the regexp. If you want to
2109 use groups here, use shy groups.
2111 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2112 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2113 to open *.html and *.xhtml with firefox.
2115 - Regular expression which contains (non-shy) groups:
2116 Match links where the whole link, including \"::\", and
2117 anything after that, matches the regexp.
2118 In a custom command string, %1, %2, etc. are replaced with
2119 the parts of the link that were matched by the groups.
2120 For backwards compatibility, if a command string is given
2121 that does not use any of the group matches, this case is
2122 handled identically to the second one (i.e. match against
2123 file name only).
2124 In a custom lisp form, you can access the group matches with
2125 (match-string n link).
2127 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2128 to open [[file:document.pdf::5]] with evince at page 5.
2130 `directory' Matches a directory
2131 `remote' Matches a remote file, accessible through tramp or efs.
2132 Remote files most likely should be visited through Emacs
2133 because external applications cannot handle such paths.
2134 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2135 so all files Emacs knows how to handle. Using this with
2136 command `emacs' will open most files in Emacs. Beware that this
2137 will also open html files inside Emacs, unless you add
2138 (\"html\" . default) to the list as well.
2139 t Default for files not matched by any of the other options.
2140 `system' The system command to open files, like `open' on Windows
2141 and Mac OS X, and mailcap under GNU/Linux. This is the command
2142 that will be selected if you call `C-c C-o' with a double
2143 \\[universal-argument] \\[universal-argument] prefix.
2145 Possible values for the command are:
2146 `emacs' The file will be visited by the current Emacs process.
2147 `default' Use the default application for this file type, which is the
2148 association for t in the list, most likely in the system-specific
2149 part.
2150 This can be used to overrule an unwanted setting in the
2151 system-specific variable.
2152 `system' Use the system command for opening files, like \"open\".
2153 This command is specified by the entry whose car is `system'.
2154 Most likely, the system-specific version of this variable
2155 does define this command, but you can overrule/replace it
2156 here.
2157 string A command to be executed by a shell; %s will be replaced
2158 by the path to the file.
2159 sexp A Lisp form which will be evaluated. The file path will
2160 be available in the Lisp variable `file'.
2161 For more examples, see the system specific constants
2162 `org-file-apps-defaults-macosx'
2163 `org-file-apps-defaults-windowsnt'
2164 `org-file-apps-defaults-gnu'."
2165 :group 'org-link-follow
2166 :type '(repeat
2167 (cons (choice :value ""
2168 (string :tag "Extension")
2169 (const :tag "System command to open files" system)
2170 (const :tag "Default for unrecognized files" t)
2171 (const :tag "Remote file" remote)
2172 (const :tag "Links to a directory" directory)
2173 (const :tag "Any files that have Emacs modes"
2174 auto-mode))
2175 (choice :value ""
2176 (const :tag "Visit with Emacs" emacs)
2177 (const :tag "Use default" default)
2178 (const :tag "Use the system command" system)
2179 (string :tag "Command")
2180 (sexp :tag "Lisp form")))))
2182 (defcustom org-doi-server-url "http://dx.doi.org/"
2183 "The URL of the DOI server."
2184 :type 'string
2185 :version "24.3"
2186 :group 'org-link-follow)
2188 (defgroup org-refile nil
2189 "Options concerning refiling entries in Org-mode."
2190 :tag "Org Refile"
2191 :group 'org)
2193 (defcustom org-directory "~/org"
2194 "Directory with org files.
2195 This is just a default location to look for Org files. There is no need
2196 at all to put your files into this directory. It is only used in the
2197 following situations:
2199 1. When a capture template specifies a target file that is not an
2200 absolute path. The path will then be interpreted relative to
2201 `org-directory'
2202 2. When a capture note is filed away in an interactive way (when exiting the
2203 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2204 with `org-directory' as the default path."
2205 :group 'org-refile
2206 :group 'org-capture
2207 :type 'directory)
2209 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2210 "Default target for storing notes.
2211 Used as a fall back file for org-capture.el, for templates that
2212 do not specify a target file."
2213 :group 'org-refile
2214 :group 'org-capture
2215 :type '(choice
2216 (const :tag "Default from remember-data-file" nil)
2217 file))
2219 (defcustom org-goto-interface 'outline
2220 "The default interface to be used for `org-goto'.
2221 Allowed values are:
2222 outline The interface shows an outline of the relevant file
2223 and the correct heading is found by moving through
2224 the outline or by searching with incremental search.
2225 outline-path-completion Headlines in the current buffer are offered via
2226 completion. This is the interface also used by
2227 the refile command."
2228 :group 'org-refile
2229 :type '(choice
2230 (const :tag "Outline" outline)
2231 (const :tag "Outline-path-completion" outline-path-completion)))
2233 (defcustom org-goto-max-level 5
2234 "Maximum target level when running `org-goto' with refile interface."
2235 :group 'org-refile
2236 :type 'integer)
2238 (defcustom org-reverse-note-order nil
2239 "Non-nil means store new notes at the beginning of a file or entry.
2240 When nil, new notes will be filed to the end of a file or entry.
2241 This can also be a list with cons cells of regular expressions that
2242 are matched against file names, and values."
2243 :group 'org-capture
2244 :group 'org-refile
2245 :type '(choice
2246 (const :tag "Reverse always" t)
2247 (const :tag "Reverse never" nil)
2248 (repeat :tag "By file name regexp"
2249 (cons regexp boolean))))
2251 (defcustom org-log-refile nil
2252 "Information to record when a task is refiled.
2254 Possible values are:
2256 nil Don't add anything
2257 time Add a time stamp to the task
2258 note Prompt for a note and add it with template `org-log-note-headings'
2260 This option can also be set with on a per-file-basis with
2262 #+STARTUP: nologrefile
2263 #+STARTUP: logrefile
2264 #+STARTUP: lognoterefile
2266 You can have local logging settings for a subtree by setting the LOGGING
2267 property to one or more of these keywords.
2269 When bulk-refiling from the agenda, the value `note' is forbidden and
2270 will temporarily be changed to `time'."
2271 :group 'org-refile
2272 :group 'org-progress
2273 :version "24.1"
2274 :type '(choice
2275 (const :tag "No logging" nil)
2276 (const :tag "Record timestamp" time)
2277 (const :tag "Record timestamp with note." note)))
2279 (defcustom org-refile-targets nil
2280 "Targets for refiling entries with \\[org-refile].
2281 This is a list of cons cells. Each cell contains:
2282 - a specification of the files to be considered, either a list of files,
2283 or a symbol whose function or variable value will be used to retrieve
2284 a file name or a list of file names. If you use `org-agenda-files' for
2285 that, all agenda files will be scanned for targets. Nil means consider
2286 headings in the current buffer.
2287 - A specification of how to find candidate refile targets. This may be
2288 any of:
2289 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2290 This tag has to be present in all target headlines, inheritance will
2291 not be considered.
2292 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2293 todo keyword.
2294 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2295 headlines that are refiling targets.
2296 - a cons cell (:level . N). Any headline of level N is considered a target.
2297 Note that, when `org-odd-levels-only' is set, level corresponds to
2298 order in hierarchy, not to the number of stars.
2299 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2300 Note that, when `org-odd-levels-only' is set, level corresponds to
2301 order in hierarchy, not to the number of stars.
2303 Each element of this list generates a set of possible targets.
2304 The union of these sets is presented (with completion) to
2305 the user by `org-refile'.
2307 You can set the variable `org-refile-target-verify-function' to a function
2308 to verify each headline found by the simple criteria above.
2310 When this variable is nil, all top-level headlines in the current buffer
2311 are used, equivalent to the value `((nil . (:level . 1))'."
2312 :group 'org-refile
2313 :type '(repeat
2314 (cons
2315 (choice :value org-agenda-files
2316 (const :tag "All agenda files" org-agenda-files)
2317 (const :tag "Current buffer" nil)
2318 (function) (variable) (file))
2319 (choice :tag "Identify target headline by"
2320 (cons :tag "Specific tag" (const :value :tag) (string))
2321 (cons :tag "TODO keyword" (const :value :todo) (string))
2322 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2323 (cons :tag "Level number" (const :value :level) (integer))
2324 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2326 (defcustom org-refile-target-verify-function nil
2327 "Function to verify if the headline at point should be a refile target.
2328 The function will be called without arguments, with point at the
2329 beginning of the headline. It should return t and leave point
2330 where it is if the headline is a valid target for refiling.
2332 If the target should not be selected, the function must return nil.
2333 In addition to this, it may move point to a place from where the search
2334 should be continued. For example, the function may decide that the entire
2335 subtree of the current entry should be excluded and move point to the end
2336 of the subtree."
2337 :group 'org-refile
2338 :type '(choice
2339 (const nil)
2340 (function)))
2342 (defcustom org-refile-use-cache nil
2343 "Non-nil means cache refile targets to speed up the process.
2344 The cache for a particular file will be updated automatically when
2345 the buffer has been killed, or when any of the marker used for flagging
2346 refile targets no longer points at a live buffer.
2347 If you have added new entries to a buffer that might themselves be targets,
2348 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2349 find that easier, `C-u C-u C-u C-c C-w'."
2350 :group 'org-refile
2351 :version "24.1"
2352 :type 'boolean)
2354 (defcustom org-refile-use-outline-path nil
2355 "Non-nil means provide refile targets as paths.
2356 So a level 3 headline will be available as level1/level2/level3.
2358 When the value is `file', also include the file name (without directory)
2359 into the path. In this case, you can also stop the completion after
2360 the file name, to get entries inserted as top level in the file.
2362 When `full-file-path', include the full file path."
2363 :group 'org-refile
2364 :type '(choice
2365 (const :tag "Not" nil)
2366 (const :tag "Yes" t)
2367 (const :tag "Start with file name" file)
2368 (const :tag "Start with full file path" full-file-path)))
2370 (defcustom org-outline-path-complete-in-steps t
2371 "Non-nil means complete the outline path in hierarchical steps.
2372 When Org-mode uses the refile interface to select an outline path
2373 \(see variable `org-refile-use-outline-path'), the completion of
2374 the path can be done is a single go, or if can be done in steps down
2375 the headline hierarchy. Going in steps is probably the best if you
2376 do not use a special completion package like `ido' or `icicles'.
2377 However, when using these packages, going in one step can be very
2378 fast, while still showing the whole path to the entry."
2379 :group 'org-refile
2380 :type 'boolean)
2382 (defcustom org-refile-allow-creating-parent-nodes nil
2383 "Non-nil means allow to create new nodes as refile targets.
2384 New nodes are then created by adding \"/new node name\" to the completion
2385 of an existing node. When the value of this variable is `confirm',
2386 new node creation must be confirmed by the user (recommended).
2387 When nil, the completion must match an existing entry.
2389 Note that, if the new heading is not seen by the criteria
2390 listed in `org-refile-targets', multiple instances of the same
2391 heading would be created by trying again to file under the new
2392 heading."
2393 :group 'org-refile
2394 :type '(choice
2395 (const :tag "Never" nil)
2396 (const :tag "Always" t)
2397 (const :tag "Prompt for confirmation" confirm)))
2399 (defcustom org-refile-active-region-within-subtree nil
2400 "Non-nil means also refile active region within a subtree.
2402 By default `org-refile' doesn't allow refiling regions if they
2403 don't contain a set of subtrees, but it might be convenient to
2404 do so sometimes: in that case, the first line of the region is
2405 converted to a headline before refiling."
2406 :group 'org-refile
2407 :version "24.1"
2408 :type 'boolean)
2410 (defgroup org-todo nil
2411 "Options concerning TODO items in Org-mode."
2412 :tag "Org TODO"
2413 :group 'org)
2415 (defgroup org-progress nil
2416 "Options concerning Progress logging in Org-mode."
2417 :tag "Org Progress"
2418 :group 'org-time)
2420 (defvar org-todo-interpretation-widgets
2421 '((:tag "Sequence (cycling hits every state)" sequence)
2422 (:tag "Type (cycling directly to DONE)" type))
2423 "The available interpretation symbols for customizing `org-todo-keywords'.
2424 Interested libraries should add to this list.")
2426 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2427 "List of TODO entry keyword sequences and their interpretation.
2428 \\<org-mode-map>This is a list of sequences.
2430 Each sequence starts with a symbol, either `sequence' or `type',
2431 indicating if the keywords should be interpreted as a sequence of
2432 action steps, or as different types of TODO items. The first
2433 keywords are states requiring action - these states will select a headline
2434 for inclusion into the global TODO list Org-mode produces. If one of
2435 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2436 signify that no further action is necessary. If \"|\" is not found,
2437 the last keyword is treated as the only DONE state of the sequence.
2439 The command \\[org-todo] cycles an entry through these states, and one
2440 additional state where no keyword is present. For details about this
2441 cycling, see the manual.
2443 TODO keywords and interpretation can also be set on a per-file basis with
2444 the special #+SEQ_TODO and #+TYP_TODO lines.
2446 Each keyword can optionally specify a character for fast state selection
2447 \(in combination with the variable `org-use-fast-todo-selection')
2448 and specifiers for state change logging, using the same syntax that
2449 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2450 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2451 indicates to record a time stamp each time this state is selected.
2453 Each keyword may also specify if a timestamp or a note should be
2454 recorded when entering or leaving the state, by adding additional
2455 characters in the parenthesis after the keyword. This looks like this:
2456 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2457 record only the time of the state change. With X and Y being either
2458 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2459 Y when leaving the state if and only if the *target* state does not
2460 define X. You may omit any of the fast-selection key or X or /Y,
2461 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2463 For backward compatibility, this variable may also be just a list
2464 of keywords. In this case the interpretation (sequence or type) will be
2465 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2466 :group 'org-todo
2467 :group 'org-keywords
2468 :type '(choice
2469 (repeat :tag "Old syntax, just keywords"
2470 (string :tag "Keyword"))
2471 (repeat :tag "New syntax"
2472 (cons
2473 (choice
2474 :tag "Interpretation"
2475 ;;Quick and dirty way to see
2476 ;;`org-todo-interpretations'. This takes the
2477 ;;place of item arguments
2478 :convert-widget
2479 (lambda (widget)
2480 (widget-put widget
2481 :args (mapcar
2482 #'(lambda (x)
2483 (widget-convert
2484 (cons 'const x)))
2485 org-todo-interpretation-widgets))
2486 widget))
2487 (repeat
2488 (string :tag "Keyword"))))))
2490 (defvar org-todo-keywords-1 nil
2491 "All TODO and DONE keywords active in a buffer.")
2492 (make-variable-buffer-local 'org-todo-keywords-1)
2493 (defvar org-todo-keywords-for-agenda nil)
2494 (defvar org-done-keywords-for-agenda nil)
2495 (defvar org-todo-keyword-alist-for-agenda nil)
2496 (defvar org-tag-alist-for-agenda nil
2497 "Alist of all tags from all agenda files.")
2498 (defvar org-tag-groups-alist-for-agenda nil
2499 "Alist of all groups tags from all current agenda files.")
2500 (defvar org-tag-groups-alist nil)
2501 (make-variable-buffer-local 'org-tag-groups-alist)
2502 (defvar org-agenda-contributing-files nil)
2503 (defvar org-not-done-keywords nil)
2504 (make-variable-buffer-local 'org-not-done-keywords)
2505 (defvar org-done-keywords nil)
2506 (make-variable-buffer-local 'org-done-keywords)
2507 (defvar org-todo-heads nil)
2508 (make-variable-buffer-local 'org-todo-heads)
2509 (defvar org-todo-sets nil)
2510 (make-variable-buffer-local 'org-todo-sets)
2511 (defvar org-todo-log-states nil)
2512 (make-variable-buffer-local 'org-todo-log-states)
2513 (defvar org-todo-kwd-alist nil)
2514 (make-variable-buffer-local 'org-todo-kwd-alist)
2515 (defvar org-todo-key-alist nil)
2516 (make-variable-buffer-local 'org-todo-key-alist)
2517 (defvar org-todo-key-trigger nil)
2518 (make-variable-buffer-local 'org-todo-key-trigger)
2520 (defcustom org-todo-interpretation 'sequence
2521 "Controls how TODO keywords are interpreted.
2522 This variable is in principle obsolete and is only used for
2523 backward compatibility, if the interpretation of todo keywords is
2524 not given already in `org-todo-keywords'. See that variable for
2525 more information."
2526 :group 'org-todo
2527 :group 'org-keywords
2528 :type '(choice (const sequence)
2529 (const type)))
2531 (defcustom org-use-fast-todo-selection t
2532 "Non-nil means use the fast todo selection scheme with C-c C-t.
2533 This variable describes if and under what circumstances the cycling
2534 mechanism for TODO keywords will be replaced by a single-key, direct
2535 selection scheme.
2537 When nil, fast selection is never used.
2539 When the symbol `prefix', it will be used when `org-todo' is called
2540 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2541 `C-u t' in an agenda buffer.
2543 When t, fast selection is used by default. In this case, the prefix
2544 argument forces cycling instead.
2546 In all cases, the special interface is only used if access keys have
2547 actually been assigned by the user, i.e. if keywords in the configuration
2548 are followed by a letter in parenthesis, like TODO(t)."
2549 :group 'org-todo
2550 :type '(choice
2551 (const :tag "Never" nil)
2552 (const :tag "By default" t)
2553 (const :tag "Only with C-u C-c C-t" prefix)))
2555 (defcustom org-provide-todo-statistics t
2556 "Non-nil means update todo statistics after insert and toggle.
2557 ALL-HEADLINES means update todo statistics by including headlines
2558 with no TODO keyword as well, counting them as not done.
2559 A list of TODO keywords means the same, but skip keywords that are
2560 not in this list.
2561 When set to a list of two lists, the first list contains keywords
2562 to consider as TODO keywords, the second list contains keywords
2563 to consider as DONE keywords.
2565 When this is set, todo statistics is updated in the parent of the
2566 current entry each time a todo state is changed."
2567 :group 'org-todo
2568 :type '(choice
2569 (const :tag "Yes, only for TODO entries" t)
2570 (const :tag "Yes, including all entries" all-headlines)
2571 (repeat :tag "Yes, for TODOs in this list"
2572 (string :tag "TODO keyword"))
2573 (list :tag "Yes, for TODOs and DONEs in these lists"
2574 (repeat (string :tag "TODO keyword"))
2575 (repeat (string :tag "DONE keyword")))
2576 (other :tag "No TODO statistics" nil)))
2578 (defcustom org-hierarchical-todo-statistics t
2579 "Non-nil means TODO statistics covers just direct children.
2580 When nil, all entries in the subtree are considered.
2581 This has only an effect if `org-provide-todo-statistics' is set.
2582 To set this to nil for only a single subtree, use a COOKIE_DATA
2583 property and include the word \"recursive\" into the value."
2584 :group 'org-todo
2585 :type 'boolean)
2587 (defcustom org-after-todo-state-change-hook nil
2588 "Hook which is run after the state of a TODO item was changed.
2589 The new state (a string with a TODO keyword, or nil) is available in the
2590 Lisp variable `org-state'."
2591 :group 'org-todo
2592 :type 'hook)
2594 (defvar org-blocker-hook nil
2595 "Hook for functions that are allowed to block a state change.
2597 Functions in this hook should not modify the buffer.
2598 Each function gets as its single argument a property list,
2599 see `org-trigger-hook' for more information about this list.
2601 If any of the functions in this hook returns nil, the state change
2602 is blocked.")
2604 (defvar org-trigger-hook nil
2605 "Hook for functions that are triggered by a state change.
2607 Each function gets as its single argument a property list with at
2608 least the following elements:
2610 (:type type-of-change :position pos-at-entry-start
2611 :from old-state :to new-state)
2613 Depending on the type, more properties may be present.
2615 This mechanism is currently implemented for:
2617 TODO state changes
2618 ------------------
2619 :type todo-state-change
2620 :from previous state (keyword as a string), or nil, or a symbol
2621 'todo' or 'done', to indicate the general type of state.
2622 :to new state, like in :from")
2624 (defcustom org-enforce-todo-dependencies nil
2625 "Non-nil means undone TODO entries will block switching the parent to DONE.
2626 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2627 be blocked if any prior sibling is not yet done.
2628 Finally, if the parent is blocked because of ordered siblings of its own,
2629 the child will also be blocked."
2630 :set (lambda (var val)
2631 (set var val)
2632 (if val
2633 (add-hook 'org-blocker-hook
2634 'org-block-todo-from-children-or-siblings-or-parent)
2635 (remove-hook 'org-blocker-hook
2636 'org-block-todo-from-children-or-siblings-or-parent)))
2637 :group 'org-todo
2638 :type 'boolean)
2640 (defcustom org-enforce-todo-checkbox-dependencies nil
2641 "Non-nil means unchecked boxes will block switching the parent to DONE.
2642 When this is nil, checkboxes have no influence on switching TODO states.
2643 When non-nil, you first need to check off all check boxes before the TODO
2644 entry can be switched to DONE.
2645 This variable needs to be set before org.el is loaded, and you need to
2646 restart Emacs after a change to make the change effective. The only way
2647 to change is while Emacs is running is through the customize interface."
2648 :set (lambda (var val)
2649 (set var val)
2650 (if val
2651 (add-hook 'org-blocker-hook
2652 'org-block-todo-from-checkboxes)
2653 (remove-hook 'org-blocker-hook
2654 'org-block-todo-from-checkboxes)))
2655 :group 'org-todo
2656 :type 'boolean)
2658 (defcustom org-treat-insert-todo-heading-as-state-change nil
2659 "Non-nil means inserting a TODO heading is treated as state change.
2660 So when the command \\[org-insert-todo-heading] is used, state change
2661 logging will apply if appropriate. When nil, the new TODO item will
2662 be inserted directly, and no logging will take place."
2663 :group 'org-todo
2664 :type 'boolean)
2666 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2667 "Non-nil means switching TODO states with S-cursor counts as state change.
2668 This is the default behavior. However, setting this to nil allows a
2669 convenient way to select a TODO state and bypass any logging associated
2670 with that."
2671 :group 'org-todo
2672 :type 'boolean)
2674 (defcustom org-todo-state-tags-triggers nil
2675 "Tag changes that should be triggered by TODO state changes.
2676 This is a list. Each entry is
2678 (state-change (tag . flag) .......)
2680 State-change can be a string with a state, and empty string to indicate the
2681 state that has no TODO keyword, or it can be one of the symbols `todo'
2682 or `done', meaning any not-done or done state, respectively."
2683 :group 'org-todo
2684 :group 'org-tags
2685 :type '(repeat
2686 (cons (choice :tag "When changing to"
2687 (const :tag "Not-done state" todo)
2688 (const :tag "Done state" done)
2689 (string :tag "State"))
2690 (repeat
2691 (cons :tag "Tag action"
2692 (string :tag "Tag")
2693 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2695 (defcustom org-log-done nil
2696 "Information to record when a task moves to the DONE state.
2698 Possible values are:
2700 nil Don't add anything, just change the keyword
2701 time Add a time stamp to the task
2702 note Prompt for a note and add it with template `org-log-note-headings'
2704 This option can also be set with on a per-file-basis with
2706 #+STARTUP: nologdone
2707 #+STARTUP: logdone
2708 #+STARTUP: lognotedone
2710 You can have local logging settings for a subtree by setting the LOGGING
2711 property to one or more of these keywords."
2712 :group 'org-todo
2713 :group 'org-progress
2714 :type '(choice
2715 (const :tag "No logging" nil)
2716 (const :tag "Record CLOSED timestamp" time)
2717 (const :tag "Record CLOSED timestamp with note." note)))
2719 ;; Normalize old uses of org-log-done.
2720 (cond
2721 ((eq org-log-done t) (setq org-log-done 'time))
2722 ((and (listp org-log-done) (memq 'done org-log-done))
2723 (setq org-log-done 'note)))
2725 (defcustom org-log-reschedule nil
2726 "Information to record when the scheduling date of a tasks is modified.
2728 Possible values are:
2730 nil Don't add anything, just change the date
2731 time Add a time stamp to the task
2732 note Prompt for a note and add it with template `org-log-note-headings'
2734 This option can also be set with on a per-file-basis with
2736 #+STARTUP: nologreschedule
2737 #+STARTUP: logreschedule
2738 #+STARTUP: lognotereschedule"
2739 :group 'org-todo
2740 :group 'org-progress
2741 :type '(choice
2742 (const :tag "No logging" nil)
2743 (const :tag "Record timestamp" time)
2744 (const :tag "Record timestamp with note." note)))
2746 (defcustom org-log-redeadline nil
2747 "Information to record when the deadline date of a tasks is modified.
2749 Possible values are:
2751 nil Don't add anything, just change the date
2752 time Add a time stamp to the task
2753 note Prompt for a note and add it with template `org-log-note-headings'
2755 This option can also be set with on a per-file-basis with
2757 #+STARTUP: nologredeadline
2758 #+STARTUP: logredeadline
2759 #+STARTUP: lognoteredeadline
2761 You can have local logging settings for a subtree by setting the LOGGING
2762 property to one or more of these keywords."
2763 :group 'org-todo
2764 :group 'org-progress
2765 :type '(choice
2766 (const :tag "No logging" nil)
2767 (const :tag "Record timestamp" time)
2768 (const :tag "Record timestamp with note." note)))
2770 (defcustom org-log-note-clock-out nil
2771 "Non-nil means record a note when clocking out of an item.
2772 This can also be configured on a per-file basis by adding one of
2773 the following lines anywhere in the buffer:
2775 #+STARTUP: lognoteclock-out
2776 #+STARTUP: nolognoteclock-out"
2777 :group 'org-todo
2778 :group 'org-progress
2779 :type 'boolean)
2781 (defcustom org-log-done-with-time t
2782 "Non-nil means the CLOSED time stamp will contain date and time.
2783 When nil, only the date will be recorded."
2784 :group 'org-progress
2785 :type 'boolean)
2787 (defcustom org-log-note-headings
2788 '((done . "CLOSING NOTE %t")
2789 (state . "State %-12s from %-12S %t")
2790 (note . "Note taken on %t")
2791 (reschedule . "Rescheduled from %S on %t")
2792 (delschedule . "Not scheduled, was %S on %t")
2793 (redeadline . "New deadline from %S on %t")
2794 (deldeadline . "Removed deadline, was %S on %t")
2795 (refile . "Refiled on %t")
2796 (clock-out . ""))
2797 "Headings for notes added to entries.
2798 The value is an alist, with the car being a symbol indicating the note
2799 context, and the cdr is the heading to be used. The heading may also be the
2800 empty string.
2801 %t in the heading will be replaced by a time stamp.
2802 %T will be an active time stamp instead the default inactive one
2803 %d will be replaced by a short-format time stamp.
2804 %D will be replaced by an active short-format time stamp.
2805 %s will be replaced by the new TODO state, in double quotes.
2806 %S will be replaced by the old TODO state, in double quotes.
2807 %u will be replaced by the user name.
2808 %U will be replaced by the full user name.
2810 In fact, it is not a good idea to change the `state' entry, because
2811 agenda log mode depends on the format of these entries."
2812 :group 'org-todo
2813 :group 'org-progress
2814 :type '(list :greedy t
2815 (cons (const :tag "Heading when closing an item" done) string)
2816 (cons (const :tag
2817 "Heading when changing todo state (todo sequence only)"
2818 state) string)
2819 (cons (const :tag "Heading when just taking a note" note) string)
2820 (cons (const :tag "Heading when rescheduling" reschedule) string)
2821 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2822 (cons (const :tag "Heading when changing deadline" redeadline) string)
2823 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2824 (cons (const :tag "Heading when refiling" refile) string)
2825 (cons (const :tag "Heading when clocking out" clock-out) string)))
2827 (unless (assq 'note org-log-note-headings)
2828 (push '(note . "%t") org-log-note-headings))
2830 (defcustom org-log-into-drawer nil
2831 "Non-nil means insert state change notes and time stamps into a drawer.
2832 When nil, state changes notes will be inserted after the headline and
2833 any scheduling and clock lines, but not inside a drawer.
2835 The value of this variable should be the name of the drawer to use.
2836 LOGBOOK is proposed as the default drawer for this purpose, you can
2837 also set this to a string to define the drawer of your choice.
2839 A value of t is also allowed, representing \"LOGBOOK\".
2841 A value of t or nil can also be set with on a per-file-basis with
2843 #+STARTUP: logdrawer
2844 #+STARTUP: nologdrawer
2846 If this variable is set, `org-log-state-notes-insert-after-drawers'
2847 will be ignored.
2849 You can set the property LOG_INTO_DRAWER to overrule this setting for
2850 a subtree."
2851 :group 'org-todo
2852 :group 'org-progress
2853 :type '(choice
2854 (const :tag "Not into a drawer" nil)
2855 (const :tag "LOGBOOK" t)
2856 (string :tag "Other")))
2858 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2860 (defun org-log-into-drawer ()
2861 "Return the value of `org-log-into-drawer', but let properties overrule.
2862 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2863 used instead of the default value."
2864 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2865 (cond
2866 ((not p) org-log-into-drawer)
2867 ((equal p "nil") nil)
2868 ((equal p "t") "LOGBOOK")
2869 (t p))))
2871 (defcustom org-log-state-notes-insert-after-drawers nil
2872 "Non-nil means insert state change notes after any drawers in entry.
2873 Only the drawers that *immediately* follow the headline and the
2874 deadline/scheduled line are skipped.
2875 When nil, insert notes right after the heading and perhaps the line
2876 with deadline/scheduling if present.
2878 This variable will have no effect if `org-log-into-drawer' is
2879 set."
2880 :group 'org-todo
2881 :group 'org-progress
2882 :type 'boolean)
2884 (defcustom org-log-states-order-reversed t
2885 "Non-nil means the latest state note will be directly after heading.
2886 When nil, the state change notes will be ordered according to time.
2888 This option can also be set with on a per-file-basis with
2890 #+STARTUP: logstatesreversed
2891 #+STARTUP: nologstatesreversed"
2892 :group 'org-todo
2893 :group 'org-progress
2894 :type 'boolean)
2896 (defcustom org-todo-repeat-to-state nil
2897 "The TODO state to which a repeater should return the repeating task.
2898 By default this is the first task in a TODO sequence, or the previous state
2899 in a TODO_TYP set. But you can specify another task here.
2900 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2901 :group 'org-todo
2902 :version "24.1"
2903 :type '(choice (const :tag "Head of sequence" nil)
2904 (string :tag "Specific state")))
2906 (defcustom org-log-repeat 'time
2907 "Non-nil means record moving through the DONE state when triggering repeat.
2908 An auto-repeating task is immediately switched back to TODO when
2909 marked DONE. If you are not logging state changes (by adding \"@\"
2910 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2911 record a closing note, there will be no record of the task moving
2912 through DONE. This variable forces taking a note anyway.
2914 nil Don't force a record
2915 time Record a time stamp
2916 note Prompt for a note and add it with template `org-log-note-headings'
2918 This option can also be set with on a per-file-basis with
2920 #+STARTUP: nologrepeat
2921 #+STARTUP: logrepeat
2922 #+STARTUP: lognoterepeat
2924 You can have local logging settings for a subtree by setting the LOGGING
2925 property to one or more of these keywords."
2926 :group 'org-todo
2927 :group 'org-progress
2928 :type '(choice
2929 (const :tag "Don't force a record" nil)
2930 (const :tag "Force recording the DONE state" time)
2931 (const :tag "Force recording a note with the DONE state" note)))
2934 (defgroup org-priorities nil
2935 "Priorities in Org-mode."
2936 :tag "Org Priorities"
2937 :group 'org-todo)
2939 (defcustom org-enable-priority-commands t
2940 "Non-nil means priority commands are active.
2941 When nil, these commands will be disabled, so that you never accidentally
2942 set a priority."
2943 :group 'org-priorities
2944 :type 'boolean)
2946 (defcustom org-highest-priority ?A
2947 "The highest priority of TODO items. A character like ?A, ?B etc.
2948 Must have a smaller ASCII number than `org-lowest-priority'."
2949 :group 'org-priorities
2950 :type 'character)
2952 (defcustom org-lowest-priority ?C
2953 "The lowest priority of TODO items. A character like ?A, ?B etc.
2954 Must have a larger ASCII number than `org-highest-priority'."
2955 :group 'org-priorities
2956 :type 'character)
2958 (defcustom org-default-priority ?B
2959 "The default priority of TODO items.
2960 This is the priority an item gets if no explicit priority is given.
2961 When starting to cycle on an empty priority the first step in the cycle
2962 depends on `org-priority-start-cycle-with-default'. The resulting first
2963 step priority must not exceed the range from `org-highest-priority' to
2964 `org-lowest-priority' which means that `org-default-priority' has to be
2965 in this range exclusive or inclusive the range boundaries. Else the
2966 first step refuses to set the default and the second will fall back
2967 to (depending on the command used) the highest or lowest priority."
2968 :group 'org-priorities
2969 :type 'character)
2971 (defcustom org-priority-start-cycle-with-default t
2972 "Non-nil means start with default priority when starting to cycle.
2973 When this is nil, the first step in the cycle will be (depending on the
2974 command used) one higher or lower than the default priority.
2975 See also `org-default-priority'."
2976 :group 'org-priorities
2977 :type 'boolean)
2979 (defcustom org-get-priority-function nil
2980 "Function to extract the priority from a string.
2981 The string is normally the headline. If this is nil Org computes the
2982 priority from the priority cookie like [#A] in the headline. It returns
2983 an integer, increasing by 1000 for each priority level.
2984 The user can set a different function here, which should take a string
2985 as an argument and return the numeric priority."
2986 :group 'org-priorities
2987 :version "24.1"
2988 :type '(choice
2989 (const nil)
2990 (function)))
2992 (defgroup org-time nil
2993 "Options concerning time stamps and deadlines in Org-mode."
2994 :tag "Org Time"
2995 :group 'org)
2997 (defcustom org-insert-labeled-timestamps-at-point nil
2998 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2999 When nil, these labeled time stamps are forces into the second line of an
3000 entry, just after the headline. When scheduling from the global TODO list,
3001 the time stamp will always be forced into the second line."
3002 :group 'org-time
3003 :type 'boolean)
3005 (defcustom org-time-stamp-rounding-minutes '(0 5)
3006 "Number of minutes to round time stamps to.
3007 These are two values, the first applies when first creating a time stamp.
3008 The second applies when changing it with the commands `S-up' and `S-down'.
3009 When changing the time stamp, this means that it will change in steps
3010 of N minutes, as given by the second value.
3012 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3013 numbers should be factors of 60, so for example 5, 10, 15.
3015 When this is larger than 1, you can still force an exact time stamp by using
3016 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3017 and by using a prefix arg to `S-up/down' to specify the exact number
3018 of minutes to shift."
3019 :group 'org-time
3020 :get #'(lambda (var) ; Make sure both elements are there
3021 (if (integerp (default-value var))
3022 (list (default-value var) 5)
3023 (default-value var)))
3024 :type '(list
3025 (integer :tag "when inserting times")
3026 (integer :tag "when modifying times")))
3028 ;; Normalize old customizations of this variable.
3029 (when (integerp org-time-stamp-rounding-minutes)
3030 (setq org-time-stamp-rounding-minutes
3031 (list org-time-stamp-rounding-minutes
3032 org-time-stamp-rounding-minutes)))
3034 (defcustom org-display-custom-times nil
3035 "Non-nil means overlay custom formats over all time stamps.
3036 The formats are defined through the variable `org-time-stamp-custom-formats'.
3037 To turn this on on a per-file basis, insert anywhere in the file:
3038 #+STARTUP: customtime"
3039 :group 'org-time
3040 :set 'set-default
3041 :type 'sexp)
3042 (make-variable-buffer-local 'org-display-custom-times)
3044 (defcustom org-time-stamp-custom-formats
3045 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3046 "Custom formats for time stamps. See `format-time-string' for the syntax.
3047 These are overlaid over the default ISO format if the variable
3048 `org-display-custom-times' is set. Time like %H:%M should be at the
3049 end of the second format. The custom formats are also honored by export
3050 commands, if custom time display is turned on at the time of export."
3051 :group 'org-time
3052 :type 'sexp)
3054 (defun org-time-stamp-format (&optional long inactive)
3055 "Get the right format for a time string."
3056 (let ((f (if long (cdr org-time-stamp-formats)
3057 (car org-time-stamp-formats))))
3058 (if inactive
3059 (concat "[" (substring f 1 -1) "]")
3060 f)))
3062 (defcustom org-time-clocksum-format
3063 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3064 "The format string used when creating CLOCKSUM lines.
3065 This is also used when Org mode generates a time duration.
3067 The value can be a single format string containing two
3068 %-sequences, which will be filled with the number of hours and
3069 minutes in that order.
3071 Alternatively, the value can be a plist associating any of the
3072 keys :years, :months, :weeks, :days, :hours or :minutes with
3073 format strings. The time duration is formatted using only the
3074 time components that are needed and concatenating the results.
3075 If a time unit in absent, it falls back to the next smallest
3076 unit.
3078 The keys :require-years, :require-months, :require-days,
3079 :require-weeks, :require-hours, :require-minutes are also
3080 meaningful. A non-nil value for these keys indicates that the
3081 corresponding time component should always be included, even if
3082 its value is 0.
3085 For example,
3087 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3088 :require-minutes t)
3090 means durations longer than a day will be expressed in days,
3091 hours and minutes, and durations less than a day will always be
3092 expressed in hours and minutes (even for durations less than an
3093 hour).
3095 The value
3097 \(:days \"%dd\" :minutes \"%dm\")
3099 means durations longer than a day will be expressed in days and
3100 minutes, and durations less than a day will be expressed entirely
3101 in minutes (even for durations longer than an hour)."
3102 :group 'org-time
3103 :group 'org-clock
3104 :version "24.4"
3105 :package-version '(Org . "8.0")
3106 :type '(choice (string :tag "Format string")
3107 (set :tag "Plist"
3108 (group :inline t (const :tag "Years" :years)
3109 (string :tag "Format string"))
3110 (group :inline t
3111 (const :tag "Always show years" :require-years)
3112 (const t))
3113 (group :inline t (const :tag "Months" :months)
3114 (string :tag "Format string"))
3115 (group :inline t
3116 (const :tag "Always show months" :require-months)
3117 (const t))
3118 (group :inline t (const :tag "Weeks" :weeks)
3119 (string :tag "Format string"))
3120 (group :inline t
3121 (const :tag "Always show weeks" :require-weeks)
3122 (const t))
3123 (group :inline t (const :tag "Days" :days)
3124 (string :tag "Format string"))
3125 (group :inline t
3126 (const :tag "Always show days" :require-days)
3127 (const t))
3128 (group :inline t (const :tag "Hours" :hours)
3129 (string :tag "Format string"))
3130 (group :inline t
3131 (const :tag "Always show hours" :require-hours)
3132 (const t))
3133 (group :inline t (const :tag "Minutes" :minutes)
3134 (string :tag "Format string"))
3135 (group :inline t
3136 (const :tag "Always show minutes" :require-minutes)
3137 (const t)))))
3139 (defcustom org-time-clocksum-use-fractional nil
3140 "When non-nil, \\[org-clock-display] uses fractional times.
3141 See `org-time-clocksum-format' for more on time clock formats."
3142 :group 'org-time
3143 :group 'org-clock
3144 :version "24.3"
3145 :type 'boolean)
3147 (defcustom org-time-clocksum-use-effort-durations nil
3148 "When non-nil, \\[org-clock-display] uses effort durations.
3149 E.g. by default, one day is considered to be a 8 hours effort,
3150 so a task that has been clocked for 16 hours will be displayed
3151 as during 2 days in the clock display or in the clocktable.
3153 See `org-effort-durations' on how to set effort durations
3154 and `org-time-clocksum-format' for more on time clock formats."
3155 :group 'org-time
3156 :group 'org-clock
3157 :version "24.4"
3158 :package-version '(Org . "8.0")
3159 :type 'boolean)
3161 (defcustom org-time-clocksum-fractional-format "%.2f"
3162 "The format string used when creating CLOCKSUM lines,
3163 or when Org mode generates a time duration, if
3164 `org-time-clocksum-use-fractional' is enabled.
3166 The value can be a single format string containing one
3167 %-sequence, which will be filled with the number of hours as
3168 a float.
3170 Alternatively, the value can be a plist associating any of the
3171 keys :years, :months, :weeks, :days, :hours or :minutes with
3172 a format string. The time duration is formatted using the
3173 largest time unit which gives a non-zero integer part. If all
3174 specified formats have zero integer part, the smallest time unit
3175 is used."
3176 :group 'org-time
3177 :type '(choice (string :tag "Format string")
3178 (set (group :inline t (const :tag "Years" :years)
3179 (string :tag "Format string"))
3180 (group :inline t (const :tag "Months" :months)
3181 (string :tag "Format string"))
3182 (group :inline t (const :tag "Weeks" :weeks)
3183 (string :tag "Format string"))
3184 (group :inline t (const :tag "Days" :days)
3185 (string :tag "Format string"))
3186 (group :inline t (const :tag "Hours" :hours)
3187 (string :tag "Format string"))
3188 (group :inline t (const :tag "Minutes" :minutes)
3189 (string :tag "Format string")))))
3191 (defcustom org-deadline-warning-days 14
3192 "Number of days before expiration during which a deadline becomes active.
3193 This variable governs the display in sparse trees and in the agenda.
3194 When 0 or negative, it means use this number (the absolute value of it)
3195 even if a deadline has a different individual lead time specified.
3197 Custom commands can set this variable in the options section."
3198 :group 'org-time
3199 :group 'org-agenda-daily/weekly
3200 :type 'integer)
3202 (defcustom org-scheduled-delay-days 0
3203 "Number of days before a scheduled item becomes active.
3204 This variable governs the display in sparse trees and in the agenda.
3205 The default value (i.e. 0) means: don't delay scheduled item.
3206 When negative, it means use this number (the absolute value of it)
3207 even if a scheduled item has a different individual delay time
3208 specified.
3210 Custom commands can set this variable in the options section."
3211 :group 'org-time
3212 :group 'org-agenda-daily/weekly
3213 :version "24.4"
3214 :package-version '(Org . "8.0")
3215 :type 'integer)
3217 (defcustom org-read-date-prefer-future t
3218 "Non-nil means assume future for incomplete date input from user.
3219 This affects the following situations:
3220 1. The user gives a month but not a year.
3221 For example, if it is April and you enter \"feb 2\", this will be read
3222 as Feb 2, *next* year. \"May 5\", however, will be this year.
3223 2. The user gives a day, but no month.
3224 For example, if today is the 15th, and you enter \"3\", Org-mode will
3225 read this as the third of *next* month. However, if you enter \"17\",
3226 it will be considered as *this* month.
3228 If you set this variable to the symbol `time', then also the following
3229 will work:
3231 3. If the user gives a time.
3232 If the time is before now, it will be interpreted as tomorrow.
3234 Currently none of this works for ISO week specifications.
3236 When this option is nil, the current day, month and year will always be
3237 used as defaults.
3239 See also `org-agenda-jump-prefer-future'."
3240 :group 'org-time
3241 :type '(choice
3242 (const :tag "Never" nil)
3243 (const :tag "Check month and day" t)
3244 (const :tag "Check month, day, and time" time)))
3246 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3247 "Should the agenda jump command prefer the future for incomplete dates?
3248 The default is to do the same as configured in `org-read-date-prefer-future'.
3249 But you can also set a deviating value here.
3250 This may t or nil, or the symbol `org-read-date-prefer-future'."
3251 :group 'org-agenda
3252 :group 'org-time
3253 :version "24.1"
3254 :type '(choice
3255 (const :tag "Use org-read-date-prefer-future"
3256 org-read-date-prefer-future)
3257 (const :tag "Never" nil)
3258 (const :tag "Always" t)))
3260 (defcustom org-read-date-force-compatible-dates t
3261 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3263 Depending on the system Emacs is running on, certain dates cannot
3264 be represented with the type used internally to represent time.
3265 Dates between 1970-1-1 and 2038-1-1 can always be represented
3266 correctly. Some systems allow for earlier dates, some for later,
3267 some for both. One way to find out it to insert any date into an
3268 Org buffer, putting the cursor on the year and hitting S-up and
3269 S-down to test the range.
3271 When this variable is set to t, the date/time prompt will not let
3272 you specify dates outside the 1970-2037 range, so it is certain that
3273 these dates will work in whatever version of Emacs you are
3274 running, and also that you can move a file from one Emacs implementation
3275 to another. WHenever Org is forcing the year for you, it will display
3276 a message and beep.
3278 When this variable is nil, Org will check if the date is
3279 representable in the specific Emacs implementation you are using.
3280 If not, it will force a year, usually the current year, and beep
3281 to remind you. Currently this setting is not recommended because
3282 the likelihood that you will open your Org files in an Emacs that
3283 has limited date range is not negligible.
3285 A workaround for this problem is to use diary sexp dates for time
3286 stamps outside of this range."
3287 :group 'org-time
3288 :version "24.1"
3289 :type 'boolean)
3291 (defcustom org-read-date-display-live t
3292 "Non-nil means display current interpretation of date prompt live.
3293 This display will be in an overlay, in the minibuffer."
3294 :group 'org-time
3295 :type 'boolean)
3297 (defcustom org-read-date-popup-calendar t
3298 "Non-nil means pop up a calendar when prompting for a date.
3299 In the calendar, the date can be selected with mouse-1. However, the
3300 minibuffer will also be active, and you can simply enter the date as well.
3301 When nil, only the minibuffer will be available."
3302 :group 'org-time
3303 :type 'boolean)
3304 (org-defvaralias 'org-popup-calendar-for-date-prompt
3305 'org-read-date-popup-calendar)
3307 (make-obsolete-variable
3308 'org-read-date-minibuffer-setup-hook
3309 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3310 (defcustom org-read-date-minibuffer-setup-hook nil
3311 "Hook to be used to set up keys for the date/time interface.
3312 Add key definitions to `minibuffer-local-map', which will be a
3313 temporary copy.
3315 WARNING: This option is obsolete, you should use
3316 `org-read-date-minibuffer-local-map' to set up keys."
3317 :group 'org-time
3318 :type 'hook)
3320 (defcustom org-extend-today-until 0
3321 "The hour when your day really ends. Must be an integer.
3322 This has influence for the following applications:
3323 - When switching the agenda to \"today\". It it is still earlier than
3324 the time given here, the day recognized as TODAY is actually yesterday.
3325 - When a date is read from the user and it is still before the time given
3326 here, the current date and time will be assumed to be yesterday, 23:59.
3327 Also, timestamps inserted in capture templates follow this rule.
3329 IMPORTANT: This is a feature whose implementation is and likely will
3330 remain incomplete. Really, it is only here because past midnight seems to
3331 be the favorite working time of John Wiegley :-)"
3332 :group 'org-time
3333 :type 'integer)
3335 (defcustom org-use-effective-time nil
3336 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3337 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3338 \"effective time\" of any timestamps between midnight and 8am will be
3339 23:59 of the previous day."
3340 :group 'org-time
3341 :version "24.1"
3342 :type 'boolean)
3344 (defcustom org-use-last-clock-out-time-as-effective-time nil
3345 "When non-nil, use the last clock out time for `org-todo'.
3346 Note that this option has precedence over the combined use of
3347 `org-use-effective-time' and `org-extend-today-until'."
3348 :group 'org-time
3349 :version "24.4"
3350 :package-version '(Org . "8.0")
3351 :type 'boolean)
3353 (defcustom org-edit-timestamp-down-means-later nil
3354 "Non-nil means S-down will increase the time in a time stamp.
3355 When nil, S-up will increase."
3356 :group 'org-time
3357 :type 'boolean)
3359 (defcustom org-calendar-follow-timestamp-change t
3360 "Non-nil means make the calendar window follow timestamp changes.
3361 When a timestamp is modified and the calendar window is visible, it will be
3362 moved to the new date."
3363 :group 'org-time
3364 :type 'boolean)
3366 (defgroup org-tags nil
3367 "Options concerning tags in Org-mode."
3368 :tag "Org Tags"
3369 :group 'org)
3371 (defcustom org-tag-alist nil
3372 "List of tags allowed in Org-mode files.
3373 When this list is nil, Org-mode will base TAG input on what is already in the
3374 buffer.
3375 The value of this variable is an alist, the car of each entry must be a
3376 keyword as a string, the cdr may be a character that is used to select
3377 that tag through the fast-tag-selection interface.
3378 See the manual for details."
3379 :group 'org-tags
3380 :type '(repeat
3381 (choice
3382 (cons (string :tag "Tag name")
3383 (character :tag "Access char"))
3384 (list :tag "Start radio group"
3385 (const :startgroup)
3386 (option (string :tag "Group description")))
3387 (list :tag "Group tags delimiter"
3388 (const :grouptags))
3389 (list :tag "End radio group"
3390 (const :endgroup)
3391 (option (string :tag "Group description")))
3392 (const :tag "New line" (:newline)))))
3394 (defcustom org-tag-persistent-alist nil
3395 "List of tags that will always appear in all Org-mode files.
3396 This is in addition to any in buffer settings or customizations
3397 of `org-tag-alist'.
3398 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3399 The value of this variable is an alist, the car of each entry must be a
3400 keyword as a string, the cdr may be a character that is used to select
3401 that tag through the fast-tag-selection interface.
3402 See the manual for details.
3403 To disable these tags on a per-file basis, insert anywhere in the file:
3404 #+STARTUP: noptag"
3405 :group 'org-tags
3406 :type '(repeat
3407 (choice
3408 (cons (string :tag "Tag name")
3409 (character :tag "Access char"))
3410 (const :tag "Start radio group" (:startgroup))
3411 (const :tag "Group tags delimiter" (:grouptags))
3412 (const :tag "End radio group" (:endgroup))
3413 (const :tag "New line" (:newline)))))
3415 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3416 "If non-nil, always offer completion for all tags of all agenda files.
3417 Instead of customizing this variable directly, you might want to
3418 set it locally for capture buffers, because there no list of
3419 tags in that file can be created dynamically (there are none).
3421 (add-hook 'org-capture-mode-hook
3422 (lambda ()
3423 (set (make-local-variable
3424 'org-complete-tags-always-offer-all-agenda-tags)
3425 t)))"
3426 :group 'org-tags
3427 :version "24.1"
3428 :type 'boolean)
3430 (defvar org-file-tags nil
3431 "List of tags that can be inherited by all entries in the file.
3432 The tags will be inherited if the variable `org-use-tag-inheritance'
3433 says they should be.
3434 This variable is populated from #+FILETAGS lines.")
3436 (defcustom org-use-fast-tag-selection 'auto
3437 "Non-nil means use fast tag selection scheme.
3438 This is a special interface to select and deselect tags with single keys.
3439 When nil, fast selection is never used.
3440 When the symbol `auto', fast selection is used if and only if selection
3441 characters for tags have been configured, either through the variable
3442 `org-tag-alist' or through a #+TAGS line in the buffer.
3443 When t, fast selection is always used and selection keys are assigned
3444 automatically if necessary."
3445 :group 'org-tags
3446 :type '(choice
3447 (const :tag "Always" t)
3448 (const :tag "Never" nil)
3449 (const :tag "When selection characters are configured" auto)))
3451 (defcustom org-fast-tag-selection-single-key nil
3452 "Non-nil means fast tag selection exits after first change.
3453 When nil, you have to press RET to exit it.
3454 During fast tag selection, you can toggle this flag with `C-c'.
3455 This variable can also have the value `expert'. In this case, the window
3456 displaying the tags menu is not even shown, until you press C-c again."
3457 :group 'org-tags
3458 :type '(choice
3459 (const :tag "No" nil)
3460 (const :tag "Yes" t)
3461 (const :tag "Expert" expert)))
3463 (defvar org-fast-tag-selection-include-todo nil
3464 "Non-nil means fast tags selection interface will also offer TODO states.
3465 This is an undocumented feature, you should not rely on it.")
3467 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3468 "The column to which tags should be indented in a headline.
3469 If this number is positive, it specifies the column. If it is negative,
3470 it means that the tags should be flushright to that column. For example,
3471 -80 works well for a normal 80 character screen.
3472 When 0, place tags directly after headline text, with only one space in
3473 between."
3474 :group 'org-tags
3475 :type 'integer)
3477 (defcustom org-auto-align-tags t
3478 "Non-nil keeps tags aligned when modifying headlines.
3479 Some operations (i.e. demoting) change the length of a headline and
3480 therefore shift the tags around. With this option turned on, after
3481 each such operation the tags are again aligned to `org-tags-column'."
3482 :group 'org-tags
3483 :type 'boolean)
3485 (defcustom org-use-tag-inheritance t
3486 "Non-nil means tags in levels apply also for sublevels.
3487 When nil, only the tags directly given in a specific line apply there.
3488 This may also be a list of tags that should be inherited, or a regexp that
3489 matches tags that should be inherited. Additional control is possible
3490 with the variable `org-tags-exclude-from-inheritance' which gives an
3491 explicit list of tags to be excluded from inheritance, even if the value of
3492 `org-use-tag-inheritance' would select it for inheritance.
3494 If this option is t, a match early-on in a tree can lead to a large
3495 number of matches in the subtree when constructing the agenda or creating
3496 a sparse tree. If you only want to see the first match in a tree during
3497 a search, check out the variable `org-tags-match-list-sublevels'."
3498 :group 'org-tags
3499 :type '(choice
3500 (const :tag "Not" nil)
3501 (const :tag "Always" t)
3502 (repeat :tag "Specific tags" (string :tag "Tag"))
3503 (regexp :tag "Tags matched by regexp")))
3505 (defcustom org-tags-exclude-from-inheritance nil
3506 "List of tags that should never be inherited.
3507 This is a way to exclude a few tags from inheritance. For way to do
3508 the opposite, to actively allow inheritance for selected tags,
3509 see the variable `org-use-tag-inheritance'."
3510 :group 'org-tags
3511 :type '(repeat (string :tag "Tag")))
3513 (defun org-tag-inherit-p (tag)
3514 "Check if TAG is one that should be inherited."
3515 (cond
3516 ((member tag org-tags-exclude-from-inheritance) nil)
3517 ((eq org-use-tag-inheritance t) t)
3518 ((not org-use-tag-inheritance) nil)
3519 ((stringp org-use-tag-inheritance)
3520 (string-match org-use-tag-inheritance tag))
3521 ((listp org-use-tag-inheritance)
3522 (member tag org-use-tag-inheritance))
3523 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3525 (defcustom org-tags-match-list-sublevels t
3526 "Non-nil means list also sublevels of headlines matching a search.
3527 This variable applies to tags/property searches, and also to stuck
3528 projects because this search is based on a tags match as well.
3530 When set to the symbol `indented', sublevels are indented with
3531 leading dots.
3533 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3534 the sublevels of a headline matching a tag search often also match
3535 the same search. Listing all of them can create very long lists.
3536 Setting this variable to nil causes subtrees of a match to be skipped.
3538 This variable is semi-obsolete and probably should always be true. It
3539 is better to limit inheritance to certain tags using the variables
3540 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3541 :group 'org-tags
3542 :type '(choice
3543 (const :tag "No, don't list them" nil)
3544 (const :tag "Yes, do list them" t)
3545 (const :tag "List them, indented with leading dots" indented)))
3547 (defcustom org-tags-sort-function nil
3548 "When set, tags are sorted using this function as a comparator."
3549 :group 'org-tags
3550 :type '(choice
3551 (const :tag "No sorting" nil)
3552 (const :tag "Alphabetical" string<)
3553 (const :tag "Reverse alphabetical" string>)
3554 (function :tag "Custom function" nil)))
3556 (defvar org-tags-history nil
3557 "History of minibuffer reads for tags.")
3558 (defvar org-last-tags-completion-table nil
3559 "The last used completion table for tags.")
3560 (defvar org-after-tags-change-hook nil
3561 "Hook that is run after the tags in a line have changed.")
3563 (defgroup org-properties nil
3564 "Options concerning properties in Org-mode."
3565 :tag "Org Properties"
3566 :group 'org)
3568 (defcustom org-property-format "%-10s %s"
3569 "How property key/value pairs should be formatted by `indent-line'.
3570 When `indent-line' hits a property definition, it will format the line
3571 according to this format, mainly to make sure that the values are
3572 lined-up with respect to each other."
3573 :group 'org-properties
3574 :type 'string)
3576 (defcustom org-properties-postprocess-alist nil
3577 "Alist of properties and functions to adjust inserted values.
3578 Elements of this alist must be of the form
3580 ([string] [function])
3582 where [string] must be a property name and [function] must be a
3583 lambda expression: this lambda expression must take one argument,
3584 the value to adjust, and return the new value as a string.
3586 For example, this element will allow the property \"Remaining\"
3587 to be updated wrt the relation between the \"Effort\" property
3588 and the clock summary:
3590 ((\"Remaining\" (lambda(value)
3591 (let ((clocksum (org-clock-sum-current-item))
3592 (effort (org-duration-string-to-minutes
3593 (org-entry-get (point) \"Effort\"))))
3594 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3595 :group 'org-properties
3596 :version "24.1"
3597 :type '(alist :key-type (string :tag "Property")
3598 :value-type (function :tag "Function")))
3600 (defcustom org-use-property-inheritance nil
3601 "Non-nil means properties apply also for sublevels.
3603 This setting is chiefly used during property searches. Turning it on can
3604 cause significant overhead when doing a search, which is why it is not
3605 on by default.
3607 When nil, only the properties directly given in the current entry count.
3608 When t, every property is inherited. The value may also be a list of
3609 properties that should have inheritance, or a regular expression matching
3610 properties that should be inherited.
3612 However, note that some special properties use inheritance under special
3613 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3614 and the properties ending in \"_ALL\" when they are used as descriptor
3615 for valid values of a property.
3617 Note for programmers:
3618 When querying an entry with `org-entry-get', you can control if inheritance
3619 should be used. By default, `org-entry-get' looks only at the local
3620 properties. You can request inheritance by setting the inherit argument
3621 to t (to force inheritance) or to `selective' (to respect the setting
3622 in this variable)."
3623 :group 'org-properties
3624 :type '(choice
3625 (const :tag "Not" nil)
3626 (const :tag "Always" t)
3627 (repeat :tag "Specific properties" (string :tag "Property"))
3628 (regexp :tag "Properties matched by regexp")))
3630 (defun org-property-inherit-p (property)
3631 "Check if PROPERTY is one that should be inherited."
3632 (cond
3633 ((eq org-use-property-inheritance t) t)
3634 ((not org-use-property-inheritance) nil)
3635 ((stringp org-use-property-inheritance)
3636 (string-match org-use-property-inheritance property))
3637 ((listp org-use-property-inheritance)
3638 (member property org-use-property-inheritance))
3639 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3641 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3642 "The default column format, if no other format has been defined.
3643 This variable can be set on the per-file basis by inserting a line
3645 #+COLUMNS: %25ITEM ....."
3646 :group 'org-properties
3647 :type 'string)
3649 (defcustom org-columns-ellipses ".."
3650 "The ellipses to be used when a field in column view is truncated.
3651 When this is the empty string, as many characters as possible are shown,
3652 but then there will be no visual indication that the field has been truncated.
3653 When this is a string of length N, the last N characters of a truncated
3654 field are replaced by this string. If the column is narrower than the
3655 ellipses string, only part of the ellipses string will be shown."
3656 :group 'org-properties
3657 :type 'string)
3659 (defcustom org-columns-modify-value-for-display-function nil
3660 "Function that modifies values for display in column view.
3661 For example, it can be used to cut out a certain part from a time stamp.
3662 The function must take 2 arguments:
3664 column-title The title of the column (*not* the property name)
3665 value The value that should be modified.
3667 The function should return the value that should be displayed,
3668 or nil if the normal value should be used."
3669 :group 'org-properties
3670 :type '(choice (const nil) (function)))
3672 (defconst org-global-properties-fixed
3673 '(("VISIBILITY_ALL" . "folded children content all")
3674 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3675 "List of property/value pairs that can be inherited by any entry.
3677 These are fixed values, for the preset properties. The user variable
3678 that can be used to add to this list is `org-global-properties'.
3680 The entries in this list are cons cells where the car is a property
3681 name and cdr is a string with the value. If the value represents
3682 multiple items like an \"_ALL\" property, separate the items by
3683 spaces.")
3685 (defcustom org-global-properties nil
3686 "List of property/value pairs that can be inherited by any entry.
3688 This list will be combined with the constant `org-global-properties-fixed'.
3690 The entries in this list are cons cells where the car is a property
3691 name and cdr is a string with the value.
3693 You can set buffer-local values for the same purpose in the variable
3694 `org-file-properties' this by adding lines like
3696 #+PROPERTY: NAME VALUE"
3697 :group 'org-properties
3698 :type '(repeat
3699 (cons (string :tag "Property")
3700 (string :tag "Value"))))
3702 (defvar org-file-properties nil
3703 "List of property/value pairs that can be inherited by any entry.
3704 Valid for the current buffer.
3705 This variable is populated from #+PROPERTY lines.")
3706 (make-variable-buffer-local 'org-file-properties)
3708 (defgroup org-agenda nil
3709 "Options concerning agenda views in Org-mode."
3710 :tag "Org Agenda"
3711 :group 'org)
3713 (defvar org-category nil
3714 "Variable used by org files to set a category for agenda display.
3715 Such files should use a file variable to set it, for example
3717 # -*- mode: org; org-category: \"ELisp\"
3719 or contain a special line
3721 #+CATEGORY: ELisp
3723 If the file does not specify a category, then file's base name
3724 is used instead.")
3725 (make-variable-buffer-local 'org-category)
3726 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3728 (defcustom org-agenda-files nil
3729 "The files to be used for agenda display.
3730 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3731 \\[org-remove-file]. You can also use customize to edit the list.
3733 If an entry is a directory, all files in that directory that are matched by
3734 `org-agenda-file-regexp' will be part of the file list.
3736 If the value of the variable is not a list but a single file name, then
3737 the list of agenda files is actually stored and maintained in that file, one
3738 agenda file per line. In this file paths can be given relative to
3739 `org-directory'. Tilde expansion and environment variable substitution
3740 are also made."
3741 :group 'org-agenda
3742 :type '(choice
3743 (repeat :tag "List of files and directories" file)
3744 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3746 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3747 "Regular expression to match files for `org-agenda-files'.
3748 If any element in the list in that variable contains a directory instead
3749 of a normal file, all files in that directory that are matched by this
3750 regular expression will be included."
3751 :group 'org-agenda
3752 :type 'regexp)
3754 (defcustom org-agenda-text-search-extra-files nil
3755 "List of extra files to be searched by text search commands.
3756 These files will be searched in addition to the agenda files by the
3757 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3758 Note that these files will only be searched for text search commands,
3759 not for the other agenda views like todo lists, tag searches or the weekly
3760 agenda. This variable is intended to list notes and possibly archive files
3761 that should also be searched by these two commands.
3762 In fact, if the first element in the list is the symbol `agenda-archives',
3763 then all archive files of all agenda files will be added to the search
3764 scope."
3765 :group 'org-agenda
3766 :type '(set :greedy t
3767 (const :tag "Agenda Archives" agenda-archives)
3768 (repeat :inline t (file))))
3770 (org-defvaralias 'org-agenda-multi-occur-extra-files
3771 'org-agenda-text-search-extra-files)
3773 (defcustom org-agenda-skip-unavailable-files nil
3774 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3775 A nil value means to remove them, after a query, from the list."
3776 :group 'org-agenda
3777 :type 'boolean)
3779 (defcustom org-calendar-to-agenda-key [?c]
3780 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3781 The command `org-calendar-goto-agenda' will be bound to this key. The
3782 default is the character `c' because then `c' can be used to switch back and
3783 forth between agenda and calendar."
3784 :group 'org-agenda
3785 :type 'sexp)
3787 (defcustom org-calendar-insert-diary-entry-key [?i]
3788 "The key to be installed in `calendar-mode-map' for adding diary entries.
3789 This option is irrelevant until `org-agenda-diary-file' has been configured
3790 to point to an Org-mode file. When that is the case, the command
3791 `org-agenda-diary-entry' will be bound to the key given here, by default
3792 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3793 if you want to continue doing this, you need to change this to a different
3794 key."
3795 :group 'org-agenda
3796 :type 'sexp)
3798 (defcustom org-agenda-diary-file 'diary-file
3799 "File to which to add new entries with the `i' key in agenda and calendar.
3800 When this is the symbol `diary-file', the functionality in the Emacs
3801 calendar will be used to add entries to the `diary-file'. But when this
3802 points to a file, `org-agenda-diary-entry' will be used instead."
3803 :group 'org-agenda
3804 :type '(choice
3805 (const :tag "The standard Emacs diary file" diary-file)
3806 (file :tag "Special Org file diary entries")))
3808 (eval-after-load "calendar"
3809 '(progn
3810 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3811 'org-calendar-goto-agenda)
3812 (add-hook 'calendar-mode-hook
3813 (lambda ()
3814 (unless (eq org-agenda-diary-file 'diary-file)
3815 (define-key calendar-mode-map
3816 org-calendar-insert-diary-entry-key
3817 'org-agenda-diary-entry))))))
3819 (defgroup org-latex nil
3820 "Options for embedding LaTeX code into Org-mode."
3821 :tag "Org LaTeX"
3822 :group 'org)
3824 (defcustom org-format-latex-options
3825 '(:foreground default :background default :scale 1.0
3826 :html-foreground "Black" :html-background "Transparent"
3827 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3828 "Options for creating images from LaTeX fragments.
3829 This is a property list with the following properties:
3830 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3831 `default' means use the foreground of the default face.
3832 `auto' means use the foreground from the text face.
3833 :background the background color, or \"Transparent\".
3834 `default' means use the background of the default face.
3835 `auto' means use the background from the text face.
3836 :scale a scaling factor for the size of the images, to get more pixels
3837 :html-foreground, :html-background, :html-scale
3838 the same numbers for HTML export.
3839 :matchers a list indicating which matchers should be used to
3840 find LaTeX fragments. Valid members of this list are:
3841 \"begin\" find environments
3842 \"$1\" find single characters surrounded by $.$
3843 \"$\" find math expressions surrounded by $...$
3844 \"$$\" find math expressions surrounded by $$....$$
3845 \"\\(\" find math expressions surrounded by \\(...\\)
3846 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3847 :group 'org-latex
3848 :type 'plist)
3850 (defcustom org-format-latex-signal-error t
3851 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3852 When nil, just push out a message."
3853 :group 'org-latex
3854 :version "24.1"
3855 :type 'boolean)
3857 (defcustom org-latex-to-mathml-jar-file nil
3858 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3859 Use this to specify additional executable file say a jar file.
3861 When using MathToWeb as the converter, specify the full-path to
3862 your mathtoweb.jar file."
3863 :group 'org-latex
3864 :version "24.1"
3865 :type '(choice
3866 (const :tag "None" nil)
3867 (file :tag "JAR file" :must-match t)))
3869 (defcustom org-latex-to-mathml-convert-command nil
3870 "Command to convert LaTeX fragments to MathML.
3871 Replace format-specifiers in the command as noted below and use
3872 `shell-command' to convert LaTeX to MathML.
3873 %j: Executable file in fully expanded form as specified by
3874 `org-latex-to-mathml-jar-file'.
3875 %I: Input LaTeX file in fully expanded form
3876 %o: Output MathML file
3877 This command is used by `org-create-math-formula'.
3879 When using MathToWeb as the converter, set this to
3880 \"java -jar %j -unicode -force -df %o %I\"."
3881 :group 'org-latex
3882 :version "24.1"
3883 :type '(choice
3884 (const :tag "None" nil)
3885 (string :tag "\nShell command")))
3887 (defcustom org-latex-create-formula-image-program 'dvipng
3888 "Program to convert LaTeX fragments with.
3890 dvipng Process the LaTeX fragments to dvi file, then convert
3891 dvi files to png files using dvipng.
3892 This will also include processing of non-math environments.
3893 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3894 to convert pdf files to png files"
3895 :group 'org-latex
3896 :version "24.1"
3897 :type '(choice
3898 (const :tag "dvipng" dvipng)
3899 (const :tag "imagemagick" imagemagick)))
3901 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3902 "Path to store latex preview images.
3903 A relative path here creates many directories relative to the
3904 processed org files paths. An absolute path puts all preview
3905 images at the same place."
3906 :group 'org-latex
3907 :version "24.3"
3908 :type 'string)
3910 (defun org-format-latex-mathml-available-p ()
3911 "Return t if `org-latex-to-mathml-convert-command' is usable."
3912 (save-match-data
3913 (when (and (boundp 'org-latex-to-mathml-convert-command)
3914 org-latex-to-mathml-convert-command)
3915 (let ((executable (car (split-string
3916 org-latex-to-mathml-convert-command))))
3917 (when (executable-find executable)
3918 (if (string-match
3919 "%j" org-latex-to-mathml-convert-command)
3920 (file-readable-p org-latex-to-mathml-jar-file)
3921 t))))))
3923 (defcustom org-format-latex-header "\\documentclass{article}
3924 \\usepackage[usenames]{color}
3925 \[PACKAGES]
3926 \[DEFAULT-PACKAGES]
3927 \\pagestyle{empty} % do not remove
3928 % The settings below are copied from fullpage.sty
3929 \\setlength{\\textwidth}{\\paperwidth}
3930 \\addtolength{\\textwidth}{-3cm}
3931 \\setlength{\\oddsidemargin}{1.5cm}
3932 \\addtolength{\\oddsidemargin}{-2.54cm}
3933 \\setlength{\\evensidemargin}{\\oddsidemargin}
3934 \\setlength{\\textheight}{\\paperheight}
3935 \\addtolength{\\textheight}{-\\headheight}
3936 \\addtolength{\\textheight}{-\\headsep}
3937 \\addtolength{\\textheight}{-\\footskip}
3938 \\addtolength{\\textheight}{-3cm}
3939 \\setlength{\\topmargin}{1.5cm}
3940 \\addtolength{\\topmargin}{-2.54cm}"
3941 "The document header used for processing LaTeX fragments.
3942 It is imperative that this header make sure that no page number
3943 appears on the page. The package defined in the variables
3944 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3945 will either replace the placeholder \"[PACKAGES]\" in this
3946 header, or they will be appended."
3947 :group 'org-latex
3948 :type 'string)
3950 (defun org-set-packages-alist (var val)
3951 "Set the packages alist and make sure it has 3 elements per entry."
3952 (set var (mapcar (lambda (x)
3953 (if (and (consp x) (= (length x) 2))
3954 (list (car x) (nth 1 x) t)
3956 val)))
3958 (defun org-get-packages-alist (var)
3959 "Get the packages alist and make sure it has 3 elements per entry."
3960 (mapcar (lambda (x)
3961 (if (and (consp x) (= (length x) 2))
3962 (list (car x) (nth 1 x) t)
3964 (default-value var)))
3966 (defcustom org-latex-default-packages-alist
3967 '(("AUTO" "inputenc" t)
3968 ("T1" "fontenc" t)
3969 ("" "fixltx2e" nil)
3970 ("" "graphicx" t)
3971 ("" "longtable" nil)
3972 ("" "float" nil)
3973 ("" "wrapfig" nil)
3974 ("" "rotating" nil)
3975 ("normalem" "ulem" t)
3976 ("" "amsmath" t)
3977 ("" "textcomp" t)
3978 ("" "marvosym" t)
3979 ("" "wasysym" t)
3980 ("" "amssymb" t)
3981 ("" "hyperref" nil)
3982 "\\tolerance=1000")
3983 "Alist of default packages to be inserted in the header.
3985 Change this only if one of the packages here causes an
3986 incompatibility with another package you are using.
3988 The packages in this list are needed by one part or another of
3989 Org mode to function properly:
3991 - inputenc, fontenc: for basic font and character selection
3992 - fixltx2e: Important patches of LaTeX itself
3993 - graphicx: for including images
3994 - longtable: For multipage tables
3995 - float, wrapfig: for figure placement
3996 - rotating: for sideways figures and tables
3997 - ulem: for underline and strike-through
3998 - amsmath: for subscript and superscript and math environments
3999 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4000 for interpreting the entities in `org-entities'. You can skip
4001 some of these packages if you don't use any of their symbols.
4002 - hyperref: for cross references
4004 Therefore you should not modify this variable unless you know
4005 what you are doing. The one reason to change it anyway is that
4006 you might be loading some other package that conflicts with one
4007 of the default packages. Each cell is of the format
4008 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
4009 the package also needs to be included when compiling LaTeX
4010 snippets into images for inclusion into non-LaTeX output."
4011 :group 'org-latex
4012 :group 'org-export-latex
4013 :set 'org-set-packages-alist
4014 :get 'org-get-packages-alist
4015 :version "24.1"
4016 :type '(repeat
4017 (choice
4018 (list :tag "options/package pair"
4019 (string :tag "options")
4020 (string :tag "package")
4021 (boolean :tag "Snippet"))
4022 (string :tag "A line of LaTeX"))))
4024 (defcustom org-latex-packages-alist nil
4025 "Alist of packages to be inserted in every LaTeX header.
4027 These will be inserted after `org-latex-default-packages-alist'.
4028 Each cell is of the format:
4030 \(\"options\" \"package\" snippet-flag)
4032 SNIPPET-FLAG, when t, indicates that this package is also needed
4033 when turning LaTeX snippets into images for inclusion into
4034 non-LaTeX output.
4036 Make sure that you only list packages here which:
4038 - you want in every file
4039 - do not conflict with the setup in `org-format-latex-header'.
4040 - do not conflict with the default packages in
4041 `org-latex-default-packages-alist'."
4042 :group 'org-latex
4043 :group 'org-export-latex
4044 :set 'org-set-packages-alist
4045 :get 'org-get-packages-alist
4046 :type '(repeat
4047 (choice
4048 (list :tag "options/package pair"
4049 (string :tag "options")
4050 (string :tag "package")
4051 (boolean :tag "Snippet"))
4052 (string :tag "A line of LaTeX"))))
4054 (defgroup org-appearance nil
4055 "Settings for Org-mode appearance."
4056 :tag "Org Appearance"
4057 :group 'org)
4059 (defcustom org-level-color-stars-only nil
4060 "Non-nil means fontify only the stars in each headline.
4061 When nil, the entire headline is fontified.
4062 Changing it requires restart of `font-lock-mode' to become effective
4063 also in regions already fontified."
4064 :group 'org-appearance
4065 :type 'boolean)
4067 (defcustom org-hide-leading-stars nil
4068 "Non-nil means hide the first N-1 stars in a headline.
4069 This works by using the face `org-hide' for these stars. This
4070 face is white for a light background, and black for a dark
4071 background. You may have to customize the face `org-hide' to
4072 make this work.
4073 Changing it requires restart of `font-lock-mode' to become effective
4074 also in regions already fontified.
4075 You may also set this on a per-file basis by adding one of the following
4076 lines to the buffer:
4078 #+STARTUP: hidestars
4079 #+STARTUP: showstars"
4080 :group 'org-appearance
4081 :type 'boolean)
4083 (defcustom org-hidden-keywords nil
4084 "List of symbols corresponding to keywords to be hidden the org buffer.
4085 For example, a value '(title) for this list will make the document's title
4086 appear in the buffer without the initial #+TITLE: keyword."
4087 :group 'org-appearance
4088 :version "24.1"
4089 :type '(set (const :tag "#+AUTHOR" author)
4090 (const :tag "#+DATE" date)
4091 (const :tag "#+EMAIL" email)
4092 (const :tag "#+TITLE" title)))
4094 (defcustom org-custom-properties nil
4095 "List of properties (as strings) with a special meaning.
4096 The default use of these custom properties is to let the user
4097 hide them with `org-toggle-custom-properties-visibility'."
4098 :group 'org-properties
4099 :group 'org-appearance
4100 :version "24.3"
4101 :type '(repeat (string :tag "Property Name")))
4103 (defcustom org-fontify-done-headline nil
4104 "Non-nil means change the face of a headline if it is marked DONE.
4105 Normally, only the TODO/DONE keyword indicates the state of a headline.
4106 When this is non-nil, the headline after the keyword is set to the
4107 `org-headline-done' as an additional indication."
4108 :group 'org-appearance
4109 :type 'boolean)
4111 (defcustom org-fontify-emphasized-text t
4112 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4113 Changing this variable requires a restart of Emacs to take effect."
4114 :group 'org-appearance
4115 :type 'boolean)
4117 (defcustom org-fontify-whole-heading-line nil
4118 "Non-nil means fontify the whole line for headings.
4119 This is useful when setting a background color for the
4120 org-level-* faces."
4121 :group 'org-appearance
4122 :type 'boolean)
4124 (defcustom org-highlight-latex-and-related nil
4125 "Non-nil means highlight LaTeX related syntax in the buffer.
4126 When non nil, the value should be a list containing any of the
4127 following symbols:
4128 `latex' Highlight LaTeX snippets and environments.
4129 `script' Highlight subscript and superscript.
4130 `entities' Highlight entities."
4131 :group 'org-appearance
4132 :version "24.4"
4133 :package-version '(Org . "8.0")
4134 :type '(choice
4135 (const :tag "No highlighting" nil)
4136 (set :greedy t :tag "Highlight"
4137 (const :tag "LaTeX snippets and environments" latex)
4138 (const :tag "Subscript and superscript" script)
4139 (const :tag "Entities" entities))))
4141 (defcustom org-hide-emphasis-markers nil
4142 "Non-nil mean font-lock should hide the emphasis marker characters."
4143 :group 'org-appearance
4144 :type 'boolean)
4146 (defcustom org-hide-macro-markers nil
4147 "Non-nil mean font-lock should hide the brackets marking macro calls."
4148 :group 'org-appearance
4149 :type 'boolean)
4151 (defcustom org-pretty-entities nil
4152 "Non-nil means show entities as UTF8 characters.
4153 When nil, the \\name form remains in the buffer."
4154 :group 'org-appearance
4155 :version "24.1"
4156 :type 'boolean)
4158 (defcustom org-pretty-entities-include-sub-superscripts t
4159 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4160 :group 'org-appearance
4161 :version "24.1"
4162 :type 'boolean)
4164 (defvar org-emph-re nil
4165 "Regular expression for matching emphasis.
4166 After a match, the match groups contain these elements:
4167 0 The match of the full regular expression, including the characters
4168 before and after the proper match
4169 1 The character before the proper match, or empty at beginning of line
4170 2 The proper match, including the leading and trailing markers
4171 3 The leading marker like * or /, indicating the type of highlighting
4172 4 The text between the emphasis markers, not including the markers
4173 5 The character after the match, empty at the end of a line")
4174 (defvar org-verbatim-re nil
4175 "Regular expression for matching verbatim text.")
4176 (defvar org-emphasis-regexp-components) ; defined just below
4177 (defvar org-emphasis-alist) ; defined just below
4178 (defun org-set-emph-re (var val)
4179 "Set variable and compute the emphasis regular expression."
4180 (set var val)
4181 (when (and (boundp 'org-emphasis-alist)
4182 (boundp 'org-emphasis-regexp-components)
4183 org-emphasis-alist org-emphasis-regexp-components)
4184 (let* ((e org-emphasis-regexp-components)
4185 (pre (car e))
4186 (post (nth 1 e))
4187 (border (nth 2 e))
4188 (body (nth 3 e))
4189 (nl (nth 4 e))
4190 (body1 (concat body "*?"))
4191 (markers (mapconcat 'car org-emphasis-alist ""))
4192 (vmarkers (mapconcat
4193 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4194 org-emphasis-alist "")))
4195 ;; make sure special characters appear at the right position in the class
4196 (if (string-match "\\^" markers)
4197 (setq markers (concat (replace-match "" t t markers) "^")))
4198 (if (string-match "-" markers)
4199 (setq markers (concat (replace-match "" t t markers) "-")))
4200 (if (string-match "\\^" vmarkers)
4201 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4202 (if (string-match "-" vmarkers)
4203 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4204 (if (> nl 0)
4205 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4206 (int-to-string nl) "\\}")))
4207 ;; Make the regexp
4208 (setq org-emph-re
4209 (concat "\\([" pre "]\\|^\\)"
4210 "\\("
4211 "\\([" markers "]\\)"
4212 "\\("
4213 "[^" border "]\\|"
4214 "[^" border "]"
4215 body1
4216 "[^" border "]"
4217 "\\)"
4218 "\\3\\)"
4219 "\\([" post "]\\|$\\)"))
4220 (setq org-verbatim-re
4221 (concat "\\([" pre "]\\|^\\)"
4222 "\\("
4223 "\\([" vmarkers "]\\)"
4224 "\\("
4225 "[^" border "]\\|"
4226 "[^" border "]"
4227 body1
4228 "[^" border "]"
4229 "\\)"
4230 "\\3\\)"
4231 "\\([" post "]\\|$\\)")))))
4233 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4234 ;; set this option proved cumbersome. See this message/thread:
4235 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4236 (defvar org-emphasis-regexp-components
4237 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4238 "Components used to build the regular expression for emphasis.
4239 This is a list with five entries. Terminology: In an emphasis string
4240 like \" *strong word* \", we call the initial space PREMATCH, the final
4241 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4242 and \"trong wor\" is the body. The different components in this variable
4243 specify what is allowed/forbidden in each part:
4245 pre Chars allowed as prematch. Beginning of line will be allowed too.
4246 post Chars allowed as postmatch. End of line will be allowed too.
4247 border The chars *forbidden* as border characters.
4248 body-regexp A regexp like \".\" to match a body character. Don't use
4249 non-shy groups here, and don't allow newline here.
4250 newline The maximum number of newlines allowed in an emphasis exp.
4252 You need to reload Org or to restart Emacs after customizing this.")
4254 (defcustom org-emphasis-alist
4255 `(("*" bold)
4256 ("/" italic)
4257 ("_" underline)
4258 ("=" org-verbatim verbatim)
4259 ("~" org-code verbatim)
4260 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4261 "Alist of characters and faces to emphasize text.
4262 Text starting and ending with a special character will be emphasized,
4263 for example *bold*, _underlined_ and /italic/. This variable sets the
4264 marker characters and the face to be used by font-lock for highlighting
4265 in Org-mode Emacs buffers.
4267 You need to reload Org or to restart Emacs after customizing this."
4268 :group 'org-appearance
4269 :set 'org-set-emph-re
4270 :version "24.4"
4271 :package-version '(Org . "8.0")
4272 :type '(repeat
4273 (list
4274 (string :tag "Marker character")
4275 (choice
4276 (face :tag "Font-lock-face")
4277 (plist :tag "Face property list"))
4278 (option (const verbatim)))))
4280 (defvar org-protecting-blocks
4281 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4282 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4283 This is needed for font-lock setup.")
4285 ;;; Miscellaneous options
4287 (defgroup org-completion nil
4288 "Completion in Org-mode."
4289 :tag "Org Completion"
4290 :group 'org)
4292 (defcustom org-completion-use-ido nil
4293 "Non-nil means use ido completion wherever possible.
4294 Note that `ido-mode' must be active for this variable to be relevant.
4295 If you decide to turn this variable on, you might well want to turn off
4296 `org-outline-path-complete-in-steps'.
4297 See also `org-completion-use-iswitchb'."
4298 :group 'org-completion
4299 :type 'boolean)
4301 (defcustom org-completion-use-iswitchb nil
4302 "Non-nil means use iswitchb completion wherever possible.
4303 Note that `iswitchb-mode' must be active for this variable to be relevant.
4304 If you decide to turn this variable on, you might well want to turn off
4305 `org-outline-path-complete-in-steps'.
4306 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4307 :group 'org-completion
4308 :type 'boolean)
4310 (defcustom org-completion-fallback-command 'hippie-expand
4311 "The expansion command called by \\[pcomplete] in normal context.
4312 Normal means, no org-mode-specific context."
4313 :group 'org-completion
4314 :type 'function)
4316 ;;; Functions and variables from their packages
4317 ;; Declared here to avoid compiler warnings
4319 ;; XEmacs only
4320 (defvar outline-mode-menu-heading)
4321 (defvar outline-mode-menu-show)
4322 (defvar outline-mode-menu-hide)
4323 (defvar zmacs-regions) ; XEmacs regions
4325 ;; Emacs only
4326 (defvar mark-active)
4328 ;; Various packages
4329 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4330 (declare-function calendar-forward-day "cal-move" (arg))
4331 (declare-function calendar-goto-date "cal-move" (date))
4332 (declare-function calendar-goto-today "cal-move" ())
4333 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4334 (defvar calc-embedded-close-formula)
4335 (defvar calc-embedded-open-formula)
4336 (declare-function cdlatex-tab "ext:cdlatex" ())
4337 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4338 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4339 (defvar font-lock-unfontify-region-function)
4340 (declare-function iswitchb-read-buffer "iswitchb"
4341 (prompt &optional default require-match start matches-set))
4342 (defvar iswitchb-temp-buflist)
4343 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4344 (defvar org-agenda-tags-todo-honor-ignore-options)
4345 (declare-function org-agenda-skip "org-agenda" ())
4346 (declare-function
4347 org-agenda-format-item "org-agenda"
4348 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4349 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4350 (declare-function org-agenda-change-all-lines "org-agenda"
4351 (newhead hdmarker &optional fixface just-this))
4352 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4353 (declare-function org-agenda-maybe-redo "org-agenda" ())
4354 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4355 (beg end))
4356 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4357 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4358 "org-agenda" (&optional end))
4359 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4360 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4361 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4362 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4363 (declare-function org-indent-mode "org-indent" (&optional arg))
4364 (declare-function parse-time-string "parse-time" (string))
4365 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4366 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4367 (defvar remember-data-file)
4368 (defvar texmathp-why)
4369 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4370 (declare-function table--at-cell-p "table" (position &optional object at-column))
4372 ;;;###autoload
4373 (defun turn-on-orgtbl ()
4374 "Unconditionally turn on `orgtbl-mode'."
4375 (require 'org-table)
4376 (orgtbl-mode 1))
4378 (defun org-at-table-p (&optional table-type)
4379 "Return t if the cursor is inside an org-type table.
4380 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4381 (if org-enable-table-editor
4382 (save-excursion
4383 (beginning-of-line 1)
4384 (looking-at (if table-type org-table-any-line-regexp
4385 org-table-line-regexp)))
4386 nil))
4387 (defsubst org-table-p () (org-at-table-p))
4389 (defun org-at-table.el-p ()
4390 "Return t if and only if we are at a table.el table."
4391 (and (org-at-table-p 'any)
4392 (save-excursion
4393 (goto-char (org-table-begin 'any))
4394 (looking-at org-table1-hline-regexp))))
4396 (defun org-table-recognize-table.el ()
4397 "If there is a table.el table nearby, recognize it and move into it."
4398 (if org-table-tab-recognizes-table.el
4399 (if (org-at-table.el-p)
4400 (progn
4401 (beginning-of-line 1)
4402 (if (looking-at org-table-dataline-regexp)
4404 (if (looking-at org-table1-hline-regexp)
4405 (progn
4406 (beginning-of-line 2)
4407 (if (looking-at org-table-any-border-regexp)
4408 (beginning-of-line -1)))))
4409 (if (re-search-forward "|" (org-table-end t) t)
4410 (progn
4411 (require 'table)
4412 (if (table--at-cell-p (point))
4414 (message "recognizing table.el table...")
4415 (table-recognize-table)
4416 (message "recognizing table.el table...done")))
4417 (error "This should not happen"))
4419 nil)
4420 nil))
4422 (defun org-at-table-hline-p ()
4423 "Return t if the cursor is inside a hline in a table."
4424 (if org-enable-table-editor
4425 (save-excursion
4426 (beginning-of-line 1)
4427 (looking-at org-table-hline-regexp))
4428 nil))
4430 (defun org-table-map-tables (function &optional quietly)
4431 "Apply FUNCTION to the start of all tables in the buffer."
4432 (save-excursion
4433 (save-restriction
4434 (widen)
4435 (goto-char (point-min))
4436 (while (re-search-forward org-table-any-line-regexp nil t)
4437 (unless quietly
4438 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4439 (beginning-of-line 1)
4440 (when (and (looking-at org-table-line-regexp)
4441 ;; Exclude tables in src/example/verbatim/clocktable blocks
4442 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4443 (save-excursion (funcall function))
4444 (or (looking-at org-table-line-regexp)
4445 (forward-char 1)))
4446 (re-search-forward org-table-any-border-regexp nil 1))))
4447 (unless quietly (message "Mapping tables: done")))
4449 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4450 (declare-function org-clock-update-mode-line "org-clock" ())
4451 (declare-function org-resolve-clocks "org-clock"
4452 (&optional also-non-dangling-p prompt last-valid))
4454 (defun org-at-TBLFM-p (&optional pos)
4455 "Return t when point (or POS) is in #+TBLFM line."
4456 (save-excursion
4457 (let ((pos pos)))
4458 (goto-char (or pos (point)))
4459 (beginning-of-line 1)
4460 (looking-at org-TBLFM-regexp)))
4462 (defvar org-clock-start-time)
4463 (defvar org-clock-marker (make-marker)
4464 "Marker recording the last clock-in.")
4465 (defvar org-clock-hd-marker (make-marker)
4466 "Marker recording the last clock-in, but the headline position.")
4467 (defvar org-clock-heading ""
4468 "The heading of the current clock entry.")
4469 (defun org-clock-is-active ()
4470 "Return the buffer where the clock is currently running.
4471 Return nil if no clock is running."
4472 (marker-buffer org-clock-marker))
4474 (defun org-check-running-clock ()
4475 "Check if the current buffer contains the running clock.
4476 If yes, offer to stop it and to save the buffer with the changes."
4477 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4478 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4479 (buffer-name))))
4480 (org-clock-out)
4481 (when (y-or-n-p "Save changed buffer?")
4482 (save-buffer))))
4484 (defun org-clocktable-try-shift (dir n)
4485 "Check if this line starts a clock table, if yes, shift the time block."
4486 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4487 (org-clocktable-shift dir n)))
4489 ;;;###autoload
4490 (defun org-clock-persistence-insinuate ()
4491 "Set up hooks for clock persistence."
4492 (require 'org-clock)
4493 (add-hook 'org-mode-hook 'org-clock-load)
4494 (add-hook 'kill-emacs-hook 'org-clock-save))
4496 (defgroup org-archive nil
4497 "Options concerning archiving in Org-mode."
4498 :tag "Org Archive"
4499 :group 'org-structure)
4501 (defcustom org-archive-location "%s_archive::"
4502 "The location where subtrees should be archived.
4504 The value of this variable is a string, consisting of two parts,
4505 separated by a double-colon. The first part is a filename and
4506 the second part is a headline.
4508 When the filename is omitted, archiving happens in the same file.
4509 %s in the filename will be replaced by the current file
4510 name (without the directory part). Archiving to a different file
4511 is useful to keep archived entries from contributing to the
4512 Org-mode Agenda.
4514 The archived entries will be filed as subtrees of the specified
4515 headline. When the headline is omitted, the subtrees are simply
4516 filed away at the end of the file, as top-level entries. Also in
4517 the heading you can use %s to represent the file name, this can be
4518 useful when using the same archive for a number of different files.
4520 Here are a few examples:
4521 \"%s_archive::\"
4522 If the current file is Projects.org, archive in file
4523 Projects.org_archive, as top-level trees. This is the default.
4525 \"::* Archived Tasks\"
4526 Archive in the current file, under the top-level headline
4527 \"* Archived Tasks\".
4529 \"~/org/archive.org::\"
4530 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4532 \"~/org/archive.org::* From %s\"
4533 Archive in file ~/org/archive.org (absolute path), under headlines
4534 \"From FILENAME\" where file name is the current file name.
4536 \"~/org/datetree.org::datetree/* Finished Tasks\"
4537 The \"datetree/\" string is special, signifying to archive
4538 items to the datetree. Items are placed in either the CLOSED
4539 date of the item, or the current date if there is no CLOSED date.
4540 The heading will be a subentry to the current date. There doesn't
4541 need to be a heading, but there always needs to be a slash after
4542 datetree. For example, to store archived items directly in the
4543 datetree, use \"~/org/datetree.org::datetree/\".
4545 \"basement::** Finished Tasks\"
4546 Archive in file ./basement (relative path), as level 3 trees
4547 below the level 2 heading \"** Finished Tasks\".
4549 You may set this option on a per-file basis by adding to the buffer a
4550 line like
4552 #+ARCHIVE: basement::** Finished Tasks
4554 You may also define it locally for a subtree by setting an ARCHIVE property
4555 in the entry. If such a property is found in an entry, or anywhere up
4556 the hierarchy, it will be used."
4557 :group 'org-archive
4558 :type 'string)
4560 (defcustom org-agenda-skip-archived-trees t
4561 "Non-nil means the agenda will skip any items located in archived trees.
4562 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4563 variable is no longer recommended, you should leave it at the value t.
4564 Instead, use the key `v' to cycle the archives-mode in the agenda."
4565 :group 'org-archive
4566 :group 'org-agenda-skip
4567 :type 'boolean)
4569 (defcustom org-columns-skip-archived-trees t
4570 "Non-nil means ignore archived trees when creating column view."
4571 :group 'org-archive
4572 :group 'org-properties
4573 :type 'boolean)
4575 (defcustom org-cycle-open-archived-trees nil
4576 "Non-nil means `org-cycle' will open archived trees.
4577 An archived tree is a tree marked with the tag ARCHIVE.
4578 When nil, archived trees will stay folded. You can still open them with
4579 normal outline commands like `show-all', but not with the cycling commands."
4580 :group 'org-archive
4581 :group 'org-cycle
4582 :type 'boolean)
4584 (defcustom org-sparse-tree-open-archived-trees nil
4585 "Non-nil means sparse tree construction shows matches in archived trees.
4586 When nil, matches in these trees are highlighted, but the trees are kept in
4587 collapsed state."
4588 :group 'org-archive
4589 :group 'org-sparse-trees
4590 :type 'boolean)
4592 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4593 "The default date type when building a sparse tree.
4594 When this is nil, a date is a scheduled or a deadline timestamp.
4595 Otherwise, these types are allowed:
4597 all: all timestamps
4598 active: only active timestamps (<...>)
4599 inactive: only inactive timestamps (<...)
4600 scheduled: only scheduled timestamps
4601 deadline: only deadline timestamps"
4602 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4603 (const :tag "All timestamps" all)
4604 (const :tag "Only active timestamps" active)
4605 (const :tag "Only inactive timestamps" inactive)
4606 (const :tag "Only scheduled timestamps" scheduled)
4607 (const :tag "Only deadline timestamps" deadline)
4608 (const :tag "Only closed timestamps" closed))
4609 :version "24.3"
4610 :group 'org-sparse-trees)
4612 (defun org-cycle-hide-archived-subtrees (state)
4613 "Re-hide all archived subtrees after a visibility state change."
4614 (when (and (not org-cycle-open-archived-trees)
4615 (not (memq state '(overview folded))))
4616 (save-excursion
4617 (let* ((globalp (memq state '(contents all)))
4618 (beg (if globalp (point-min) (point)))
4619 (end (if globalp (point-max) (org-end-of-subtree t))))
4620 (org-hide-archived-subtrees beg end)
4621 (goto-char beg)
4622 (if (looking-at (concat ".*:" org-archive-tag ":"))
4623 (message "%s" (substitute-command-keys
4624 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4626 (defun org-force-cycle-archived ()
4627 "Cycle subtree even if it is archived."
4628 (interactive)
4629 (setq this-command 'org-cycle)
4630 (let ((org-cycle-open-archived-trees t))
4631 (call-interactively 'org-cycle)))
4633 (defun org-hide-archived-subtrees (beg end)
4634 "Re-hide all archived subtrees after a visibility state change."
4635 (save-excursion
4636 (let* ((re (concat ":" org-archive-tag ":")))
4637 (goto-char beg)
4638 (while (re-search-forward re end t)
4639 (when (org-at-heading-p)
4640 (org-flag-subtree t)
4641 (org-end-of-subtree t))))))
4643 (declare-function outline-end-of-heading "outline" ())
4644 (declare-function outline-flag-region "outline" (from to flag))
4645 (defun org-flag-subtree (flag)
4646 (save-excursion
4647 (org-back-to-heading t)
4648 (outline-end-of-heading)
4649 (outline-flag-region (point)
4650 (progn (org-end-of-subtree t) (point))
4651 flag)))
4653 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4655 ;; Declare Column View Code
4657 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4658 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4659 (declare-function org-columns-compute "org-colview" (property))
4661 ;; Declare ID code
4663 (declare-function org-id-store-link "org-id")
4664 (declare-function org-id-locations-load "org-id")
4665 (declare-function org-id-locations-save "org-id")
4666 (defvar org-id-track-globally)
4668 ;;; Variables for pre-computed regular expressions, all buffer local
4670 (defvar org-todo-regexp nil
4671 "Matches any of the TODO state keywords.")
4672 (make-variable-buffer-local 'org-todo-regexp)
4673 (defvar org-not-done-regexp nil
4674 "Matches any of the TODO state keywords except the last one.")
4675 (make-variable-buffer-local 'org-not-done-regexp)
4676 (defvar org-not-done-heading-regexp nil
4677 "Matches a TODO headline that is not done.")
4678 (make-variable-buffer-local 'org-not-done-regexp)
4679 (defvar org-todo-line-regexp nil
4680 "Matches a headline and puts TODO state into group 2 if present.")
4681 (make-variable-buffer-local 'org-todo-line-regexp)
4682 (defvar org-complex-heading-regexp nil
4683 "Matches a headline and puts everything into groups:
4684 group 1: the stars
4685 group 2: The todo keyword, maybe
4686 group 3: Priority cookie
4687 group 4: True headline
4688 group 5: Tags")
4689 (make-variable-buffer-local 'org-complex-heading-regexp)
4690 (defvar org-complex-heading-regexp-format nil
4691 "Printf format to make regexp to match an exact headline.
4692 This regexp will match the headline of any node which has the
4693 exact headline text that is put into the format, but may have any
4694 TODO state, priority and tags.")
4695 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4696 (defvar org-todo-line-tags-regexp nil
4697 "Matches a headline and puts TODO state into group 2 if present.
4698 Also put tags into group 4 if tags are present.")
4699 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4700 (defvar org-ds-keyword-length 12
4701 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4702 (make-variable-buffer-local 'org-ds-keyword-length)
4703 (defvar org-deadline-regexp nil
4704 "Matches the DEADLINE keyword.")
4705 (make-variable-buffer-local 'org-deadline-regexp)
4706 (defvar org-deadline-time-regexp nil
4707 "Matches the DEADLINE keyword together with a time stamp.")
4708 (make-variable-buffer-local 'org-deadline-time-regexp)
4709 (defvar org-deadline-time-hour-regexp nil
4710 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4711 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4712 (defvar org-deadline-line-regexp nil
4713 "Matches the DEADLINE keyword and the rest of the line.")
4714 (make-variable-buffer-local 'org-deadline-line-regexp)
4715 (defvar org-scheduled-regexp nil
4716 "Matches the SCHEDULED keyword.")
4717 (make-variable-buffer-local 'org-scheduled-regexp)
4718 (defvar org-scheduled-time-regexp nil
4719 "Matches the SCHEDULED keyword together with a time stamp.")
4720 (make-variable-buffer-local 'org-scheduled-time-regexp)
4721 (defvar org-scheduled-time-hour-regexp nil
4722 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4723 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4724 (defvar org-closed-time-regexp nil
4725 "Matches the CLOSED keyword together with a time stamp.")
4726 (make-variable-buffer-local 'org-closed-time-regexp)
4728 (defvar org-keyword-time-regexp nil
4729 "Matches any of the 4 keywords, together with the time stamp.")
4730 (make-variable-buffer-local 'org-keyword-time-regexp)
4731 (defvar org-keyword-time-not-clock-regexp nil
4732 "Matches any of the 3 keywords, together with the time stamp.")
4733 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4734 (defvar org-maybe-keyword-time-regexp nil
4735 "Matches a timestamp, possibly preceded by a keyword.")
4736 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4737 (defvar org-all-time-keywords nil
4738 "List of time keywords.")
4739 (make-variable-buffer-local 'org-all-time-keywords)
4741 (defconst org-plain-time-of-day-regexp
4742 (concat
4743 "\\(\\<[012]?[0-9]"
4744 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4745 "\\(--?"
4746 "\\(\\<[012]?[0-9]"
4747 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4748 "\\)?")
4749 "Regular expression to match a plain time or time range.
4750 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4751 groups carry important information:
4752 0 the full match
4753 1 the first time, range or not
4754 8 the second time, if it is a range.")
4756 (defconst org-plain-time-extension-regexp
4757 (concat
4758 "\\(\\<[012]?[0-9]"
4759 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4760 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4761 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4762 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4763 groups carry important information:
4764 0 the full match
4765 7 hours of duration
4766 9 minutes of duration")
4768 (defconst org-stamp-time-of-day-regexp
4769 (concat
4770 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4771 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4772 "\\(--?"
4773 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4774 "Regular expression to match a timestamp time or time range.
4775 After a match, the following groups carry important information:
4776 0 the full match
4777 1 date plus weekday, for back referencing to make sure both times are on the same day
4778 2 the first time, range or not
4779 4 the second time, if it is a range.")
4781 (defconst org-startup-options
4782 '(("fold" org-startup-folded t)
4783 ("overview" org-startup-folded t)
4784 ("nofold" org-startup-folded nil)
4785 ("showall" org-startup-folded nil)
4786 ("showeverything" org-startup-folded showeverything)
4787 ("content" org-startup-folded content)
4788 ("indent" org-startup-indented t)
4789 ("noindent" org-startup-indented nil)
4790 ("hidestars" org-hide-leading-stars t)
4791 ("showstars" org-hide-leading-stars nil)
4792 ("odd" org-odd-levels-only t)
4793 ("oddeven" org-odd-levels-only nil)
4794 ("align" org-startup-align-all-tables t)
4795 ("noalign" org-startup-align-all-tables nil)
4796 ("inlineimages" org-startup-with-inline-images t)
4797 ("noinlineimages" org-startup-with-inline-images nil)
4798 ("latexpreview" org-startup-with-latex-preview t)
4799 ("nolatexpreview" org-startup-with-latex-preview nil)
4800 ("customtime" org-display-custom-times t)
4801 ("logdone" org-log-done time)
4802 ("lognotedone" org-log-done note)
4803 ("nologdone" org-log-done nil)
4804 ("lognoteclock-out" org-log-note-clock-out t)
4805 ("nolognoteclock-out" org-log-note-clock-out nil)
4806 ("logrepeat" org-log-repeat state)
4807 ("lognoterepeat" org-log-repeat note)
4808 ("logdrawer" org-log-into-drawer t)
4809 ("nologdrawer" org-log-into-drawer nil)
4810 ("logstatesreversed" org-log-states-order-reversed t)
4811 ("nologstatesreversed" org-log-states-order-reversed nil)
4812 ("nologrepeat" org-log-repeat nil)
4813 ("logreschedule" org-log-reschedule time)
4814 ("lognotereschedule" org-log-reschedule note)
4815 ("nologreschedule" org-log-reschedule nil)
4816 ("logredeadline" org-log-redeadline time)
4817 ("lognoteredeadline" org-log-redeadline note)
4818 ("nologredeadline" org-log-redeadline nil)
4819 ("logrefile" org-log-refile time)
4820 ("lognoterefile" org-log-refile note)
4821 ("nologrefile" org-log-refile nil)
4822 ("fninline" org-footnote-define-inline t)
4823 ("nofninline" org-footnote-define-inline nil)
4824 ("fnlocal" org-footnote-section nil)
4825 ("fnauto" org-footnote-auto-label t)
4826 ("fnprompt" org-footnote-auto-label nil)
4827 ("fnconfirm" org-footnote-auto-label confirm)
4828 ("fnplain" org-footnote-auto-label plain)
4829 ("fnadjust" org-footnote-auto-adjust t)
4830 ("nofnadjust" org-footnote-auto-adjust nil)
4831 ("constcgs" constants-unit-system cgs)
4832 ("constSI" constants-unit-system SI)
4833 ("noptag" org-tag-persistent-alist nil)
4834 ("hideblocks" org-hide-block-startup t)
4835 ("nohideblocks" org-hide-block-startup nil)
4836 ("beamer" org-startup-with-beamer-mode t)
4837 ("entitiespretty" org-pretty-entities t)
4838 ("entitiesplain" org-pretty-entities nil))
4839 "Variable associated with STARTUP options for org-mode.
4840 Each element is a list of three items: the startup options (as written
4841 in the #+STARTUP line), the corresponding variable, and the value to set
4842 this variable to if the option is found. An optional forth element PUSH
4843 means to push this value onto the list in the variable.")
4845 (defun org-update-property-plist (key val props)
4846 "Update PROPS with KEY and VAL."
4847 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4848 (key (if appending (substring key 0 (- (length key) 1)) key))
4849 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4850 (previous (cdr (assoc key props))))
4851 (if appending
4852 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4853 (cons (cons key val) remainder))))
4855 (defcustom org-group-tags t
4856 "When non-nil (the default), use group tags.
4857 This can be turned on/off through `org-toggle-tags-groups'."
4858 :group 'org-tags
4859 :group 'org-startup
4860 :type 'boolean)
4862 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4864 (defun org-toggle-tags-groups ()
4865 "Toggle support for group tags.
4866 Support for group tags is controlled by the option
4867 `org-group-tags', which is non-nil by default."
4868 (interactive)
4869 (setq org-group-tags (not org-group-tags))
4870 (cond ((and (derived-mode-p 'org-agenda-mode)
4871 org-group-tags)
4872 (org-agenda-redo))
4873 ((derived-mode-p 'org-mode)
4874 (let ((org-inhibit-startup t)) (org-mode))))
4875 (message "Groups tags support has been turned %s"
4876 (if org-group-tags "on" "off")))
4878 (defun org-set-regexps-and-options-for-tags ()
4879 "Precompute variables used for tags."
4880 (when (derived-mode-p 'org-mode)
4881 (org-set-local 'org-file-tags nil)
4882 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4883 (splitre "[ \t]+")
4884 (start 0)
4885 tags ftags key value)
4886 (save-excursion
4887 (save-restriction
4888 (widen)
4889 (goto-char (point-min))
4890 (while (re-search-forward re nil t)
4891 (setq key (upcase (org-match-string-no-properties 1))
4892 value (org-match-string-no-properties 2))
4893 (if (stringp value) (setq value (org-trim value)))
4894 (cond
4895 ((equal key "TAGS")
4896 (setq tags (append tags (if tags '("\\n") nil)
4897 (org-split-string value splitre))))
4898 ((equal key "FILETAGS")
4899 (when (string-match "\\S-" value)
4900 (setq ftags
4901 (append
4902 ftags
4903 (apply 'append
4904 (mapcar (lambda (x) (org-split-string x ":"))
4905 (org-split-string value)))))))))))
4906 ;; Process the file tags.
4907 (and ftags (org-set-local 'org-file-tags
4908 (mapcar 'org-add-prop-inherited ftags)))
4909 (org-set-local 'org-tag-groups-alist nil)
4910 ;; Process the tags.
4911 (when (and (not tags) org-tag-alist)
4912 (setq tags
4913 (mapcar
4914 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4915 ((eq (car tg) :endgroup) "}")
4916 ((eq (car tg) :grouptags) ":")
4917 ((eq (car tg) :newline) "\n")
4918 (t (concat (car tg)
4919 (if (characterp (cdr tg))
4920 (format "(%s)" (char-to-string (cdr tg))) "")))))
4921 org-tag-alist)))
4922 (let (e tgs g)
4923 (while (setq e (pop tags))
4924 (cond
4925 ((equal e "{")
4926 (progn (push '(:startgroup) tgs)
4927 (when (equal (nth 1 tags) ":")
4928 (push (list (replace-regexp-in-string
4929 "(.+)$" "" (nth 0 tags)))
4930 org-tag-groups-alist)
4931 (setq g 0))))
4932 ((equal e ":") (push '(:grouptags) tgs))
4933 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4934 ((equal e "\\n") (push '(:newline) tgs))
4935 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4936 (push (cons (match-string 1 e)
4937 (string-to-char (match-string 2 e))) tgs)
4938 (if (and g (> g 0))
4939 (setcar org-tag-groups-alist
4940 (append (car org-tag-groups-alist)
4941 (list (match-string 1 e)))))
4942 (if g (setq g (1+ g))))
4943 (t (push (list e) tgs)
4944 (if (and g (> g 0))
4945 (setcar org-tag-groups-alist
4946 (append (car org-tag-groups-alist) (list e))))
4947 (if g (setq g (1+ g))))))
4948 (org-set-local 'org-tag-alist nil)
4949 (while (setq e (pop tgs))
4950 (or (and (stringp (car e))
4951 (assoc (car e) org-tag-alist))
4952 (push e org-tag-alist)))
4953 ;; Return a list with tag variables
4954 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4956 (defvar org-ota nil)
4957 (defun org-set-regexps-and-options ()
4958 "Precompute regular expressions used in the current buffer."
4959 (when (derived-mode-p 'org-mode)
4960 (org-set-local 'org-todo-kwd-alist nil)
4961 (org-set-local 'org-todo-key-alist nil)
4962 (org-set-local 'org-todo-key-trigger nil)
4963 (org-set-local 'org-todo-keywords-1 nil)
4964 (org-set-local 'org-done-keywords nil)
4965 (org-set-local 'org-todo-heads nil)
4966 (org-set-local 'org-todo-sets nil)
4967 (org-set-local 'org-todo-log-states nil)
4968 (org-set-local 'org-file-properties nil)
4969 (let ((re (org-make-options-regexp
4970 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4971 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4972 "SETUPFILE" "OPTIONS")
4973 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4974 (splitre "[ \t]+")
4975 (scripts org-use-sub-superscripts)
4976 kwds kws0 kwsa key log value cat arch const links hw dws
4977 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4978 (start 0))
4979 (save-excursion
4980 (save-restriction
4981 (widen)
4982 (goto-char (point-min))
4983 (while
4984 (or (and
4985 ext-setup-or-nil
4986 (not org-ota)
4987 (let (ret)
4988 (with-temp-buffer
4989 (insert ext-setup-or-nil)
4990 (let ((major-mode 'org-mode) org-ota)
4991 (setq ret (save-match-data
4992 (org-set-regexps-and-options-for-tags)))))
4993 ;; Append setupfile tags to existing tags
4994 (setq org-ota t)
4995 (setq org-file-tags
4996 (delq nil (append org-file-tags (nth 0 ret)))
4997 org-tag-alist
4998 (delq nil (append org-tag-alist (nth 1 ret)))
4999 org-tag-groups-alist
5000 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
5001 (and ext-setup-or-nil
5002 (string-match re ext-setup-or-nil start)
5003 (setq start (match-end 0)))
5004 (and (setq ext-setup-or-nil nil start 0)
5005 (re-search-forward re nil t)))
5006 (setq key (upcase (match-string 1 ext-setup-or-nil))
5007 value (org-match-string-no-properties 2 ext-setup-or-nil))
5008 (if (stringp value) (setq value (org-trim value)))
5009 (cond
5010 ((equal key "CATEGORY")
5011 (setq cat value))
5012 ((member key '("SEQ_TODO" "TODO"))
5013 (push (cons 'sequence (org-split-string value splitre)) kwds))
5014 ((equal key "TYP_TODO")
5015 (push (cons 'type (org-split-string value splitre)) kwds))
5016 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
5017 ;; general TODO-like setup
5018 (push (cons (intern (downcase (match-string 1 key)))
5019 (org-split-string value splitre)) kwds))
5020 ((equal key "COLUMNS")
5021 (org-set-local 'org-columns-default-format value))
5022 ((equal key "LINK")
5023 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5024 (push (cons (match-string 1 value)
5025 (org-trim (match-string 2 value)))
5026 links)))
5027 ((equal key "PRIORITIES")
5028 (setq prio (org-split-string value " +")))
5029 ((equal key "PROPERTY")
5030 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5031 (setq props (org-update-property-plist (match-string 1 value)
5032 (match-string 2 value)
5033 props))))
5034 ((equal key "CONSTANTS")
5035 (org-table-set-constants))
5036 ((equal key "STARTUP")
5037 (let ((opts (org-split-string value splitre))
5038 l var val)
5039 (while (setq l (pop opts))
5040 (when (setq l (assoc l org-startup-options))
5041 (setq var (nth 1 l) val (nth 2 l))
5042 (if (not (nth 3 l))
5043 (set (make-local-variable var) val)
5044 (if (not (listp (symbol-value var)))
5045 (set (make-local-variable var) nil))
5046 (set (make-local-variable var) (symbol-value var))
5047 (add-to-list var val))))))
5048 ((equal key "ARCHIVE")
5049 (setq arch value)
5050 (remove-text-properties 0 (length arch)
5051 '(face t fontified t) arch))
5052 ((equal key "OPTIONS")
5053 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5054 (setq scripts (read (match-string 2 value)))))
5055 ((and (equal key "SETUPFILE")
5056 ;; Prevent checking in Gnus messages
5057 (not buffer-read-only))
5058 (setq setup-contents (org-file-contents
5059 (expand-file-name
5060 (org-remove-double-quotes value))
5061 'noerror))
5062 (if (not ext-setup-or-nil)
5063 (setq ext-setup-or-nil setup-contents start 0)
5064 (setq ext-setup-or-nil
5065 (concat (substring ext-setup-or-nil 0 start)
5066 "\n" setup-contents "\n"
5067 (substring ext-setup-or-nil start)))))))
5068 ;; search for property blocks
5069 (goto-char (point-min))
5070 (while (re-search-forward org-block-regexp nil t)
5071 (when (equal "PROPERTY" (upcase (match-string 1)))
5072 (setq value (replace-regexp-in-string
5073 "[\n\r]" " " (match-string 4)))
5074 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5075 (setq props (org-update-property-plist (match-string 1 value)
5076 (match-string 2 value)
5077 props)))))))
5078 (org-set-local 'org-use-sub-superscripts scripts)
5079 (when cat
5080 (org-set-local 'org-category (intern cat))
5081 (push (cons "CATEGORY" cat) props))
5082 (when prio
5083 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5084 (setq prio (mapcar 'string-to-char prio))
5085 (org-set-local 'org-highest-priority (nth 0 prio))
5086 (org-set-local 'org-lowest-priority (nth 1 prio))
5087 (org-set-local 'org-default-priority (nth 2 prio)))
5088 (and props (org-set-local 'org-file-properties (nreverse props)))
5089 (and arch (org-set-local 'org-archive-location arch))
5090 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5091 ;; Process the TODO keywords
5092 (unless kwds
5093 ;; Use the global values as if they had been given locally.
5094 (setq kwds (default-value 'org-todo-keywords))
5095 (if (stringp (car kwds))
5096 (setq kwds (list (cons org-todo-interpretation
5097 (default-value 'org-todo-keywords)))))
5098 (setq kwds (reverse kwds)))
5099 (setq kwds (nreverse kwds))
5100 (let (inter kws kw)
5101 (while (setq kws (pop kwds))
5102 (let ((kws (or
5103 (run-hook-with-args-until-success
5104 'org-todo-setup-filter-hook kws)
5105 kws)))
5106 (setq inter (pop kws) sep (member "|" kws)
5107 kws0 (delete "|" (copy-sequence kws))
5108 kwsa nil
5109 kws1 (mapcar
5110 (lambda (x)
5111 ;; 1 2
5112 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5113 (progn
5114 (setq kw (match-string 1 x)
5115 key (and (match-end 2) (match-string 2 x))
5116 log (org-extract-log-state-settings x))
5117 (push (cons kw (and key (string-to-char key))) kwsa)
5118 (and log (push log org-todo-log-states))
5120 (error "Invalid TODO keyword %s" x)))
5121 kws0)
5122 kwsa (if kwsa (append '((:startgroup))
5123 (nreverse kwsa)
5124 '((:endgroup))))
5125 hw (car kws1)
5126 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5127 tail (list inter hw (car dws) (org-last dws))))
5128 (add-to-list 'org-todo-heads hw 'append)
5129 (push kws1 org-todo-sets)
5130 (setq org-done-keywords (append org-done-keywords dws nil))
5131 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5132 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5133 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5134 (setq org-todo-sets (nreverse org-todo-sets)
5135 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5136 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5137 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5138 ;; Compute the regular expressions and other local variables.
5139 ;; Using `org-outline-regexp-bol' would complicate them much,
5140 ;; because of the fixed white space at the end of that string.
5141 (if (not org-done-keywords)
5142 (setq org-done-keywords (and org-todo-keywords-1
5143 (list (org-last org-todo-keywords-1)))))
5144 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5145 (length org-scheduled-string)
5146 (length org-clock-string)
5147 (length org-closed-string)))
5148 org-not-done-keywords
5149 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5150 org-todo-regexp
5151 (concat "\\("
5152 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5153 "\\)")
5154 org-not-done-regexp
5155 (concat "\\("
5156 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5157 "\\)")
5158 org-not-done-heading-regexp
5159 (format org-heading-keyword-regexp-format org-not-done-regexp)
5160 org-todo-line-regexp
5161 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5162 org-complex-heading-regexp
5163 (concat "^\\(\\*+\\)"
5164 "\\(?: +" org-todo-regexp "\\)?"
5165 "\\(?: +\\(\\[#.\\]\\)\\)?"
5166 "\\(?: +\\(.*?\\)\\)??"
5167 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5168 "[ \t]*$")
5169 org-complex-heading-regexp-format
5170 (concat "^\\(\\*+\\)"
5171 "\\(?: +" org-todo-regexp "\\)?"
5172 "\\(?: +\\(\\[#.\\]\\)\\)?"
5173 "\\(?: +"
5174 ;; Stats cookies can be stuck to body.
5175 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5176 "\\(%s\\)"
5177 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5178 "\\)"
5179 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5180 "[ \t]*$")
5181 org-todo-line-tags-regexp
5182 (concat "^\\(\\*+\\)"
5183 "\\(?: +" org-todo-regexp "\\)?"
5184 "\\(?: +\\(.*?\\)\\)??"
5185 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5186 "[ \t]*$")
5187 org-deadline-regexp (concat "\\<" org-deadline-string)
5188 org-deadline-time-regexp
5189 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5190 org-deadline-time-hour-regexp
5191 (concat "\\<" org-deadline-string
5192 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5193 org-deadline-line-regexp
5194 (concat "\\<\\(" org-deadline-string "\\).*")
5195 org-scheduled-regexp
5196 (concat "\\<" org-scheduled-string)
5197 org-scheduled-time-regexp
5198 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5199 org-scheduled-time-hour-regexp
5200 (concat "\\<" org-scheduled-string
5201 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5202 org-closed-time-regexp
5203 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5204 org-keyword-time-regexp
5205 (concat "\\<\\(" org-scheduled-string
5206 "\\|" org-deadline-string
5207 "\\|" org-closed-string
5208 "\\|" org-clock-string "\\)"
5209 " *[[<]\\([^]>]+\\)[]>]")
5210 org-keyword-time-not-clock-regexp
5211 (concat "\\<\\(" org-scheduled-string
5212 "\\|" org-deadline-string
5213 "\\|" org-closed-string
5214 "\\)"
5215 " *[[<]\\([^]>]+\\)[]>]")
5216 org-maybe-keyword-time-regexp
5217 (concat "\\(\\<\\(" org-scheduled-string
5218 "\\|" org-deadline-string
5219 "\\|" org-closed-string
5220 "\\|" org-clock-string "\\)\\)?"
5221 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5222 org-all-time-keywords
5223 (mapcar (lambda (w) (substring w 0 -1))
5224 (list org-scheduled-string org-deadline-string
5225 org-clock-string org-closed-string)))
5226 (setq org-ota nil)
5227 (org-compute-latex-and-related-regexp))))
5229 (defun org-file-contents (file &optional noerror)
5230 "Return the contents of FILE, as a string."
5231 (if (and file (file-readable-p file))
5232 (with-temp-buffer
5233 (insert-file-contents file)
5234 (buffer-string))
5235 (funcall (if noerror #'message #'error)
5236 "Cannot read file \"%s\"%s"
5237 file
5238 (let ((from (buffer-file-name (buffer-base-buffer))))
5239 (if from (concat " (referenced in file \"" from "\")") "")))))
5241 (defun org-extract-log-state-settings (x)
5242 "Extract the log state setting from a TODO keyword string.
5243 This will extract info from a string like \"WAIT(w@/!)\"."
5244 (let (kw key log1 log2)
5245 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5246 (setq kw (match-string 1 x)
5247 key (and (match-end 2) (match-string 2 x))
5248 log1 (and (match-end 3) (match-string 3 x))
5249 log2 (and (match-end 4) (match-string 4 x)))
5250 (and (or log1 log2)
5251 (list kw
5252 (and log1 (if (equal log1 "!") 'time 'note))
5253 (and log2 (if (equal log2 "!") 'time 'note)))))))
5255 (defun org-remove-keyword-keys (list)
5256 "Remove a pair of parenthesis at the end of each string in LIST."
5257 (mapcar (lambda (x)
5258 (if (string-match "(.*)$" x)
5259 (substring x 0 (match-beginning 0))
5261 list))
5263 (defun org-assign-fast-keys (alist)
5264 "Assign fast keys to a keyword-key alist.
5265 Respect keys that are already there."
5266 (let (new e (alt ?0))
5267 (while (setq e (pop alist))
5268 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5269 (cdr e)) ;; Key already assigned.
5270 (push e new)
5271 (let ((clist (string-to-list (downcase (car e))))
5272 (used (append new alist)))
5273 (when (= (car clist) ?@)
5274 (pop clist))
5275 (while (and clist (rassoc (car clist) used))
5276 (pop clist))
5277 (unless clist
5278 (while (rassoc alt used)
5279 (incf alt)))
5280 (push (cons (car e) (or (car clist) alt)) new))))
5281 (nreverse new)))
5283 ;;; Some variables used in various places
5285 (defvar org-window-configuration nil
5286 "Used in various places to store a window configuration.")
5287 (defvar org-selected-window nil
5288 "Used in various places to store a window configuration.")
5289 (defvar org-finish-function nil
5290 "Function to be called when `C-c C-c' is used.
5291 This is for getting out of special buffers like capture.")
5294 ;; FIXME: Occasionally check by commenting these, to make sure
5295 ;; no other functions uses these, forgetting to let-bind them.
5296 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5297 (defvar org-last-state)
5298 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5300 ;; Defined somewhere in this file, but used before definition.
5301 (defvar org-entities) ;; defined in org-entities.el
5302 (defvar org-struct-menu)
5303 (defvar org-org-menu)
5304 (defvar org-tbl-menu)
5306 ;;;; Define the Org-mode
5308 ;; We use a before-change function to check if a table might need
5309 ;; an update.
5310 (defvar org-table-may-need-update t
5311 "Indicates that a table might need an update.
5312 This variable is set by `org-before-change-function'.
5313 `org-table-align' sets it back to nil.")
5314 (defun org-before-change-function (beg end)
5315 "Every change indicates that a table might need an update."
5316 (setq org-table-may-need-update t))
5317 (defvar org-mode-map)
5318 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5319 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5320 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5321 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5322 (defvar org-table-buffer-is-an nil)
5324 (defvar bidi-paragraph-direction)
5325 (defvar buffer-face-mode-face)
5327 (require 'outline)
5328 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5329 (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"))
5330 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5332 ;; Other stuff we need.
5333 (require 'time-date)
5334 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5335 (require 'easymenu)
5336 (require 'overlay)
5338 ;; (require 'org-macs) moved higher up in the file before it is first used
5339 (require 'org-entities)
5340 ;; (require 'org-compat) moved higher up in the file before it is first used
5341 (require 'org-faces)
5342 (require 'org-list)
5343 (require 'org-pcomplete)
5344 (require 'org-src)
5345 (require 'org-footnote)
5346 (require 'org-macro)
5348 ;; babel
5349 (require 'ob)
5351 ;;;###autoload
5352 (define-derived-mode org-mode outline-mode "Org"
5353 "Outline-based notes management and organizer, alias
5354 \"Carsten's outline-mode for keeping track of everything.\"
5356 Org-mode develops organizational tasks around a NOTES file which
5357 contains information about projects as plain text. Org-mode is
5358 implemented on top of outline-mode, which is ideal to keep the content
5359 of large files well structured. It supports ToDo items, deadlines and
5360 time stamps, which magically appear in the diary listing of the Emacs
5361 calendar. Tables are easily created with a built-in table editor.
5362 Plain text URL-like links connect to websites, emails (VM), Usenet
5363 messages (Gnus), BBDB entries, and any files related to the project.
5364 For printing and sharing of notes, an Org-mode file (or a part of it)
5365 can be exported as a structured ASCII or HTML file.
5367 The following commands are available:
5369 \\{org-mode-map}"
5371 ;; Get rid of Outline menus, they are not needed
5372 ;; Need to do this here because define-derived-mode sets up
5373 ;; the keymap so late. Still, it is a waste to call this each time
5374 ;; we switch another buffer into org-mode.
5375 (if (featurep 'xemacs)
5376 (when (boundp 'outline-mode-menu-heading)
5377 ;; Assume this is Greg's port, it uses easymenu
5378 (easy-menu-remove outline-mode-menu-heading)
5379 (easy-menu-remove outline-mode-menu-show)
5380 (easy-menu-remove outline-mode-menu-hide))
5381 (define-key org-mode-map [menu-bar headings] 'undefined)
5382 (define-key org-mode-map [menu-bar hide] 'undefined)
5383 (define-key org-mode-map [menu-bar show] 'undefined))
5385 (org-load-modules-maybe)
5386 (easy-menu-add org-org-menu)
5387 (easy-menu-add org-tbl-menu)
5388 (org-install-agenda-files-menu)
5389 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5390 (add-to-invisibility-spec '(org-cwidth))
5391 (add-to-invisibility-spec '(org-hide-block . t))
5392 (when (featurep 'xemacs)
5393 (org-set-local 'line-move-ignore-invisible t))
5394 (org-set-local 'outline-regexp org-outline-regexp)
5395 (org-set-local 'outline-level 'org-outline-level)
5396 (setq bidi-paragraph-direction 'left-to-right)
5397 (when (and org-ellipsis
5398 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5399 (fboundp 'make-glyph-code))
5400 (unless org-display-table
5401 (setq org-display-table (make-display-table)))
5402 (set-display-table-slot
5403 org-display-table 4
5404 (vconcat (mapcar
5405 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5406 org-ellipsis)))
5407 (if (stringp org-ellipsis) org-ellipsis "..."))))
5408 (setq buffer-display-table org-display-table))
5409 (org-set-regexps-and-options-for-tags)
5410 (org-set-regexps-and-options)
5411 (org-set-font-lock-defaults)
5412 (when (and org-tag-faces (not org-tags-special-faces-re))
5413 ;; tag faces set outside customize.... force initialization.
5414 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5415 ;; Calc embedded
5416 (org-set-local 'calc-embedded-open-mode "# ")
5417 ;; Modify a few syntax entries
5418 (modify-syntax-entry ?@ "w")
5419 (modify-syntax-entry ?\" "\"")
5420 (if org-startup-truncated (setq truncate-lines t))
5421 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5422 (org-set-local 'font-lock-unfontify-region-function
5423 'org-unfontify-region)
5424 ;; Activate before-change-function
5425 (org-set-local 'org-table-may-need-update t)
5426 (org-add-hook 'before-change-functions 'org-before-change-function nil
5427 'local)
5428 ;; Check for running clock before killing a buffer
5429 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5430 ;; Initialize macros templates.
5431 (org-macro-initialize-templates)
5432 ;; Initialize radio targets.
5433 (org-update-radio-target-regexp)
5434 ;; Indentation.
5435 (org-set-local 'indent-line-function 'org-indent-line)
5436 (org-set-local 'indent-region-function 'org-indent-region)
5437 ;; Filling and auto-filling.
5438 (org-setup-filling)
5439 ;; Comments.
5440 (org-setup-comments-handling)
5441 ;; Initialize cache.
5442 (org-element-cache-reset)
5443 ;; Beginning/end of defun
5444 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5445 (org-set-local 'end-of-defun-function 'org-forward-element)
5446 ;; Next error for sparse trees
5447 (org-set-local 'next-error-function 'org-occur-next-match)
5448 ;; Make sure dependence stuff works reliably, even for users who set it
5449 ;; too late :-(
5450 (if org-enforce-todo-dependencies
5451 (add-hook 'org-blocker-hook
5452 'org-block-todo-from-children-or-siblings-or-parent)
5453 (remove-hook 'org-blocker-hook
5454 'org-block-todo-from-children-or-siblings-or-parent))
5455 (if org-enforce-todo-checkbox-dependencies
5456 (add-hook 'org-blocker-hook
5457 'org-block-todo-from-checkboxes)
5458 (remove-hook 'org-blocker-hook
5459 'org-block-todo-from-checkboxes))
5461 ;; Align options lines
5462 (org-set-local
5463 'align-mode-rules-list
5464 '((org-in-buffer-settings
5465 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5466 (modes . '(org-mode)))))
5468 ;; Imenu
5469 (org-set-local 'imenu-create-index-function
5470 'org-imenu-get-tree)
5472 ;; Make isearch reveal context
5473 (if (or (featurep 'xemacs)
5474 (not (boundp 'outline-isearch-open-invisible-function)))
5475 ;; Emacs 21 and XEmacs make use of the hook
5476 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5477 ;; Emacs 22 deals with this through a special variable
5478 (org-set-local 'outline-isearch-open-invisible-function
5479 (lambda (&rest ignore) (org-show-context 'isearch)))
5480 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5482 ;; Setup the pcomplete hooks
5483 (set (make-local-variable 'pcomplete-command-completion-function)
5484 'org-pcomplete-initial)
5485 (set (make-local-variable 'pcomplete-command-name-function)
5486 'org-command-at-point)
5487 (set (make-local-variable 'pcomplete-default-completion-function)
5488 'ignore)
5489 (set (make-local-variable 'pcomplete-parse-arguments-function)
5490 'org-parse-arguments)
5491 (set (make-local-variable 'pcomplete-termination-string) "")
5492 (when (>= emacs-major-version 23)
5493 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5495 ;; If empty file that did not turn on org-mode automatically, make it to.
5496 (if (and org-insert-mode-line-in-empty-file
5497 (org-called-interactively-p 'any)
5498 (= (point-min) (point-max)))
5499 (insert "# -*- mode: org -*-\n\n"))
5500 (unless org-inhibit-startup
5501 (org-unmodified
5502 (and org-startup-with-beamer-mode (org-beamer-mode))
5503 (when org-startup-align-all-tables
5504 (org-table-map-tables 'org-table-align 'quietly))
5505 (when org-startup-with-inline-images
5506 (org-display-inline-images))
5507 (when org-startup-with-latex-preview
5508 (org-preview-latex-fragment))
5509 (unless org-inhibit-startup-visibility-stuff
5510 (org-set-startup-visibility))))
5511 ;; Try to set org-hide correctly
5512 (let ((foreground (org-find-invisible-foreground)))
5513 (if foreground
5514 (set-face-foreground 'org-hide foreground))))
5516 ;; Update `customize-package-emacs-version-alist'
5517 (add-to-list 'customize-package-emacs-version-alist
5518 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5519 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5520 ("8.2.6" . "24.4")))
5522 (defvar org-mode-transpose-word-syntax-table
5523 (let ((st (make-syntax-table)))
5524 (mapc (lambda(c) (modify-syntax-entry
5525 (string-to-char (car c)) "w p" st))
5526 org-emphasis-alist)
5527 st))
5529 (when (fboundp 'abbrev-table-put)
5530 (abbrev-table-put org-mode-abbrev-table
5531 :parents (list text-mode-abbrev-table)))
5533 (defsubst org-fix-ellipsis-at-bol ()
5534 (save-excursion (goto-char (window-start)) (recenter 0)))
5536 (defun org-find-invisible-foreground ()
5537 (let ((candidates (remove
5538 "unspecified-bg"
5539 (nconc
5540 (list (face-background 'default)
5541 (face-background 'org-default))
5542 (mapcar
5543 (lambda (alist)
5544 (when (boundp alist)
5545 (cdr (assoc 'background-color (symbol-value alist)))))
5546 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5547 (list (face-foreground 'org-hide))))))
5548 (car (remove nil candidates))))
5550 (defun org-current-time (&optional rounding-minutes past)
5551 "Current time, possibly rounded to ROUNDING-MINUTES.
5552 When ROUNDING-MINUTES is not an integer, fall back on the car of
5553 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5554 the rounding returns a past time."
5555 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5556 (car org-time-stamp-rounding-minutes)))
5557 (time (decode-time)) res)
5558 (if (< r 1)
5559 (current-time)
5560 (setq res
5561 (apply 'encode-time
5562 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5563 (nthcdr 2 time))))
5564 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5565 (seconds-to-time (- (org-float-time res) (* r 60)))
5566 res))))
5568 (defun org-today ()
5569 "Return today date, considering `org-extend-today-until'."
5570 (time-to-days
5571 (time-subtract (current-time)
5572 (list 0 (* 3600 org-extend-today-until) 0))))
5574 ;;;; Font-Lock stuff, including the activators
5576 (defvar org-mouse-map (make-sparse-keymap))
5577 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5578 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5579 (when org-mouse-1-follows-link
5580 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5581 (when org-tab-follows-link
5582 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5583 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5585 (require 'font-lock)
5587 (defconst org-non-link-chars "]\t\n\r<>")
5588 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5589 "file+sys" "news" "shell" "elisp" "doi" "message"
5590 "help"))
5591 (defvar org-link-types-re nil
5592 "Matches a link that has a url-like prefix like \"http:\"")
5593 (defvar org-link-re-with-space nil
5594 "Matches a link with spaces, optional angular brackets around it.")
5595 (defvar org-link-re-with-space2 nil
5596 "Matches a link with spaces, optional angular brackets around it.")
5597 (defvar org-link-re-with-space3 nil
5598 "Matches a link with spaces, only for internal part in bracket links.")
5599 (defvar org-angle-link-re nil
5600 "Matches link with angular brackets, spaces are allowed.")
5601 (defvar org-plain-link-re nil
5602 "Matches plain link, without spaces.")
5603 (defvar org-bracket-link-regexp nil
5604 "Matches a link in double brackets.")
5605 (defvar org-bracket-link-analytic-regexp nil
5606 "Regular expression used to analyze links.
5607 Here is what the match groups contain after a match:
5608 1: http:
5609 2: http
5610 3: path
5611 4: [desc]
5612 5: desc")
5613 (defvar org-bracket-link-analytic-regexp++ nil
5614 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5615 (defvar org-any-link-re nil
5616 "Regular expression matching any link.")
5618 (defconst org-match-sexp-depth 3
5619 "Number of stacked braces for sub/superscript matching.")
5621 (defun org-create-multibrace-regexp (left right n)
5622 "Create a regular expression which will match a balanced sexp.
5623 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5624 as single character strings.
5625 The regexp returned will match the entire expression including the
5626 delimiters. It will also define a single group which contains the
5627 match except for the outermost delimiters. The maximum depth of
5628 stacked delimiters is N. Escaping delimiters is not possible."
5629 (let* ((nothing (concat "[^" left right "]*?"))
5630 (or "\\|")
5631 (re nothing)
5632 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5633 (while (> n 1)
5634 (setq n (1- n)
5635 re (concat re or next)
5636 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5637 (concat left "\\(" re "\\)" right)))
5639 (defconst org-match-substring-regexp
5640 (concat
5641 "\\(\\S-\\)\\([_^]\\)\\("
5642 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5643 "\\|"
5644 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5645 "\\|"
5646 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5647 "The regular expression matching a sub- or superscript.")
5649 (defconst org-match-substring-with-braces-regexp
5650 (concat
5651 "\\(\\S-\\)\\([_^]\\)"
5652 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5653 "The regular expression matching a sub- or superscript, forcing braces.")
5655 (defun org-make-link-regexps ()
5656 "Update the link regular expressions.
5657 This should be called after the variable `org-link-types' has changed."
5658 (setq org-link-types-re
5659 (concat
5660 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5661 org-link-re-with-space
5662 (concat
5663 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5664 "\\([^" org-non-link-chars " ]"
5665 "[^" org-non-link-chars "]*"
5666 "[^" org-non-link-chars " ]\\)>?")
5667 org-link-re-with-space2
5668 (concat
5669 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5670 "\\([^" org-non-link-chars " ]"
5671 "[^\t\n\r]*"
5672 "[^" org-non-link-chars " ]\\)>?")
5673 org-link-re-with-space3
5674 (concat
5675 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5676 "\\([^" org-non-link-chars " ]"
5677 "[^\t\n\r]*\\)")
5678 org-angle-link-re
5679 (concat
5680 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5681 "\\([^" org-non-link-chars " ]"
5682 "[^" org-non-link-chars "]*"
5683 "\\)>")
5684 org-plain-link-re
5685 (concat
5686 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5687 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5688 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5689 org-bracket-link-regexp
5690 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5691 org-bracket-link-analytic-regexp
5692 (concat
5693 "\\[\\["
5694 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5695 "\\([^]]+\\)"
5696 "\\]"
5697 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5698 "\\]")
5699 org-bracket-link-analytic-regexp++
5700 (concat
5701 "\\[\\["
5702 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5703 "\\([^]]+\\)"
5704 "\\]"
5705 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5706 "\\]")
5707 org-any-link-re
5708 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5709 org-angle-link-re "\\)\\|\\("
5710 org-plain-link-re "\\)")))
5712 (org-make-link-regexps)
5714 (defvar org-emph-face nil)
5716 (defun org-do-emphasis-faces (limit)
5717 "Run through the buffer and add overlays to emphasized strings."
5718 (let (rtn a)
5719 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5720 (let* ((border (char-after (match-beginning 3)))
5721 (bre (regexp-quote (char-to-string border))))
5722 (if (and (not (= border (char-after (match-beginning 4))))
5723 (not (save-match-data
5724 (string-match (concat bre ".*" bre)
5725 (replace-regexp-in-string
5726 "\n" " "
5727 (substring (match-string 2) 1 -1))))))
5728 (progn
5729 (setq rtn t)
5730 (setq a (assoc (match-string 3) org-emphasis-alist))
5731 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5732 'face
5733 (nth 1 a))
5734 (and (nth 2 a)
5735 (org-remove-flyspell-overlays-in
5736 (match-beginning 0) (match-end 0)))
5737 (add-text-properties (match-beginning 2) (match-end 2)
5738 '(font-lock-multiline t org-emphasis t))
5739 (when org-hide-emphasis-markers
5740 (add-text-properties (match-end 4) (match-beginning 5)
5741 '(invisible org-link))
5742 (add-text-properties (match-beginning 3) (match-end 3)
5743 '(invisible org-link))))))
5744 (goto-char (1+ (match-beginning 0))))
5745 rtn))
5747 (defun org-emphasize (&optional char)
5748 "Insert or change an emphasis, i.e. a font like bold or italic.
5749 If there is an active region, change that region to a new emphasis.
5750 If there is no region, just insert the marker characters and position
5751 the cursor between them.
5752 CHAR should be the marker character. If it is a space, it means to
5753 remove the emphasis of the selected region.
5754 If CHAR is not given (for example in an interactive call) it will be
5755 prompted for."
5756 (interactive)
5757 (let ((erc org-emphasis-regexp-components)
5758 (prompt "")
5759 (string "") beg end move c s)
5760 (if (org-region-active-p)
5761 (setq beg (region-beginning) end (region-end)
5762 string (buffer-substring beg end))
5763 (setq move t))
5765 (unless char
5766 (message "Emphasis marker or tag: [%s]"
5767 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5768 (setq char (read-char-exclusive)))
5769 (if (equal char ?\ )
5770 (setq s "" move nil)
5771 (unless (assoc (char-to-string char) org-emphasis-alist)
5772 (user-error "No such emphasis marker: \"%c\"" char))
5773 (setq s (char-to-string char)))
5774 (while (and (> (length string) 1)
5775 (equal (substring string 0 1) (substring string -1))
5776 (assoc (substring string 0 1) org-emphasis-alist))
5777 (setq string (substring string 1 -1)))
5778 (setq string (concat s string s))
5779 (if beg (delete-region beg end))
5780 (unless (or (bolp)
5781 (string-match (concat "[" (nth 0 erc) "\n]")
5782 (char-to-string (char-before (point)))))
5783 (insert " "))
5784 (unless (or (eobp)
5785 (string-match (concat "[" (nth 1 erc) "\n]")
5786 (char-to-string (char-after (point)))))
5787 (insert " ") (backward-char 1))
5788 (insert string)
5789 (and move (backward-char 1))))
5791 (defconst org-nonsticky-props
5792 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5794 (defsubst org-rear-nonsticky-at (pos)
5795 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5797 (defun org-activate-plain-links (limit)
5798 "Run through the buffer and add overlays to links."
5799 (let (f hl)
5800 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5801 (not (org-in-src-block-p)))
5802 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5803 (setq f (get-text-property (match-beginning 0) 'face))
5804 (setq hl (org-match-string-no-properties 0))
5805 (if (or (eq f 'org-tag)
5806 (and (listp f) (memq 'org-tag f)))
5808 (add-text-properties (match-beginning 0) (match-end 0)
5809 (list 'mouse-face 'highlight
5810 'face 'org-link
5811 'htmlize-link `(:uri ,hl)
5812 'keymap org-mouse-map))
5813 (org-rear-nonsticky-at (match-end 0)))
5814 t)))
5816 (defun org-activate-code (limit)
5817 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5818 (progn
5819 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5820 (remove-text-properties (match-beginning 0) (match-end 0)
5821 '(display t invisible t intangible t))
5822 t)))
5824 (defcustom org-src-fontify-natively t
5825 "When non-nil, fontify code in code blocks."
5826 :type 'boolean
5827 :version "24.4"
5828 :package-version '(Org . "8.3")
5829 :group 'org-appearance
5830 :group 'org-babel)
5832 (defcustom org-allow-promoting-top-level-subtree nil
5833 "When non-nil, allow promoting a top level subtree.
5834 The leading star of the top level headline will be replaced
5835 by a #."
5836 :type 'boolean
5837 :version "24.1"
5838 :group 'org-appearance)
5840 (defun org-fontify-meta-lines-and-blocks (limit)
5841 (condition-case nil
5842 (org-fontify-meta-lines-and-blocks-1 limit)
5843 (error (message "org-mode fontification error"))))
5845 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5846 "Fontify #+ lines and blocks."
5847 (let ((case-fold-search t))
5848 (if (re-search-forward
5849 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5850 limit t)
5851 (let ((beg (match-beginning 0))
5852 (block-start (match-end 0))
5853 (block-end nil)
5854 (lang (match-string 7))
5855 (beg1 (line-beginning-position 2))
5856 (dc1 (downcase (match-string 2)))
5857 (dc3 (downcase (match-string 3)))
5858 end end1 quoting block-type ovl)
5859 (cond
5860 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5861 ;; a single line of backend-specific content
5862 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5863 (remove-text-properties (match-beginning 0) (match-end 0)
5864 '(display t invisible t intangible t))
5865 (add-text-properties (match-beginning 1) (match-end 3)
5866 '(font-lock-fontified t face org-meta-line))
5867 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5868 '(font-lock-fontified t face org-block))
5869 ; for backend-specific code
5871 ((and (match-end 4) (equal dc3 "+begin"))
5872 ;; Truly a block
5873 (setq block-type (downcase (match-string 5))
5874 quoting (member block-type org-protecting-blocks))
5875 (when (re-search-forward
5876 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5877 nil t) ;; on purpose, we look further than LIMIT
5878 (setq end (min (point-max) (match-end 0))
5879 end1 (min (point-max) (1- (match-beginning 0))))
5880 (setq block-end (match-beginning 0))
5881 (when quoting
5882 (org-remove-flyspell-overlays-in beg1 end1)
5883 (remove-text-properties beg end
5884 '(display t invisible t intangible t)))
5885 (add-text-properties
5886 beg end '(font-lock-fontified t font-lock-multiline t))
5887 (add-text-properties beg beg1 '(face org-meta-line))
5888 (org-remove-flyspell-overlays-in beg beg1)
5889 (add-text-properties ; For end_src
5890 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5891 (org-remove-flyspell-overlays-in end1 end)
5892 (cond
5893 ((and lang (not (string= lang "")) org-src-fontify-natively)
5894 (org-src-font-lock-fontify-block lang block-start block-end)
5895 ;; remove old background overlays
5896 (mapc (lambda (ov)
5897 (if (eq (overlay-get ov 'face) 'org-block-background)
5898 (delete-overlay ov)))
5899 (overlays-at (/ (+ beg1 block-end) 2)))
5900 ;; add a background overlay
5901 (setq ovl (make-overlay beg1 block-end))
5902 (overlay-put ovl 'face 'org-block-background)
5903 (overlay-put ovl 'evaporate t)) ; make it go away when empty
5904 (quoting
5905 (add-text-properties beg1 (min (point-max) (1+ end1))
5906 '(face org-block))) ; end of source block
5907 ((not org-fontify-quote-and-verse-blocks))
5908 ((string= block-type "quote")
5909 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5910 ((string= block-type "verse")
5911 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5912 (add-text-properties beg beg1 '(face org-block-begin-line))
5913 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5914 '(face org-block-end-line))
5916 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5917 (org-remove-flyspell-overlays-in
5918 (match-beginning 0)
5919 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5920 (add-text-properties
5921 beg (match-end 3)
5922 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5923 '(font-lock-fontified t invisible t)
5924 '(font-lock-fontified t face org-document-info-keyword)))
5925 (add-text-properties
5926 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5927 (if (string-equal dc1 "+title:")
5928 '(font-lock-fontified t face org-document-title)
5929 '(font-lock-fontified t face org-document-info))))
5930 ((or (equal dc1 "+results")
5931 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5932 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5933 "+call:" "+header:" "+headers:" "+name:"))
5934 (and (match-end 4) (equal dc3 "+attr")))
5935 (org-remove-flyspell-overlays-in
5936 (match-beginning 0)
5937 (if (equal "+caption:" dc1) (match-end 2) (match-end 0)))
5938 (add-text-properties
5939 beg (match-end 0)
5940 '(font-lock-fontified t face org-meta-line))
5942 ((member dc3 '(" " ""))
5943 (org-remove-flyspell-overlays-in beg (match-end 0))
5944 (add-text-properties
5945 beg (match-end 0)
5946 '(font-lock-fontified t face font-lock-comment-face)))
5947 (t ;; just any other in-buffer setting, but not indented
5948 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5949 (add-text-properties
5950 beg (match-end 0)
5951 '(font-lock-fontified t face org-meta-line))
5952 t))))))
5954 (defun org-fontify-drawers (limit)
5955 "Fontify drawers."
5956 (when (re-search-forward org-drawer-regexp limit t)
5957 (add-text-properties
5958 (match-beginning 0) (match-end 0)
5959 '(font-lock-fontified t face org-special-keyword))
5960 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5963 (defun org-fontify-macros (limit)
5964 "Fontify macros."
5965 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5966 (add-text-properties
5967 (match-beginning 0) (match-end 0)
5968 '(font-lock-fontified t face org-macro))
5969 (when org-hide-macro-markers
5970 (add-text-properties (match-end 2) (match-beginning 2)
5971 '(invisible t))
5972 (add-text-properties (match-beginning 1) (match-end 1)
5973 '(invisible t)))
5974 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5977 (defun org-activate-angle-links (limit)
5978 "Run through the buffer and add overlays to links."
5979 (if (and (re-search-forward org-angle-link-re limit t)
5980 (not (org-in-src-block-p)))
5981 (progn
5982 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5983 (add-text-properties (match-beginning 0) (match-end 0)
5984 (list 'mouse-face 'highlight
5985 'keymap org-mouse-map))
5986 (org-rear-nonsticky-at (match-end 0))
5987 t)))
5989 (defun org-activate-footnote-links (limit)
5990 "Run through the buffer and add overlays to footnotes."
5991 (let ((fn (org-footnote-next-reference-or-definition limit)))
5992 (when fn
5993 (let* ((beg (nth 1 fn))
5994 (end (nth 2 fn))
5995 (label (car fn))
5996 (referencep (/= (line-beginning-position) beg)))
5997 (when (and referencep (nth 3 fn))
5998 (save-excursion
5999 (goto-char beg)
6000 (search-forward (or label "fn:"))
6001 (org-remove-flyspell-overlays-in beg (match-end 0))))
6002 (add-text-properties beg end
6003 (list 'mouse-face 'highlight
6004 'keymap org-mouse-map
6005 'help-echo
6006 (if referencep "Footnote reference"
6007 "Footnote definition")
6008 'font-lock-fontified t
6009 'font-lock-multiline t
6010 'face 'org-footnote))))))
6012 (defun org-activate-bracket-links (limit)
6013 "Run through the buffer and add overlays to bracketed links."
6014 (if (and (re-search-forward org-bracket-link-regexp limit t)
6015 (not (org-in-src-block-p)))
6016 (let* ((hl (org-match-string-no-properties 1))
6017 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6018 (ip (org-maybe-intangible
6019 (list 'invisible 'org-link
6020 'keymap org-mouse-map 'mouse-face 'highlight
6021 'font-lock-multiline t 'help-echo help
6022 'htmlize-link `(:uri ,hl))))
6023 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6024 'font-lock-multiline t 'help-echo help
6025 'htmlize-link `(:uri ,hl))))
6026 ;; We need to remove the invisible property here. Table narrowing
6027 ;; may have made some of this invisible.
6028 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6029 (remove-text-properties (match-beginning 0) (match-end 0)
6030 '(invisible nil))
6031 (if (match-end 3)
6032 (progn
6033 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6034 (org-rear-nonsticky-at (match-beginning 3))
6035 (add-text-properties (match-beginning 3) (match-end 3) vp)
6036 (org-rear-nonsticky-at (match-end 3))
6037 (add-text-properties (match-end 3) (match-end 0) ip)
6038 (org-rear-nonsticky-at (match-end 0)))
6039 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6040 (org-rear-nonsticky-at (match-beginning 1))
6041 (add-text-properties (match-beginning 1) (match-end 1) vp)
6042 (org-rear-nonsticky-at (match-end 1))
6043 (add-text-properties (match-end 1) (match-end 0) ip)
6044 (org-rear-nonsticky-at (match-end 0)))
6045 t)))
6047 (defun org-activate-dates (limit)
6048 "Run through the buffer and add overlays to dates."
6049 (if (and (re-search-forward org-tsr-regexp-both limit t)
6050 (not (equal (char-before (match-beginning 0)) 91)))
6051 (progn
6052 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6053 (add-text-properties (match-beginning 0) (match-end 0)
6054 (list 'mouse-face 'highlight
6055 'keymap org-mouse-map))
6056 (org-rear-nonsticky-at (match-end 0))
6057 (when org-display-custom-times
6058 (if (match-end 3)
6059 (org-display-custom-time (match-beginning 3) (match-end 3)))
6060 (org-display-custom-time (match-beginning 1) (match-end 1)))
6061 t)))
6063 (defvar org-target-link-regexp nil
6064 "Regular expression matching radio targets in plain text.")
6065 (make-variable-buffer-local 'org-target-link-regexp)
6066 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
6067 "Regular expression matching a link target.")
6068 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
6069 "Regular expression matching a radio target.")
6070 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
6071 "Regular expression matching any target.")
6073 (defun org-activate-target-links (limit)
6074 "Run through the buffer and add overlays to target matches."
6075 (when org-target-link-regexp
6076 (let ((case-fold-search t))
6077 (if (re-search-forward org-target-link-regexp limit t)
6078 (progn
6079 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6080 (add-text-properties (match-beginning 0) (match-end 0)
6081 (list 'mouse-face 'highlight
6082 'keymap org-mouse-map
6083 'help-echo "Radio target link"
6084 'org-linked-text t))
6085 (org-rear-nonsticky-at (match-end 0))
6086 t)))))
6088 (defun org-update-radio-target-regexp ()
6089 "Find all radio targets in this file and update the regular expression."
6090 (interactive)
6091 (when (memq 'radio org-activate-links)
6092 (setq org-target-link-regexp
6093 (org-make-target-link-regexp (org-all-targets 'radio)))
6094 (org-restart-font-lock)))
6096 (defun org-hide-wide-columns (limit)
6097 (let (s e)
6098 (setq s (text-property-any (point) (or limit (point-max))
6099 'org-cwidth t))
6100 (when s
6101 (setq e (next-single-property-change s 'org-cwidth))
6102 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6103 (goto-char e)
6104 t)))
6106 (defvar org-latex-and-related-regexp nil
6107 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6109 (defun org-compute-latex-and-related-regexp ()
6110 "Compute regular expression for LaTeX, entities and sub/superscript.
6111 Result depends on variable `org-highlight-latex-and-related'."
6112 (org-set-local
6113 'org-latex-and-related-regexp
6114 (let* ((re-sub
6115 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6116 ((eq org-use-sub-superscripts '{})
6117 (list org-match-substring-with-braces-regexp))
6118 (org-use-sub-superscripts (list org-match-substring-regexp))))
6119 (re-latex
6120 (when (memq 'latex org-highlight-latex-and-related)
6121 (let ((matchers (plist-get org-format-latex-options :matchers)))
6122 (delq nil
6123 (mapcar (lambda (x)
6124 (and (member (car x) matchers) (nth 1 x)))
6125 org-latex-regexps)))))
6126 (re-entities
6127 (when (memq 'entities org-highlight-latex-and-related)
6128 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6129 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6131 (defun org-do-latex-and-related (limit)
6132 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6133 LIMIT bounds the search for syntax to highlight. Stop at first
6134 highlighted object, if any. Return t if some highlighting was
6135 done, nil otherwise."
6136 (when (org-string-nw-p org-latex-and-related-regexp)
6137 (catch 'found
6138 (while (re-search-forward org-latex-and-related-regexp limit t)
6139 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6140 'face))
6141 '(org-code org-verbatim underline))
6142 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6143 '(?_ ?^))
6145 0)))
6146 (font-lock-prepend-text-property
6147 (+ offset (match-beginning 0)) (match-end 0)
6148 'face 'org-latex-and-related)
6149 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6150 '(font-lock-multiline t)))
6151 (throw 'found t)))
6152 nil)))
6154 (defun org-restart-font-lock ()
6155 "Restart `font-lock-mode', to force refontification."
6156 (when (and (boundp 'font-lock-mode) font-lock-mode)
6157 (font-lock-mode -1)
6158 (font-lock-mode 1)))
6160 (defun org-all-targets (&optional radio)
6161 "Return a list of all targets in this file.
6162 When optional argument RADIO is non-nil, only find radio
6163 targets."
6164 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6165 (save-excursion
6166 (goto-char (point-min))
6167 (while (re-search-forward re nil t)
6168 ;; Make sure point is really within the object.
6169 (backward-char)
6170 (let ((obj (org-element-context)))
6171 (when (memq (org-element-type obj) '(radio-target target))
6172 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6173 rtn)))
6175 (defun org-make-target-link-regexp (targets)
6176 "Make regular expression matching all strings in TARGETS.
6177 The regular expression finds the targets also if there is a line break
6178 between words."
6179 (and targets
6180 (concat
6181 "\\<\\("
6182 (mapconcat
6183 (lambda (x)
6184 (setq x (regexp-quote x))
6185 (while (string-match " +" x)
6186 (setq x (replace-match "\\s-+" t t x)))
6188 targets
6189 "\\|")
6190 "\\)\\>")))
6192 (defun org-activate-tags (limit)
6193 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6194 (progn
6195 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6196 (add-text-properties (match-beginning 1) (match-end 1)
6197 (list 'mouse-face 'highlight
6198 'keymap org-mouse-map))
6199 (org-rear-nonsticky-at (match-end 1))
6200 t)))
6202 (defun org-outline-level ()
6203 "Compute the outline level of the heading at point.
6204 If this is called at a normal headline, the level is the number of stars.
6205 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6206 (save-excursion
6207 (if (not (condition-case nil
6208 (org-back-to-heading t)
6209 (error nil)))
6211 (looking-at org-outline-regexp)
6212 (1- (- (match-end 0) (match-beginning 0))))))
6214 (defvar org-font-lock-keywords nil)
6216 (defsubst org-re-property (property &optional literal)
6217 "Return a regexp matching a PROPERTY line.
6218 Match group 3 will be set to the value if it exists."
6219 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6220 (if literal property (regexp-quote property))
6221 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6223 (defconst org-property-re
6224 (org-re-property ".*?" 'literal)
6225 "Regular expression matching a property line.
6226 There are four matching groups:
6227 1: :PROPKEY: including the leading and trailing colon,
6228 2: PROPKEY without the leading and trailing colon,
6229 3: PROPVAL without leading or trailing spaces,
6230 4: the indentation of the current line,
6231 5: trailing whitespace.")
6233 (defvar org-font-lock-hook nil
6234 "Functions to be called for special font lock stuff.")
6236 (defvar org-font-lock-set-keywords-hook nil
6237 "Functions that can manipulate `org-font-lock-extra-keywords'.
6238 This is called after `org-font-lock-extra-keywords' is defined, but before
6239 it is installed to be used by font lock. This can be useful if something
6240 needs to be inserted at a specific position in the font-lock sequence.")
6242 (defun org-font-lock-hook (limit)
6243 "Run `org-font-lock-hook' within LIMIT."
6244 (run-hook-with-args 'org-font-lock-hook limit))
6246 (defun org-set-font-lock-defaults ()
6247 "Set font lock defaults for the current buffer."
6248 (let* ((em org-fontify-emphasized-text)
6249 (lk org-activate-links)
6250 (org-font-lock-extra-keywords
6251 (list
6252 ;; Call the hook
6253 '(org-font-lock-hook)
6254 ;; Headlines
6255 `(,(if org-fontify-whole-heading-line
6256 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6257 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6258 (1 (org-get-level-face 1))
6259 (2 (org-get-level-face 2))
6260 (3 (org-get-level-face 3)))
6261 ;; Table lines
6262 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6263 (1 'org-table t))
6264 ;; Table internals
6265 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6266 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6267 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6268 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6269 ;; Drawers
6270 '(org-fontify-drawers)
6271 ;; Properties
6272 (list org-property-re
6273 '(1 'org-special-keyword t)
6274 '(3 'org-property-value t))
6275 ;; Links
6276 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6277 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6278 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6279 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6280 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6281 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6282 (if (memq 'footnote lk) '(org-activate-footnote-links))
6283 ;; Targets.
6284 (list org-any-target-regexp '(0 'org-target t))
6285 ;; Diary sexps.
6286 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6287 ;; Macro
6288 '(org-fontify-macros)
6289 '(org-hide-wide-columns (0 nil append))
6290 ;; TODO keyword
6291 (list (format org-heading-keyword-regexp-format
6292 org-todo-regexp)
6293 '(2 (org-get-todo-face 2) t))
6294 ;; DONE
6295 (if org-fontify-done-headline
6296 (list (format org-heading-keyword-regexp-format
6297 (concat
6298 "\\(?:"
6299 (mapconcat 'regexp-quote org-done-keywords "\\|")
6300 "\\)"))
6301 '(2 'org-headline-done t))
6302 nil)
6303 ;; Priorities
6304 '(org-font-lock-add-priority-faces)
6305 ;; Tags
6306 '(org-font-lock-add-tag-faces)
6307 ;; Tags groups
6308 (if (and org-group-tags org-tag-groups-alist)
6309 (list (concat org-outline-regexp-bol ".+\\(:"
6310 (regexp-opt (mapcar 'car org-tag-groups-alist))
6311 ":\\).*$")
6312 '(1 'org-tag-group prepend)))
6313 ;; Special keywords
6314 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6315 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6316 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6317 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6318 ;; Emphasis
6319 (if em
6320 (if (featurep 'xemacs)
6321 '(org-do-emphasis-faces (0 nil append))
6322 '(org-do-emphasis-faces)))
6323 ;; Checkboxes
6324 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6325 1 'org-checkbox prepend)
6326 (if (cdr (assq 'checkbox org-list-automatic-rules))
6327 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6328 (0 (org-get-checkbox-statistics-face) t)))
6329 ;; Description list items
6330 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6331 1 'org-list-dt prepend)
6332 ;; ARCHIVEd headings
6333 (list (concat
6334 org-outline-regexp-bol
6335 "\\(.*:" org-archive-tag ":.*\\)")
6336 '(1 'org-archived prepend))
6337 ;; Specials
6338 '(org-do-latex-and-related)
6339 '(org-fontify-entities)
6340 '(org-raise-scripts)
6341 ;; Code
6342 '(org-activate-code (1 'org-code t))
6343 ;; COMMENT
6344 (list (format org-heading-keyword-regexp-format
6345 (concat "\\(" org-comment-string "\\)"))
6346 '(2 'org-special-keyword t))
6347 ;; Blocks and meta lines
6348 '(org-fontify-meta-lines-and-blocks))))
6349 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6350 (run-hooks 'org-font-lock-set-keywords-hook)
6351 ;; Now set the full font-lock-keywords
6352 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6353 (org-set-local 'font-lock-defaults
6354 '(org-font-lock-keywords t nil nil backward-paragraph))
6355 (kill-local-variable 'font-lock-keywords) nil))
6357 (defun org-toggle-pretty-entities ()
6358 "Toggle the composition display of entities as UTF8 characters."
6359 (interactive)
6360 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6361 (org-restart-font-lock)
6362 (if org-pretty-entities
6363 (message "Entities are now displayed as UTF8 characters")
6364 (save-restriction
6365 (widen)
6366 (org-decompose-region (point-min) (point-max))
6367 (message "Entities are now displayed as plain text"))))
6369 (defvar org-custom-properties-overlays nil
6370 "List of overlays used for custom properties.")
6371 (make-variable-buffer-local 'org-custom-properties-overlays)
6373 (defun org-toggle-custom-properties-visibility ()
6374 "Display or hide properties in `org-custom-properties'."
6375 (interactive)
6376 (if org-custom-properties-overlays
6377 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6378 (setq org-custom-properties-overlays nil))
6379 (unless (not org-custom-properties)
6380 (save-excursion
6381 (save-restriction
6382 (widen)
6383 (goto-char (point-min))
6384 (while (re-search-forward org-property-re nil t)
6385 (mapc (lambda(p)
6386 (when (equal p (substring (match-string 1) 1 -1))
6387 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6388 (overlay-put o 'invisible t)
6389 (overlay-put o 'org-custom-property t)
6390 (push o org-custom-properties-overlays))))
6391 org-custom-properties)))))))
6393 (defun org-fontify-entities (limit)
6394 "Find an entity to fontify."
6395 (let (ee)
6396 (when org-pretty-entities
6397 (catch 'match
6398 (while (re-search-forward
6399 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6400 limit t)
6401 (if (and (not (org-in-indented-comment-line))
6402 (setq ee (org-entity-get (match-string 1)))
6403 (= (length (nth 6 ee)) 1))
6404 (let*
6405 ((end (if (equal (match-string 2) "{}")
6406 (match-end 2)
6407 (match-end 1))))
6408 (add-text-properties
6409 (match-beginning 0) end
6410 (list 'font-lock-fontified t))
6411 (compose-region (match-beginning 0) end
6412 (nth 6 ee) nil)
6413 (backward-char 1)
6414 (throw 'match t))))
6415 nil))))
6417 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6418 "Fontify string S like in Org-mode."
6419 (with-temp-buffer
6420 (insert s)
6421 (let ((org-odd-levels-only odd-levels))
6422 (org-mode)
6423 (font-lock-fontify-buffer)
6424 (buffer-string))))
6426 (defvar org-m nil)
6427 (defvar org-l nil)
6428 (defvar org-f nil)
6429 (defun org-get-level-face (n)
6430 "Get the right face for match N in font-lock matching of headlines."
6431 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6432 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6433 (if org-cycle-level-faces
6434 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6435 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6436 (cond
6437 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6438 ((eq n 2) org-f)
6439 (t (if org-level-color-stars-only nil org-f))))
6442 (defun org-get-todo-face (kwd)
6443 "Get the right face for a TODO keyword KWD.
6444 If KWD is a number, get the corresponding match group."
6445 (if (numberp kwd) (setq kwd (match-string kwd)))
6446 (or (org-face-from-face-or-color
6447 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6448 (and (member kwd org-done-keywords) 'org-done)
6449 'org-todo))
6451 (defun org-face-from-face-or-color (context inherit face-or-color)
6452 "Create a face list that inherits INHERIT, but sets the foreground color.
6453 When FACE-OR-COLOR is not a string, just return it."
6454 (if (stringp face-or-color)
6455 (list :inherit inherit
6456 (cdr (assoc context org-faces-easy-properties))
6457 face-or-color)
6458 face-or-color))
6460 (defun org-font-lock-add-tag-faces (limit)
6461 "Add the special tag faces."
6462 (when (and org-tag-faces org-tags-special-faces-re)
6463 (while (re-search-forward org-tags-special-faces-re limit t)
6464 (add-text-properties (match-beginning 1) (match-end 1)
6465 (list 'face (org-get-tag-face 1)
6466 'font-lock-fontified t))
6467 (backward-char 1))))
6469 (defun org-font-lock-add-priority-faces (limit)
6470 "Add the special priority faces."
6471 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6472 (when (save-match-data (org-at-heading-p))
6473 (add-text-properties
6474 (match-beginning 0) (match-end 0)
6475 (list 'face (or (org-face-from-face-or-color
6476 'priority 'org-priority
6477 (cdr (assoc (char-after (match-beginning 1))
6478 org-priority-faces)))
6479 'org-priority)
6480 'font-lock-fontified t)))))
6482 (defun org-get-tag-face (kwd)
6483 "Get the right face for a TODO keyword KWD.
6484 If KWD is a number, get the corresponding match group."
6485 (if (numberp kwd) (setq kwd (match-string kwd)))
6486 (or (org-face-from-face-or-color
6487 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6488 'org-tag))
6490 (defun org-unfontify-region (beg end &optional maybe_loudly)
6491 "Remove fontification and activation overlays from links."
6492 (font-lock-default-unfontify-region beg end)
6493 (let* ((buffer-undo-list t)
6494 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6495 (inhibit-modification-hooks t)
6496 deactivate-mark buffer-file-name buffer-file-truename)
6497 (org-decompose-region beg end)
6498 (remove-text-properties beg end
6499 '(mouse-face t keymap t org-linked-text t
6500 invisible t intangible t
6501 org-emphasis t))
6502 (org-remove-font-lock-display-properties beg end)))
6504 (defconst org-script-display '(((raise -0.3) (height 0.7))
6505 ((raise 0.3) (height 0.7))
6506 ((raise -0.5))
6507 ((raise 0.5)))
6508 "Display properties for showing superscripts and subscripts.")
6510 (defun org-remove-font-lock-display-properties (beg end)
6511 "Remove specific display properties that have been added by font lock.
6512 The will remove the raise properties that are used to show superscripts
6513 and subscripts."
6514 (let (next prop)
6515 (while (< beg end)
6516 (setq next (next-single-property-change beg 'display nil end)
6517 prop (get-text-property beg 'display))
6518 (if (member prop org-script-display)
6519 (put-text-property beg next 'display nil))
6520 (setq beg next))))
6522 (defun org-raise-scripts (limit)
6523 "Add raise properties to sub/superscripts."
6524 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6525 (if (re-search-forward
6526 (if (eq org-use-sub-superscripts t)
6527 org-match-substring-regexp
6528 org-match-substring-with-braces-regexp)
6529 limit t)
6530 (let* ((pos (point)) table-p comment-p
6531 (mpos (match-beginning 3))
6532 (emph-p (get-text-property mpos 'org-emphasis))
6533 (link-p (get-text-property mpos 'mouse-face))
6534 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6535 (goto-char (point-at-bol))
6536 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6537 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6538 (goto-char pos)
6539 ;; Handle a_b^c
6540 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6541 (if (or comment-p emph-p link-p keyw-p)
6543 (put-text-property (match-beginning 3) (match-end 0)
6544 'display
6545 (if (equal (char-after (match-beginning 2)) ?^)
6546 (nth (if table-p 3 1) org-script-display)
6547 (nth (if table-p 2 0) org-script-display)))
6548 (add-text-properties (match-beginning 2) (match-end 2)
6549 (list 'invisible t
6550 'org-dwidth t 'org-dwidth-n 1))
6551 (if (and (eq (char-after (match-beginning 3)) ?{)
6552 (eq (char-before (match-end 3)) ?}))
6553 (progn
6554 (add-text-properties
6555 (match-beginning 3) (1+ (match-beginning 3))
6556 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6557 (add-text-properties
6558 (1- (match-end 3)) (match-end 3)
6559 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6560 t)))))
6562 ;;;; Visibility cycling, including org-goto and indirect buffer
6564 ;;; Cycling
6566 (defvar org-cycle-global-status nil)
6567 (make-variable-buffer-local 'org-cycle-global-status)
6568 (put 'org-cycle-global-status 'org-state t)
6569 (defvar org-cycle-subtree-status nil)
6570 (make-variable-buffer-local 'org-cycle-subtree-status)
6571 (put 'org-cycle-subtree-status 'org-state t)
6573 (defvar org-inlinetask-min-level)
6575 (defun org-unlogged-message (&rest args)
6576 "Display a message, but avoid logging it in the *Messages* buffer."
6577 (let ((message-log-max nil))
6578 (apply 'message args)))
6580 ;;;###autoload
6581 (defun org-cycle (&optional arg)
6582 "TAB-action and visibility cycling for Org-mode.
6584 This is the command invoked in Org-mode by the TAB key. Its main purpose
6585 is outline visibility cycling, but it also invokes other actions
6586 in special contexts.
6588 - When this function is called with a prefix argument, rotate the entire
6589 buffer through 3 states (global cycling)
6590 1. OVERVIEW: Show only top-level headlines.
6591 2. CONTENTS: Show all headlines of all levels, but no body text.
6592 3. SHOW ALL: Show everything.
6593 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6594 determined by the variable `org-startup-folded', and by any VISIBILITY
6595 properties in the buffer.
6596 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6597 including any drawers.
6599 - When inside a table, re-align the table and move to the next field.
6601 - When point is at the beginning of a headline, rotate the subtree started
6602 by this line through 3 different states (local cycling)
6603 1. FOLDED: Only the main headline is shown.
6604 2. CHILDREN: The main headline and the direct children are shown.
6605 From this state, you can move to one of the children
6606 and zoom in further.
6607 3. SUBTREE: Show the entire subtree, including body text.
6608 If there is no subtree, switch directly from CHILDREN to FOLDED.
6610 - When point is at the beginning of an empty headline and the variable
6611 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6612 of the headline by demoting and promoting it to likely levels. This
6613 speeds up creation document structure by pressing TAB once or several
6614 times right after creating a new headline.
6616 - When there is a numeric prefix, go up to a heading with level ARG, do
6617 a `show-subtree' and return to the previous cursor position. If ARG
6618 is negative, go up that many levels.
6620 - When point is not at the beginning of a headline, execute the global
6621 binding for TAB, which is re-indenting the line. See the option
6622 `org-cycle-emulate-tab' for details.
6624 - Special case: if point is at the beginning of the buffer and there is
6625 no headline in line 1, this function will act as if called with prefix arg
6626 (C-u TAB, same as S-TAB) also when called without prefix arg.
6627 But only if also the variable `org-cycle-global-at-bob' is t."
6628 (interactive "P")
6629 (org-load-modules-maybe)
6630 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6631 (and org-cycle-level-after-item/entry-creation
6632 (or (org-cycle-level)
6633 (org-cycle-item-indentation))))
6634 (let* ((limit-level
6635 (or org-cycle-max-level
6636 (and (boundp 'org-inlinetask-min-level)
6637 org-inlinetask-min-level
6638 (1- org-inlinetask-min-level))))
6639 (nstars (and limit-level
6640 (if org-odd-levels-only
6641 (and limit-level (1- (* limit-level 2)))
6642 limit-level)))
6643 (org-outline-regexp
6644 (if (not (derived-mode-p 'org-mode))
6645 outline-regexp
6646 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6647 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6648 (not (looking-at org-outline-regexp))))
6649 (org-cycle-hook
6650 (if bob-special
6651 (delq 'org-optimize-window-after-visibility-change
6652 (copy-sequence org-cycle-hook))
6653 org-cycle-hook))
6654 (pos (point)))
6656 (if (or bob-special (equal arg '(4)))
6657 ;; special case: use global cycling
6658 (setq arg t))
6660 (cond
6662 ((equal arg '(16))
6663 (setq last-command 'dummy)
6664 (org-set-startup-visibility)
6665 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6667 ((equal arg '(64))
6668 (show-all)
6669 (org-unlogged-message "Entire buffer visible, including drawers"))
6671 ;; Table: enter it or move to the next field.
6672 ((org-at-table-p 'any)
6673 (if (org-at-table.el-p)
6674 (message "Use C-c ' to edit table.el tables")
6675 (if arg (org-table-edit-field t)
6676 (org-table-justify-field-maybe)
6677 (call-interactively 'org-table-next-field))))
6679 ((run-hook-with-args-until-success
6680 'org-tab-after-check-for-table-hook))
6682 ;; Global cycling: delegate to `org-cycle-internal-global'.
6683 ((eq arg t) (org-cycle-internal-global))
6685 ;; Drawers: delegate to `org-flag-drawer'.
6686 ((save-excursion
6687 (beginning-of-line 1)
6688 (looking-at org-drawer-regexp))
6689 (org-flag-drawer ; toggle block visibility
6690 (not (get-char-property (match-end 0) 'invisible))))
6692 ;; Show-subtree, ARG levels up from here.
6693 ((integerp arg)
6694 (save-excursion
6695 (org-back-to-heading)
6696 (outline-up-heading (if (< arg 0) (- arg)
6697 (- (funcall outline-level) arg)))
6698 (org-show-subtree)))
6700 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6701 ((and (featurep 'org-inlinetask)
6702 (org-inlinetask-at-task-p)
6703 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6704 (org-inlinetask-toggle-visibility))
6706 ((org-try-cdlatex-tab))
6708 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6709 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6710 (save-excursion (beginning-of-line 1)
6711 (looking-at org-outline-regexp)))
6712 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6713 (org-cycle-internal-local))
6715 ;; From there: TAB emulation and template completion.
6716 (buffer-read-only (org-back-to-heading))
6718 ((run-hook-with-args-until-success
6719 'org-tab-after-check-for-cycling-hook))
6721 ((org-try-structure-completion))
6723 ((run-hook-with-args-until-success
6724 'org-tab-before-tab-emulation-hook))
6726 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6727 (or (not (bolp))
6728 (not (looking-at org-outline-regexp))))
6729 (call-interactively (global-key-binding "\t")))
6731 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6732 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6733 (or (and (eq org-cycle-emulate-tab 'white)
6734 (= (match-end 0) (point-at-eol)))
6735 (and (eq org-cycle-emulate-tab 'whitestart)
6736 (>= (match-end 0) pos))))
6738 (eq org-cycle-emulate-tab t))
6739 (call-interactively (global-key-binding "\t")))
6741 (t (save-excursion
6742 (org-back-to-heading)
6743 (org-cycle)))))))
6745 (defun org-cycle-internal-global ()
6746 "Do the global cycling action."
6747 ;; Hack to avoid display of messages for .org attachments in Gnus
6748 (let ((ga (string-match "\\*fontification" (buffer-name))))
6749 (cond
6750 ((and (eq last-command this-command)
6751 (eq org-cycle-global-status 'overview))
6752 ;; We just created the overview - now do table of contents
6753 ;; This can be slow in very large buffers, so indicate action
6754 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6755 (unless ga (org-unlogged-message "CONTENTS..."))
6756 (org-content)
6757 (unless ga (org-unlogged-message "CONTENTS...done"))
6758 (setq org-cycle-global-status 'contents)
6759 (run-hook-with-args 'org-cycle-hook 'contents))
6761 ((and (eq last-command this-command)
6762 (eq org-cycle-global-status 'contents))
6763 ;; We just showed the table of contents - now show everything
6764 (run-hook-with-args 'org-pre-cycle-hook 'all)
6765 (show-all)
6766 (unless ga (org-unlogged-message "SHOW ALL"))
6767 (setq org-cycle-global-status 'all)
6768 (run-hook-with-args 'org-cycle-hook 'all))
6771 ;; Default action: go to overview
6772 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6773 (org-overview)
6774 (unless ga (org-unlogged-message "OVERVIEW"))
6775 (setq org-cycle-global-status 'overview)
6776 (run-hook-with-args 'org-cycle-hook 'overview)))))
6778 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6780 (defun org-cycle-internal-local ()
6781 "Do the local cycling action."
6782 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6783 ;; First, determine end of headline (EOH), end of subtree or item
6784 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6785 (save-excursion
6786 (if (org-at-item-p)
6787 (progn
6788 (beginning-of-line)
6789 (setq struct (org-list-struct))
6790 (setq eoh (point-at-eol))
6791 (setq eos (org-list-get-item-end-before-blank (point) struct))
6792 (setq has-children (org-list-has-child-p (point) struct)))
6793 (org-back-to-heading)
6794 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6795 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6796 (setq has-children
6797 (or (save-excursion
6798 (let ((level (funcall outline-level)))
6799 (outline-next-heading)
6800 (and (org-at-heading-p t)
6801 (> (funcall outline-level) level))))
6802 (save-excursion
6803 (org-list-search-forward (org-item-beginning-re) eos t)))))
6804 ;; Determine end invisible part of buffer (EOL)
6805 (beginning-of-line 2)
6806 ;; XEmacs doesn't have `next-single-char-property-change'
6807 (if (featurep 'xemacs)
6808 (while (and (not (eobp)) ;; this is like `next-line'
6809 (get-char-property (1- (point)) 'invisible))
6810 (beginning-of-line 2))
6811 (while (and (not (eobp)) ;; this is like `next-line'
6812 (get-char-property (1- (point)) 'invisible))
6813 (goto-char (next-single-char-property-change (point) 'invisible))
6814 (and (eolp) (beginning-of-line 2))))
6815 (setq eol (point)))
6816 ;; Find out what to do next and set `this-command'
6817 (cond
6818 ((= eos eoh)
6819 ;; Nothing is hidden behind this heading
6820 (unless (org-before-first-heading-p)
6821 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6822 (org-unlogged-message "EMPTY ENTRY")
6823 (setq org-cycle-subtree-status nil)
6824 (save-excursion
6825 (goto-char eos)
6826 (outline-next-heading)
6827 (if (outline-invisible-p) (org-flag-heading nil))))
6828 ((and (or (>= eol eos)
6829 (not (string-match "\\S-" (buffer-substring eol eos))))
6830 (or has-children
6831 (not (setq children-skipped
6832 org-cycle-skip-children-state-if-no-children))))
6833 ;; Entire subtree is hidden in one line: children view
6834 (unless (org-before-first-heading-p)
6835 (run-hook-with-args 'org-pre-cycle-hook 'children))
6836 (if (org-at-item-p)
6837 (org-list-set-item-visibility (point-at-bol) struct 'children)
6838 (org-show-entry)
6839 (org-with-limited-levels (show-children))
6840 ;; FIXME: This slows down the func way too much.
6841 ;; How keep drawers hidden in subtree anyway?
6842 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6843 ;; (org-cycle-hide-drawers 'subtree))
6845 ;; Fold every list in subtree to top-level items.
6846 (when (eq org-cycle-include-plain-lists 'integrate)
6847 (save-excursion
6848 (org-back-to-heading)
6849 (while (org-list-search-forward (org-item-beginning-re) eos t)
6850 (beginning-of-line 1)
6851 (let* ((struct (org-list-struct))
6852 (prevs (org-list-prevs-alist struct))
6853 (end (org-list-get-bottom-point struct)))
6854 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6855 (org-list-get-all-items (point) struct prevs))
6856 (goto-char (if (< end eos) end eos)))))))
6857 (org-unlogged-message "CHILDREN")
6858 (save-excursion
6859 (goto-char eos)
6860 (outline-next-heading)
6861 (if (outline-invisible-p) (org-flag-heading nil)))
6862 (setq org-cycle-subtree-status 'children)
6863 (unless (org-before-first-heading-p)
6864 (run-hook-with-args 'org-cycle-hook 'children)))
6865 ((or children-skipped
6866 (and (eq last-command this-command)
6867 (eq org-cycle-subtree-status 'children)))
6868 ;; We just showed the children, or no children are there,
6869 ;; now show everything.
6870 (unless (org-before-first-heading-p)
6871 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6872 (outline-flag-region eoh eos nil)
6873 (org-unlogged-message
6874 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6875 (setq org-cycle-subtree-status 'subtree)
6876 (unless (org-before-first-heading-p)
6877 (run-hook-with-args 'org-cycle-hook 'subtree)))
6879 ;; Default action: hide the subtree.
6880 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6881 (outline-flag-region eoh eos t)
6882 (org-unlogged-message "FOLDED")
6883 (setq org-cycle-subtree-status 'folded)
6884 (unless (org-before-first-heading-p)
6885 (run-hook-with-args 'org-cycle-hook 'folded))))))
6887 ;;;###autoload
6888 (defun org-global-cycle (&optional arg)
6889 "Cycle the global visibility. For details see `org-cycle'.
6890 With \\[universal-argument] prefix arg, switch to startup visibility.
6891 With a numeric prefix, show all headlines up to that level."
6892 (interactive "P")
6893 (let ((org-cycle-include-plain-lists
6894 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6895 (cond
6896 ((integerp arg)
6897 (show-all)
6898 (hide-sublevels arg)
6899 (setq org-cycle-global-status 'contents))
6900 ((equal arg '(4))
6901 (org-set-startup-visibility)
6902 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6904 (org-cycle '(4))))))
6906 (defun org-set-startup-visibility ()
6907 "Set the visibility required by startup options and properties."
6908 (cond
6909 ((eq org-startup-folded t)
6910 (org-overview))
6911 ((eq org-startup-folded 'content)
6912 (org-content))
6913 ((or (eq org-startup-folded 'showeverything)
6914 (eq org-startup-folded nil))
6915 (show-all)))
6916 (unless (eq org-startup-folded 'showeverything)
6917 (if org-hide-block-startup (org-hide-block-all))
6918 (org-set-visibility-according-to-property 'no-cleanup)
6919 (org-cycle-hide-archived-subtrees 'all)
6920 (org-cycle-hide-drawers 'all)
6921 (org-cycle-show-empty-lines t)))
6923 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6924 "Switch subtree visibilities according to :VISIBILITY: property."
6925 (interactive)
6926 (let (org-show-entry-below state)
6927 (save-excursion
6928 (goto-char (point-min))
6929 (while (re-search-forward
6930 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6931 nil t)
6932 (setq state (match-string 1))
6933 (save-excursion
6934 (org-back-to-heading t)
6935 (hide-subtree)
6936 (org-reveal)
6937 (cond
6938 ((equal state '("fold" "folded"))
6939 (hide-subtree))
6940 ((equal state "children")
6941 (org-show-hidden-entry)
6942 (show-children))
6943 ((equal state "content")
6944 (save-excursion
6945 (save-restriction
6946 (org-narrow-to-subtree)
6947 (org-content))))
6948 ((member state '("all" "showall"))
6949 (show-subtree)))))
6950 (unless no-cleanup
6951 (org-cycle-hide-archived-subtrees 'all)
6952 (org-cycle-hide-drawers 'all)
6953 (org-cycle-show-empty-lines 'all)))))
6955 ;; This function uses outline-regexp instead of the more fundamental
6956 ;; org-outline-regexp so that org-cycle-global works outside of Org
6957 ;; buffers, where outline-regexp is needed.
6958 (defun org-overview ()
6959 "Switch to overview mode, showing only top-level headlines.
6960 Really, this shows all headlines with level equal or greater than the level
6961 of the first headline in the buffer. This is important, because if the
6962 first headline is not level one, then (hide-sublevels 1) gives confusing
6963 results."
6964 (interactive)
6965 (let ((pos (point))
6966 (level (save-excursion
6967 (goto-char (point-min))
6968 (if (re-search-forward (concat "^" outline-regexp) nil t)
6969 (progn
6970 (goto-char (match-beginning 0))
6971 (funcall outline-level))))))
6972 (and level (hide-sublevels level))
6973 (recenter '(4))
6974 (goto-char pos)))
6976 (defun org-content (&optional arg)
6977 "Show all headlines in the buffer, like a table of contents.
6978 With numerical argument N, show content up to level N."
6979 (interactive "P")
6980 (org-overview)
6981 (save-excursion
6982 ;; Visit all headings and show their offspring
6983 (and (integerp arg) (org-overview))
6984 (goto-char (point-max))
6985 (catch 'exit
6986 (while (and (progn (condition-case nil
6987 (outline-previous-visible-heading 1)
6988 (error (goto-char (point-min))))
6990 (looking-at org-outline-regexp))
6991 (if (integerp arg)
6992 (show-children (1- arg))
6993 (show-branches))
6994 (if (bobp) (throw 'exit nil))))))
6996 (defun org-optimize-window-after-visibility-change (state)
6997 "Adjust the window after a change in outline visibility.
6998 This function is the default value of the hook `org-cycle-hook'."
6999 (when (get-buffer-window (current-buffer))
7000 (cond
7001 ((eq state 'content) nil)
7002 ((eq state 'all) nil)
7003 ((eq state 'folded) nil)
7004 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7005 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7007 (defun org-remove-empty-overlays-at (pos)
7008 "Remove outline overlays that do not contain non-white stuff."
7009 (mapc
7010 (lambda (o)
7011 (and (eq 'outline (overlay-get o 'invisible))
7012 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7013 (overlay-end o))))
7014 (delete-overlay o)))
7015 (overlays-at pos)))
7017 (defun org-clean-visibility-after-subtree-move ()
7018 "Fix visibility issues after moving a subtree."
7019 ;; First, find a reasonable region to look at:
7020 ;; Start two siblings above, end three below
7021 (let* ((beg (save-excursion
7022 (and (org-get-last-sibling)
7023 (org-get-last-sibling))
7024 (point)))
7025 (end (save-excursion
7026 (and (org-get-next-sibling)
7027 (org-get-next-sibling)
7028 (org-get-next-sibling))
7029 (if (org-at-heading-p)
7030 (point-at-eol)
7031 (point))))
7032 (level (looking-at "\\*+"))
7033 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7034 (save-excursion
7035 (save-restriction
7036 (narrow-to-region beg end)
7037 (when re
7038 ;; Properly fold already folded siblings
7039 (goto-char (point-min))
7040 (while (re-search-forward re nil t)
7041 (if (and (not (outline-invisible-p))
7042 (save-excursion
7043 (goto-char (point-at-eol)) (outline-invisible-p)))
7044 (hide-entry))))
7045 (org-cycle-show-empty-lines 'overview)
7046 (org-cycle-hide-drawers 'overview)))))
7048 (defun org-cycle-show-empty-lines (state)
7049 "Show empty lines above all visible headlines.
7050 The region to be covered depends on STATE when called through
7051 `org-cycle-hook'. Lisp program can use t for STATE to get the
7052 entire buffer covered. Note that an empty line is only shown if there
7053 are at least `org-cycle-separator-lines' empty lines before the headline."
7054 (when (not (= org-cycle-separator-lines 0))
7055 (save-excursion
7056 (let* ((n (abs org-cycle-separator-lines))
7057 (re (cond
7058 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7059 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7060 (t (let ((ns (number-to-string (- n 2))))
7061 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7062 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7063 beg end b e)
7064 (cond
7065 ((memq state '(overview contents t))
7066 (setq beg (point-min) end (point-max)))
7067 ((memq state '(children folded))
7068 (setq beg (point) end (progn (org-end-of-subtree t t)
7069 (beginning-of-line 2)
7070 (point)))))
7071 (when beg
7072 (goto-char beg)
7073 (while (re-search-forward re end t)
7074 (unless (get-char-property (match-end 1) 'invisible)
7075 (setq e (match-end 1))
7076 (if (< org-cycle-separator-lines 0)
7077 (setq b (save-excursion
7078 (goto-char (match-beginning 0))
7079 (org-back-over-empty-lines)
7080 (if (save-excursion
7081 (goto-char (max (point-min) (1- (point))))
7082 (org-at-heading-p))
7083 (1- (point))
7084 (point))))
7085 (setq b (match-beginning 1)))
7086 (outline-flag-region b e nil)))))))
7087 ;; Never hide empty lines at the end of the file.
7088 (save-excursion
7089 (goto-char (point-max))
7090 (outline-previous-heading)
7091 (outline-end-of-heading)
7092 (if (and (looking-at "[ \t\n]+")
7093 (= (match-end 0) (point-max)))
7094 (outline-flag-region (point) (match-end 0) nil))))
7096 (defun org-show-empty-lines-in-parent ()
7097 "Move to the parent and re-show empty lines before visible headlines."
7098 (save-excursion
7099 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7100 (org-cycle-show-empty-lines context))))
7102 (defun org-files-list ()
7103 "Return `org-agenda-files' list, plus all open org-mode files.
7104 This is useful for operations that need to scan all of a user's
7105 open and agenda-wise Org files."
7106 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7107 (dolist (buf (buffer-list))
7108 (with-current-buffer buf
7109 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7110 (let ((file (expand-file-name (buffer-file-name))))
7111 (unless (member file files)
7112 (push file files))))))
7113 files))
7115 (defsubst org-entry-beginning-position ()
7116 "Return the beginning position of the current entry."
7117 (save-excursion (outline-back-to-heading t) (point)))
7119 (defsubst org-entry-end-position ()
7120 "Return the end position of the current entry."
7121 (save-excursion (outline-next-heading) (point)))
7123 (defun org-cycle-hide-drawers (state &optional exceptions)
7124 "Re-hide all drawers after a visibility state change.
7125 When non-nil, optional argument EXCEPTIONS is a list of strings
7126 specifying which drawers should not be hidden."
7127 (when (and (derived-mode-p 'org-mode)
7128 (not (memq state '(overview folded contents))))
7129 (save-excursion
7130 (let* ((globalp (memq state '(contents all)))
7131 (beg (if globalp (point-min) (point)))
7132 (end (if globalp (point-max)
7133 (if (eq state 'children)
7134 (save-excursion (outline-next-heading) (point))
7135 (org-end-of-subtree t)))))
7136 (goto-char beg)
7137 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7138 (unless (member-ignore-case (match-string 1) exceptions)
7139 (let ((drawer (org-element-at-point)))
7140 (when (memq (org-element-type drawer) '(drawer property-drawer))
7141 (org-flag-drawer t drawer)
7142 ;; Make sure to skip drawer entirely or we might flag
7143 ;; it another time when matching its ending line with
7144 ;; `org-drawer-regexp'.
7145 (goto-char (org-element-property :end drawer))))))))))
7147 (defun org-cycle-hide-inline-tasks (state)
7148 "Re-hide inline tasks when switching to 'contents or 'children
7149 visibility state."
7150 (case state
7151 (contents
7152 (when (org-bound-and-true-p org-inlinetask-min-level)
7153 (hide-sublevels (1- org-inlinetask-min-level))))
7154 (children
7155 (when (featurep 'org-inlinetask)
7156 (save-excursion
7157 (while (and (outline-next-heading)
7158 (org-inlinetask-at-task-p))
7159 (org-inlinetask-toggle-visibility)
7160 (org-inlinetask-goto-end)))))))
7162 (defun org-flag-drawer (flag &optional element)
7163 "When FLAG is non-nil, hide the drawer we are at.
7164 Otherwise make it visible. When optional argument ELEMENT is
7165 a parsed drawer, as returned by `org-element-at-point', hide or
7166 show that drawer instead."
7167 (let ((drawer (or element (org-element-at-point))))
7168 (when (memq (org-element-type drawer) '(drawer property-drawer))
7169 (save-excursion
7170 (goto-char (org-element-property :post-affiliated drawer))
7171 (outline-flag-region
7172 (line-end-position)
7173 (progn (goto-char (org-element-property :end drawer))
7174 (skip-chars-backward " \r\t\n")
7175 (line-end-position))
7176 flag)))))
7178 (defun org-subtree-end-visible-p ()
7179 "Is the end of the current subtree visible?"
7180 (pos-visible-in-window-p
7181 (save-excursion (org-end-of-subtree t) (point))))
7183 (defun org-first-headline-recenter (&optional N)
7184 "Move cursor to the first headline and recenter the headline.
7185 Optional argument N means put the headline into the Nth line of the window."
7186 (goto-char (point-min))
7187 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7188 (beginning-of-line)
7189 (recenter (prefix-numeric-value N))))
7191 ;;; Saving and restoring visibility
7193 (defun org-outline-overlay-data (&optional use-markers)
7194 "Return a list of the locations of all outline overlays.
7195 These are overlays with the `invisible' property value `outline'.
7196 The return value is a list of cons cells, with start and stop
7197 positions for each overlay.
7198 If USE-MARKERS is set, return the positions as markers."
7199 (let (beg end)
7200 (save-excursion
7201 (save-restriction
7202 (widen)
7203 (delq nil
7204 (mapcar (lambda (o)
7205 (when (eq (overlay-get o 'invisible) 'outline)
7206 (setq beg (overlay-start o)
7207 end (overlay-end o))
7208 (and beg end (> end beg)
7209 (if use-markers
7210 (cons (copy-marker beg)
7211 (copy-marker end t))
7212 (cons beg end)))))
7213 (overlays-in (point-min) (point-max))))))))
7215 (defun org-set-outline-overlay-data (data)
7216 "Create visibility overlays for all positions in DATA.
7217 DATA should have been made by `org-outline-overlay-data'."
7218 (let (o)
7219 (save-excursion
7220 (save-restriction
7221 (widen)
7222 (show-all)
7223 (mapc (lambda (c)
7224 (outline-flag-region (car c) (cdr c) t))
7225 data)))))
7227 ;;; Folding of blocks
7229 (defvar org-hide-block-overlays nil
7230 "Overlays hiding blocks.")
7231 (make-variable-buffer-local 'org-hide-block-overlays)
7233 (defun org-block-map (function &optional start end)
7234 "Call FUNCTION at the head of all source blocks in the current buffer.
7235 Optional arguments START and END can be used to limit the range."
7236 (let ((start (or start (point-min)))
7237 (end (or end (point-max))))
7238 (save-excursion
7239 (goto-char start)
7240 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7241 (save-excursion
7242 (save-match-data
7243 (goto-char (match-beginning 0))
7244 (funcall function)))))))
7246 (defun org-hide-block-toggle-all ()
7247 "Toggle the visibility of all blocks in the current buffer."
7248 (org-block-map #'org-hide-block-toggle))
7250 (defun org-hide-block-all ()
7251 "Fold all blocks in the current buffer."
7252 (interactive)
7253 (org-show-block-all)
7254 (org-block-map #'org-hide-block-toggle-maybe))
7256 (defun org-show-block-all ()
7257 "Unfold all blocks in the current buffer."
7258 (interactive)
7259 (mapc 'delete-overlay org-hide-block-overlays)
7260 (setq org-hide-block-overlays nil))
7262 (defun org-hide-block-toggle-maybe ()
7263 "Toggle visibility of block at point."
7264 (interactive)
7265 (let ((case-fold-search t))
7266 (if (save-excursion
7267 (beginning-of-line 1)
7268 (looking-at org-block-regexp))
7269 (progn (org-hide-block-toggle)
7270 t) ;; to signal that we took action
7271 nil))) ;; to signal that we did not
7273 (defun org-hide-block-toggle (&optional force)
7274 "Toggle the visibility of the current block."
7275 (interactive)
7276 (save-excursion
7277 (beginning-of-line)
7278 (if (re-search-forward org-block-regexp nil t)
7279 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7280 (end (match-end 0)) ;; end of entire body
7282 (if (memq t (mapcar (lambda (overlay)
7283 (eq (overlay-get overlay 'invisible)
7284 'org-hide-block))
7285 (overlays-at start)))
7286 (if (or (not force) (eq force 'off))
7287 (mapc (lambda (ov)
7288 (when (member ov org-hide-block-overlays)
7289 (setq org-hide-block-overlays
7290 (delq ov org-hide-block-overlays)))
7291 (when (eq (overlay-get ov 'invisible)
7292 'org-hide-block)
7293 (delete-overlay ov)))
7294 (overlays-at start)))
7295 (setq ov (make-overlay start end))
7296 (overlay-put ov 'invisible 'org-hide-block)
7297 ;; make the block accessible to isearch
7298 (overlay-put
7299 ov 'isearch-open-invisible
7300 (lambda (ov)
7301 (when (member ov org-hide-block-overlays)
7302 (setq org-hide-block-overlays
7303 (delq ov org-hide-block-overlays)))
7304 (when (eq (overlay-get ov 'invisible)
7305 'org-hide-block)
7306 (delete-overlay ov))))
7307 (push ov org-hide-block-overlays)))
7308 (user-error "Not looking at a source block"))))
7310 ;; org-tab-after-check-for-cycling-hook
7311 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7312 ;; Remove overlays when changing major mode
7313 (add-hook 'org-mode-hook
7314 (lambda () (org-add-hook 'change-major-mode-hook
7315 'org-show-block-all 'append 'local)))
7317 ;;; Org-goto
7319 (defvar org-goto-window-configuration nil)
7320 (defvar org-goto-marker nil)
7321 (defvar org-goto-map)
7322 (defun org-goto-map ()
7323 "Set the keymap `org-goto'."
7324 (setq org-goto-map
7325 (let ((map (make-sparse-keymap)))
7326 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7327 mouse-drag-region universal-argument org-occur))
7328 cmd)
7329 (while (setq cmd (pop cmds))
7330 (substitute-key-definition cmd cmd map global-map)))
7331 (suppress-keymap map)
7332 (org-defkey map "\C-m" 'org-goto-ret)
7333 (org-defkey map [(return)] 'org-goto-ret)
7334 (org-defkey map [(left)] 'org-goto-left)
7335 (org-defkey map [(right)] 'org-goto-right)
7336 (org-defkey map [(control ?g)] 'org-goto-quit)
7337 (org-defkey map "\C-i" 'org-cycle)
7338 (org-defkey map [(tab)] 'org-cycle)
7339 (org-defkey map [(down)] 'outline-next-visible-heading)
7340 (org-defkey map [(up)] 'outline-previous-visible-heading)
7341 (if org-goto-auto-isearch
7342 (if (fboundp 'define-key-after)
7343 (define-key-after map [t] 'org-goto-local-auto-isearch)
7344 nil)
7345 (org-defkey map "q" 'org-goto-quit)
7346 (org-defkey map "n" 'outline-next-visible-heading)
7347 (org-defkey map "p" 'outline-previous-visible-heading)
7348 (org-defkey map "f" 'outline-forward-same-level)
7349 (org-defkey map "b" 'outline-backward-same-level)
7350 (org-defkey map "u" 'outline-up-heading))
7351 (org-defkey map "/" 'org-occur)
7352 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7353 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7354 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7355 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7356 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7357 map)))
7359 (defconst org-goto-help
7360 "Browse buffer copy, to find location or copy text.%s
7361 RET=jump to location C-g=quit and return to previous location
7362 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7364 (defvar org-goto-start-pos) ; dynamically scoped parameter
7366 (defun org-goto (&optional alternative-interface)
7367 "Look up a different location in the current file, keeping current visibility.
7369 When you want look-up or go to a different location in a
7370 document, the fastest way is often to fold the entire buffer and
7371 then dive into the tree. This method has the disadvantage, that
7372 the previous location will be folded, which may not be what you
7373 want.
7375 This command works around this by showing a copy of the current
7376 buffer in an indirect buffer, in overview mode. You can dive
7377 into the tree in that copy, use org-occur and incremental search
7378 to find a location. When pressing RET or `Q', the command
7379 returns to the original buffer in which the visibility is still
7380 unchanged. After RET it will also jump to the location selected
7381 in the indirect buffer and expose the headline hierarchy above.
7383 With a prefix argument, use the alternative interface: e.g. if
7384 `org-goto-interface' is 'outline use 'outline-path-completion."
7385 (interactive "P")
7386 (org-goto-map)
7387 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7388 (org-refile-use-outline-path t)
7389 (org-refile-target-verify-function nil)
7390 (interface
7391 (if (not alternative-interface)
7392 org-goto-interface
7393 (if (eq org-goto-interface 'outline)
7394 'outline-path-completion
7395 'outline)))
7396 (org-goto-start-pos (point))
7397 (selected-point
7398 (if (eq interface 'outline)
7399 (car (org-get-location (current-buffer) org-goto-help))
7400 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7401 (org-refile-check-position pa)
7402 (nth 3 pa)))))
7403 (if selected-point
7404 (progn
7405 (org-mark-ring-push org-goto-start-pos)
7406 (goto-char selected-point)
7407 (if (or (outline-invisible-p) (org-invisible-p2))
7408 (org-show-context 'org-goto)))
7409 (message "Quit"))))
7411 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7412 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7413 (defvar org-goto-local-auto-isearch-map) ; defined below
7415 (defun org-get-location (buf help)
7416 "Let the user select a location in the Org-mode buffer BUF.
7417 This function uses a recursive edit. It returns the selected position
7418 or nil."
7419 (org-no-popups
7420 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7421 (isearch-hide-immediately nil)
7422 (isearch-search-fun-function
7423 (lambda () 'org-goto-local-search-headings))
7424 (org-goto-selected-point org-goto-exit-command))
7425 (save-excursion
7426 (save-window-excursion
7427 (delete-other-windows)
7428 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7429 (org-pop-to-buffer-same-window
7430 (condition-case nil
7431 (make-indirect-buffer (current-buffer) "*org-goto*")
7432 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7433 (with-output-to-temp-buffer "*Org Help*"
7434 (princ (format help (if org-goto-auto-isearch
7435 " Just type for auto-isearch."
7436 " n/p/f/b/u to navigate, q to quit."))))
7437 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7438 (setq buffer-read-only nil)
7439 (let ((org-startup-truncated t)
7440 (org-startup-folded nil)
7441 (org-startup-align-all-tables nil))
7442 (org-mode)
7443 (org-overview))
7444 (setq buffer-read-only t)
7445 (if (and (boundp 'org-goto-start-pos)
7446 (integer-or-marker-p org-goto-start-pos))
7447 (let ((org-show-hierarchy-above t)
7448 (org-show-siblings t)
7449 (org-show-following-heading t))
7450 (goto-char org-goto-start-pos)
7451 (and (outline-invisible-p) (org-show-context)))
7452 (goto-char (point-min)))
7453 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7454 (message "Select location and press RET")
7455 (use-local-map org-goto-map)
7456 (recursive-edit)))
7457 (kill-buffer "*org-goto*")
7458 (cons org-goto-selected-point org-goto-exit-command))))
7460 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7461 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7462 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7463 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7465 (defun org-goto-local-search-headings (string bound noerror)
7466 "Search and make sure that any matches are in headlines."
7467 (catch 'return
7468 (while (if isearch-forward
7469 (search-forward string bound noerror)
7470 (search-backward string bound noerror))
7471 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7472 (and (member :headline context)
7473 (not (member :tags context))))
7474 (throw 'return (point))))))
7476 (defun org-goto-local-auto-isearch ()
7477 "Start isearch."
7478 (interactive)
7479 (goto-char (point-min))
7480 (let ((keys (this-command-keys)))
7481 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7482 (isearch-mode t)
7483 (isearch-process-search-char (string-to-char keys)))))
7485 (defun org-goto-ret (&optional arg)
7486 "Finish `org-goto' by going to the new location."
7487 (interactive "P")
7488 (setq org-goto-selected-point (point)
7489 org-goto-exit-command 'return)
7490 (throw 'exit nil))
7492 (defun org-goto-left ()
7493 "Finish `org-goto' by going to the new location."
7494 (interactive)
7495 (if (org-at-heading-p)
7496 (progn
7497 (beginning-of-line 1)
7498 (setq org-goto-selected-point (point)
7499 org-goto-exit-command 'left)
7500 (throw 'exit nil))
7501 (user-error "Not on a heading")))
7503 (defun org-goto-right ()
7504 "Finish `org-goto' by going to the new location."
7505 (interactive)
7506 (if (org-at-heading-p)
7507 (progn
7508 (setq org-goto-selected-point (point)
7509 org-goto-exit-command 'right)
7510 (throw 'exit nil))
7511 (user-error "Not on a heading")))
7513 (defun org-goto-quit ()
7514 "Finish `org-goto' without cursor motion."
7515 (interactive)
7516 (setq org-goto-selected-point nil)
7517 (setq org-goto-exit-command 'quit)
7518 (throw 'exit nil))
7520 ;;; Indirect buffer display of subtrees
7522 (defvar org-indirect-dedicated-frame nil
7523 "This is the frame being used for indirect tree display.")
7524 (defvar org-last-indirect-buffer nil)
7526 (defun org-tree-to-indirect-buffer (&optional arg)
7527 "Create indirect buffer and narrow it to current subtree.
7528 With a numerical prefix ARG, go up to this level and then take that tree.
7529 If ARG is negative, go up that many levels.
7531 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7532 indirect buffer previously made with this command, to avoid proliferation of
7533 indirect buffers. However, when you call the command with a \
7534 \\[universal-argument] prefix, or
7535 when `org-indirect-buffer-display' is `new-frame', the last buffer
7536 is kept so that you can work with several indirect buffers at the same time.
7537 If `org-indirect-buffer-display' is `dedicated-frame', the \
7538 \\[universal-argument] prefix also
7539 requests that a new frame be made for the new buffer, so that the dedicated
7540 frame is not changed."
7541 (interactive "P")
7542 (let ((cbuf (current-buffer))
7543 (cwin (selected-window))
7544 (pos (point))
7545 beg end level heading ibuf)
7546 (save-excursion
7547 (org-back-to-heading t)
7548 (when (numberp arg)
7549 (setq level (org-outline-level))
7550 (if (< arg 0) (setq arg (+ level arg)))
7551 (while (> (setq level (org-outline-level)) arg)
7552 (org-up-heading-safe)))
7553 (setq beg (point)
7554 heading (org-get-heading))
7555 (org-end-of-subtree t t)
7556 (if (org-at-heading-p) (backward-char 1))
7557 (setq end (point)))
7558 (if (and (buffer-live-p org-last-indirect-buffer)
7559 (not (eq org-indirect-buffer-display 'new-frame))
7560 (not arg))
7561 (kill-buffer org-last-indirect-buffer))
7562 (setq ibuf (org-get-indirect-buffer cbuf heading)
7563 org-last-indirect-buffer ibuf)
7564 (cond
7565 ((or (eq org-indirect-buffer-display 'new-frame)
7566 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7567 (select-frame (make-frame))
7568 (delete-other-windows)
7569 (org-pop-to-buffer-same-window ibuf)
7570 (org-set-frame-title heading))
7571 ((eq org-indirect-buffer-display 'dedicated-frame)
7572 (raise-frame
7573 (select-frame (or (and org-indirect-dedicated-frame
7574 (frame-live-p org-indirect-dedicated-frame)
7575 org-indirect-dedicated-frame)
7576 (setq org-indirect-dedicated-frame (make-frame)))))
7577 (delete-other-windows)
7578 (org-pop-to-buffer-same-window ibuf)
7579 (org-set-frame-title (concat "Indirect: " heading)))
7580 ((eq org-indirect-buffer-display 'current-window)
7581 (org-pop-to-buffer-same-window ibuf))
7582 ((eq org-indirect-buffer-display 'other-window)
7583 (pop-to-buffer ibuf))
7584 (t (error "Invalid value")))
7585 (if (featurep 'xemacs)
7586 (save-excursion (org-mode) (turn-on-font-lock)))
7587 (narrow-to-region beg end)
7588 (show-all)
7589 (goto-char pos)
7590 (run-hook-with-args 'org-cycle-hook 'all)
7591 (and (window-live-p cwin) (select-window cwin))))
7593 (defun org-get-indirect-buffer (&optional buffer heading)
7594 (setq buffer (or buffer (current-buffer)))
7595 (let ((n 1) (base (buffer-name buffer)) bname)
7596 (while (buffer-live-p
7597 (get-buffer
7598 (setq bname
7599 (concat base "-"
7600 (if heading (concat heading "-" (number-to-string n))
7601 (number-to-string n))))))
7602 (setq n (1+ n)))
7603 (condition-case nil
7604 (make-indirect-buffer buffer bname 'clone)
7605 (error (make-indirect-buffer buffer bname)))))
7607 (defun org-set-frame-title (title)
7608 "Set the title of the current frame to the string TITLE."
7609 ;; FIXME: how to name a single frame in XEmacs???
7610 (unless (featurep 'xemacs)
7611 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7613 ;;;; Structure editing
7615 ;;; Inserting headlines
7617 (defun org-previous-line-empty-p (&optional next)
7618 "Is the previous line a blank line?
7619 When NEXT is non-nil, check the next line instead."
7620 (save-excursion
7621 (and (not (bobp))
7622 (or (beginning-of-line (if next 2 0)) t)
7623 (save-match-data
7624 (looking-at "[ \t]*$")))))
7626 (defun org-insert-heading (&optional arg invisible-ok)
7627 "Insert a new heading or item with same depth at point.
7628 If point is in a plain list and ARG is nil, create a new list item.
7629 With one universal prefix argument, insert a heading even in lists.
7630 With two universal prefix arguments, insert the heading at the end
7631 of the parent subtree.
7633 If point is at the beginning of a headline, insert a sibling before
7634 the current headline. If point is not at the beginning, split the line
7635 and create a new headline with the text in the current line after point
7636 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7638 If point is at the beginning of a normal line, turn this line into
7639 a heading.
7641 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7642 This is important for non-interactive uses of the command."
7643 (interactive "P")
7644 (if (org-called-interactively-p 'any) (org-reveal))
7645 (let ((itemp (org-in-item-p))
7646 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7647 (respect-content (or org-insert-heading-respect-content
7648 (equal arg '(4))))
7649 (initial-content "")
7650 (adjust-empty-lines t))
7652 (cond
7654 ((or (= (buffer-size) 0)
7655 (and (not (save-excursion
7656 (and (ignore-errors (org-back-to-heading invisible-ok))
7657 (org-at-heading-p))))
7658 (or arg (not itemp))))
7659 ;; At beginning of buffer or so high up that only a heading
7660 ;; makes sense.
7661 (insert
7662 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7663 (if (org-in-src-block-p) ",* " "* "))
7664 (run-hooks 'org-insert-heading-hook))
7666 ((and itemp (not (equal arg '(4))))
7667 ;; Insert an item
7668 (org-insert-item))
7671 ;; Maybe move at the end of the subtree
7672 (when (equal arg '(16))
7673 (org-up-heading-safe)
7674 (org-end-of-subtree t))
7675 ;; Insert a heading
7676 (save-restriction
7677 (widen)
7678 (let* ((level nil)
7679 (on-heading (org-at-heading-p))
7680 (empty-line-p (if on-heading
7681 (org-previous-line-empty-p)
7682 ;; We will decide later
7683 nil))
7684 ;; Get a level string to fall back on
7685 (fix-level
7686 (save-excursion
7687 (org-back-to-heading t)
7688 (if (org-previous-line-empty-p) (setq empty-line-p t))
7689 (looking-at org-outline-regexp)
7690 (make-string (1- (length (match-string 0))) ?*)))
7691 (stars
7692 (save-excursion
7693 (condition-case nil
7694 (progn
7695 (org-back-to-heading invisible-ok)
7696 (when (and (not on-heading)
7697 (featurep 'org-inlinetask)
7698 (integerp org-inlinetask-min-level)
7699 (>= (length (match-string 0))
7700 org-inlinetask-min-level))
7701 ;; Find a heading level before the inline task
7702 (while (and (setq level (org-up-heading-safe))
7703 (>= level org-inlinetask-min-level)))
7704 (if (org-at-heading-p)
7705 (org-back-to-heading invisible-ok)
7706 (error "This should not happen")))
7707 (unless (and (save-excursion
7708 (save-match-data
7709 (org-backward-heading-same-level
7710 1 invisible-ok))
7711 (= (point) (match-beginning 0)))
7712 (not (org-previous-line-empty-p t)))
7713 (setq empty-line-p (or empty-line-p
7714 (org-previous-line-empty-p))))
7715 (match-string 0))
7716 (error (or fix-level "* ")))))
7717 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7718 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7719 pos hide-previous previous-pos)
7721 ;; If we insert after content, move there and clean up whitespace
7722 (when respect-content
7723 (org-end-of-subtree nil t)
7724 (skip-chars-backward " \r\n")
7725 (and (not (looking-back "^\*+"))
7726 (looking-at "[ \t]+") (replace-match ""))
7727 (unless (eobp) (forward-char 1))
7728 (when (looking-at "^\\*")
7729 (unless (bobp) (backward-char 1))
7730 (insert "\n")))
7732 ;; If we are splitting, grab the text that should be moved to the new headline
7733 (when may-split
7734 (if (org-on-heading-p)
7735 ;; This is a heading, we split intelligently (keeping tags)
7736 (let ((pos (point)))
7737 (goto-char (point-at-bol))
7738 (unless (looking-at org-complex-heading-regexp)
7739 (error "This should not happen"))
7740 (when (and (match-beginning 4)
7741 (> pos (match-beginning 4))
7742 (< pos (match-end 4)))
7743 (setq initial-content (buffer-substring pos (match-end 4)))
7744 (goto-char pos)
7745 (delete-region (point) (match-end 4))
7746 (if (looking-at "[ \t]*$")
7747 (replace-match "")
7748 (insert (make-string (length initial-content) ?\ )))
7749 (setq initial-content (org-trim initial-content)))
7750 (goto-char pos))
7751 ;; a normal line
7752 (unless (bolp)
7753 (setq initial-content (buffer-substring (point) (point-at-eol)))
7754 (delete-region (point) (point-at-eol))
7755 (setq initial-content (org-trim initial-content)))))
7757 ;; If we are at the beginning of the line, insert before it. Else after
7758 (cond
7759 ((and (bolp) (looking-at "[ \t]*$")))
7760 ((and (bolp) (not (looking-at "[ \t]*$")))
7761 (open-line 1))
7763 (goto-char (point-at-eol))
7764 (insert "\n")))
7766 ;; Insert the new heading
7767 (insert stars)
7768 (just-one-space)
7769 (insert initial-content)
7770 (when adjust-empty-lines
7771 (if (or (not blank)
7772 (and blank (not (org-previous-line-empty-p))))
7773 (org-N-empty-lines-before-current (if blank 1 0))))
7774 (run-hooks 'org-insert-heading-hook)))))))
7776 (defun org-N-empty-lines-before-current (N)
7777 "Make the number of empty lines before current exactly N.
7778 So this will delete or add empty lines."
7779 (save-excursion
7780 (goto-char (point-at-bol))
7781 (if (looking-back "\\s-+" nil 'greedy)
7782 (replace-match ""))
7783 (or (bobp) (insert "\n"))
7784 (while (> N 0)
7785 (insert "\n")
7786 (setq N (1- N)))))
7788 (defun org-get-heading (&optional no-tags no-todo)
7789 "Return the heading of the current entry, without the stars.
7790 When NO-TAGS is non-nil, don't include tags.
7791 When NO-TODO is non-nil, don't include TODO keywords."
7792 (save-excursion
7793 (org-back-to-heading t)
7794 (cond
7795 ((and no-tags no-todo)
7796 (looking-at org-complex-heading-regexp)
7797 (match-string 4))
7798 (no-tags
7799 (looking-at (concat org-outline-regexp
7800 "\\(.*?\\)"
7801 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7802 (match-string 1))
7803 (no-todo
7804 (looking-at org-todo-line-regexp)
7805 (match-string 3))
7806 (t (looking-at org-heading-regexp)
7807 (match-string 2)))))
7809 (defvar orgstruct-mode) ; defined below
7811 (defun org-heading-components ()
7812 "Return the components of the current heading.
7813 This is a list with the following elements:
7814 - the level as an integer
7815 - the reduced level, different if `org-odd-levels-only' is set.
7816 - the TODO keyword, or nil
7817 - the priority character, like ?A, or nil if no priority is given
7818 - the headline text itself, or the tags string if no headline text
7819 - the tags string, or nil."
7820 (save-excursion
7821 (org-back-to-heading t)
7822 (if (let (case-fold-search)
7823 (looking-at
7824 (if orgstruct-mode
7825 org-heading-regexp
7826 org-complex-heading-regexp)))
7827 (if orgstruct-mode
7828 (list (length (match-string 1))
7829 (org-reduced-level (length (match-string 1)))
7832 (match-string 2)
7833 nil)
7834 (list (length (match-string 1))
7835 (org-reduced-level (length (match-string 1)))
7836 (org-match-string-no-properties 2)
7837 (and (match-end 3) (aref (match-string 3) 2))
7838 (org-match-string-no-properties 4)
7839 (org-match-string-no-properties 5))))))
7841 (defun org-get-entry ()
7842 "Get the entry text, after heading, entire subtree."
7843 (save-excursion
7844 (org-back-to-heading t)
7845 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7847 (defun org-insert-heading-after-current ()
7848 "Insert a new heading with same level as current, after current subtree."
7849 (interactive)
7850 (org-back-to-heading)
7851 (org-insert-heading)
7852 (org-move-subtree-down)
7853 (end-of-line 1))
7855 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7856 "Insert heading with `org-insert-heading-respect-content' set to t."
7857 (interactive "P")
7858 (let ((org-insert-heading-respect-content t))
7859 (org-insert-heading '(4) invisible-ok)))
7861 (defun org-insert-todo-heading-respect-content (&optional force-state)
7862 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7863 (interactive "P")
7864 (let ((org-insert-heading-respect-content t))
7865 (org-insert-todo-heading force-state '(4))))
7867 (defun org-insert-todo-heading (arg &optional force-heading)
7868 "Insert a new heading with the same level and TODO state as current heading.
7869 If the heading has no TODO state, or if the state is DONE, use the first
7870 state (TODO by default). Also with one prefix arg, force first state. With
7871 two prefix args, force inserting at the end of the parent subtree."
7872 (interactive "P")
7873 (when (or force-heading (not (org-insert-item 'checkbox)))
7874 (org-insert-heading (or (and (equal arg '(16)) '(16))
7875 force-heading))
7876 (save-excursion
7877 (org-back-to-heading)
7878 (outline-previous-heading)
7879 (looking-at org-todo-line-regexp))
7880 (let*
7881 ((new-mark-x
7882 (if (or (equal arg '(4))
7883 (not (match-beginning 2))
7884 (member (match-string 2) org-done-keywords))
7885 (car org-todo-keywords-1)
7886 (match-string 2)))
7887 (new-mark
7889 (run-hook-with-args-until-success
7890 'org-todo-get-default-hook new-mark-x nil)
7891 new-mark-x)))
7892 (beginning-of-line 1)
7893 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7894 (if org-treat-insert-todo-heading-as-state-change
7895 (org-todo new-mark)
7896 (insert new-mark " "))))
7897 (when org-provide-todo-statistics
7898 (org-update-parent-todo-statistics))))
7900 (defun org-insert-subheading (arg)
7901 "Insert a new subheading and demote it.
7902 Works for outline headings and for plain lists alike."
7903 (interactive "P")
7904 (org-insert-heading arg)
7905 (cond
7906 ((org-at-heading-p) (org-do-demote))
7907 ((org-at-item-p) (org-indent-item))))
7909 (defun org-insert-todo-subheading (arg)
7910 "Insert a new subheading with TODO keyword or checkbox and demote it.
7911 Works for outline headings and for plain lists alike."
7912 (interactive "P")
7913 (org-insert-todo-heading arg)
7914 (cond
7915 ((org-at-heading-p) (org-do-demote))
7916 ((org-at-item-p) (org-indent-item))))
7918 ;;; Promotion and Demotion
7920 (defvar org-after-demote-entry-hook nil
7921 "Hook run after an entry has been demoted.
7922 The cursor will be at the beginning of the entry.
7923 When a subtree is being demoted, the hook will be called for each node.")
7925 (defvar org-after-promote-entry-hook nil
7926 "Hook run after an entry has been promoted.
7927 The cursor will be at the beginning of the entry.
7928 When a subtree is being promoted, the hook will be called for each node.")
7930 (defun org-promote-subtree ()
7931 "Promote the entire subtree.
7932 See also `org-promote'."
7933 (interactive)
7934 (save-excursion
7935 (org-with-limited-levels (org-map-tree 'org-promote)))
7936 (org-fix-position-after-promote))
7938 (defun org-demote-subtree ()
7939 "Demote the entire subtree. See `org-demote'.
7940 See also `org-promote'."
7941 (interactive)
7942 (save-excursion
7943 (org-with-limited-levels (org-map-tree 'org-demote)))
7944 (org-fix-position-after-promote))
7947 (defun org-do-promote ()
7948 "Promote the current heading higher up the tree.
7949 If the region is active in `transient-mark-mode', promote all headings
7950 in the region."
7951 (interactive)
7952 (save-excursion
7953 (if (org-region-active-p)
7954 (org-map-region 'org-promote (region-beginning) (region-end))
7955 (org-promote)))
7956 (org-fix-position-after-promote))
7958 (defun org-do-demote ()
7959 "Demote the current heading lower down the tree.
7960 If the region is active in `transient-mark-mode', demote all headings
7961 in the region."
7962 (interactive)
7963 (save-excursion
7964 (if (org-region-active-p)
7965 (org-map-region 'org-demote (region-beginning) (region-end))
7966 (org-demote)))
7967 (org-fix-position-after-promote))
7969 (defun org-fix-position-after-promote ()
7970 "Make sure that after pro/demotion cursor position is right."
7971 (let ((pos (point)))
7972 (when (save-excursion
7973 (beginning-of-line 1)
7974 (looking-at org-todo-line-regexp)
7975 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7976 (cond ((eobp) (insert " "))
7977 ((eolp) (insert " "))
7978 ((equal (char-after) ?\ ) (forward-char 1))))))
7980 (defun org-current-level ()
7981 "Return the level of the current entry, or nil if before the first headline.
7982 The level is the number of stars at the beginning of the headline."
7983 (save-excursion
7984 (org-with-limited-levels
7985 (if (ignore-errors (org-back-to-heading t))
7986 (funcall outline-level)))))
7988 (defun org-get-previous-line-level ()
7989 "Return the outline depth of the last headline before the current line.
7990 Returns 0 for the first headline in the buffer, and nil if before the
7991 first headline."
7992 (and (org-current-level)
7993 (or (and (/= (line-beginning-position) (point-min))
7994 (save-excursion (beginning-of-line 0) (org-current-level)))
7995 0)))
7997 (defun org-reduced-level (l)
7998 "Compute the effective level of a heading.
7999 This takes into account the setting of `org-odd-levels-only'."
8000 (cond
8001 ((zerop l) 0)
8002 (org-odd-levels-only (1+ (floor (/ l 2))))
8003 (t l)))
8005 (defun org-level-increment ()
8006 "Return the number of stars that will be added or removed at a
8007 time to headlines when structure editing, based on the value of
8008 `org-odd-levels-only'."
8009 (if org-odd-levels-only 2 1))
8011 (defun org-get-valid-level (level &optional change)
8012 "Rectify a level change under the influence of `org-odd-levels-only'
8013 LEVEL is a current level, CHANGE is by how much the level should be
8014 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8015 even level numbers will become the next higher odd number."
8016 (if org-odd-levels-only
8017 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8018 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8019 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8020 (max 1 (+ level (or change 0)))))
8022 (if (boundp 'define-obsolete-function-alias)
8023 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8024 (define-obsolete-function-alias 'org-get-legal-level
8025 'org-get-valid-level)
8026 (define-obsolete-function-alias 'org-get-legal-level
8027 'org-get-valid-level "23.1")))
8029 (defun org-promote ()
8030 "Promote the current heading higher up the tree.
8031 If the region is active in `transient-mark-mode', promote all headings
8032 in the region."
8033 (org-back-to-heading t)
8034 (let* ((level (save-match-data (funcall outline-level)))
8035 (after-change-functions (remove 'flyspell-after-change-function
8036 after-change-functions))
8037 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8038 (diff (abs (- level (length up-head) -1))))
8039 (cond ((and (= level 1) org-called-with-limited-levels
8040 org-allow-promoting-top-level-subtree)
8041 (replace-match "# " nil t))
8042 ((= level 1)
8043 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8044 (t (replace-match up-head nil t)))
8045 ;; Fixup tag positioning
8046 (unless (= level 1)
8047 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8048 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8049 (run-hooks 'org-after-promote-entry-hook)))
8051 (defun org-demote ()
8052 "Demote the current heading lower down the tree.
8053 If the region is active in `transient-mark-mode', demote all headings
8054 in the region."
8055 (org-back-to-heading t)
8056 (let* ((level (save-match-data (funcall outline-level)))
8057 (after-change-functions (remove 'flyspell-after-change-function
8058 after-change-functions))
8059 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8060 (diff (abs (- level (length down-head) -1))))
8061 (replace-match down-head nil t)
8062 ;; Fixup tag positioning
8063 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8064 (if org-adapt-indentation (org-fixup-indentation diff))
8065 (run-hooks 'org-after-demote-entry-hook)))
8067 (defun org-cycle-level ()
8068 "Cycle the level of an empty headline through possible states.
8069 This goes first to child, then to parent, level, then up the hierarchy.
8070 After top level, it switches back to sibling level."
8071 (interactive)
8072 (let ((org-adapt-indentation nil))
8073 (when (org-point-at-end-of-empty-headline)
8074 (setq this-command 'org-cycle-level) ; Only needed for caching
8075 (let ((cur-level (org-current-level))
8076 (prev-level (org-get-previous-line-level)))
8077 (cond
8078 ;; If first headline in file, promote to top-level.
8079 ((= prev-level 0)
8080 (loop repeat (/ (- cur-level 1) (org-level-increment))
8081 do (org-do-promote)))
8082 ;; If same level as prev, demote one.
8083 ((= prev-level cur-level)
8084 (org-do-demote))
8085 ;; If parent is top-level, promote to top level if not already.
8086 ((= prev-level 1)
8087 (loop repeat (/ (- cur-level 1) (org-level-increment))
8088 do (org-do-promote)))
8089 ;; If top-level, return to prev-level.
8090 ((= cur-level 1)
8091 (loop repeat (/ (- prev-level 1) (org-level-increment))
8092 do (org-do-demote)))
8093 ;; If less than prev-level, promote one.
8094 ((< cur-level prev-level)
8095 (org-do-promote))
8096 ;; If deeper than prev-level, promote until higher than
8097 ;; prev-level.
8098 ((> cur-level prev-level)
8099 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8100 do (org-do-promote))))
8101 t))))
8103 (defun org-map-tree (fun)
8104 "Call FUN for every heading underneath the current one."
8105 (org-back-to-heading)
8106 (let ((level (funcall outline-level)))
8107 (save-excursion
8108 (funcall fun)
8109 (while (and (progn
8110 (outline-next-heading)
8111 (> (funcall outline-level) level))
8112 (not (eobp)))
8113 (funcall fun)))))
8115 (defun org-map-region (fun beg end)
8116 "Call FUN for every heading between BEG and END."
8117 (let ((org-ignore-region t))
8118 (save-excursion
8119 (setq end (copy-marker end))
8120 (goto-char beg)
8121 (if (and (re-search-forward org-outline-regexp-bol nil t)
8122 (< (point) end))
8123 (funcall fun))
8124 (while (and (progn
8125 (outline-next-heading)
8126 (< (point) end))
8127 (not (eobp)))
8128 (funcall fun)))))
8130 (defvar org-property-end-re) ; silence byte-compiler
8131 (defun org-fixup-indentation (diff)
8132 "Change the indentation in the current entry by DIFF.
8133 However, if any line in the current entry has no indentation, or if it
8134 would end up with no indentation after the change, nothing at all is done."
8135 (save-excursion
8136 (let ((end (save-excursion (outline-next-heading)
8137 (point-marker)))
8138 (prohibit (if (> diff 0)
8139 "^\\S-"
8140 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8141 col)
8142 (unless (save-excursion (end-of-line 1)
8143 (re-search-forward prohibit end t))
8144 (while (and (< (point) end)
8145 (re-search-forward "^[ \t]+" end t))
8146 (goto-char (match-end 0))
8147 (setq col (current-column))
8148 (if (< diff 0) (replace-match ""))
8149 (org-indent-to-column (+ diff col))))
8150 (move-marker end nil))))
8152 (defun org-convert-to-odd-levels ()
8153 "Convert an org-mode file with all levels allowed to one with odd levels.
8154 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8155 level 5 etc."
8156 (interactive)
8157 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8158 (let ((outline-level 'org-outline-level)
8159 (org-odd-levels-only nil) n)
8160 (save-excursion
8161 (goto-char (point-min))
8162 (while (re-search-forward "^\\*\\*+ " nil t)
8163 (setq n (- (length (match-string 0)) 2))
8164 (while (>= (setq n (1- n)) 0)
8165 (org-demote))
8166 (end-of-line 1))))))
8168 (defun org-convert-to-oddeven-levels ()
8169 "Convert an org-mode file with only odd levels to one with odd/even levels.
8170 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8171 file contains a section with an even level, conversion would
8172 destroy the structure of the file. An error is signaled in this
8173 case."
8174 (interactive)
8175 (goto-char (point-min))
8176 ;; First check if there are no even levels
8177 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8178 (org-show-context t)
8179 (error "Not all levels are odd in this file. Conversion not possible"))
8180 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8181 (let ((outline-regexp org-outline-regexp)
8182 (outline-level 'org-outline-level)
8183 (org-odd-levels-only nil) n)
8184 (save-excursion
8185 (goto-char (point-min))
8186 (while (re-search-forward "^\\*\\*+ " nil t)
8187 (setq n (/ (1- (length (match-string 0))) 2))
8188 (while (>= (setq n (1- n)) 0)
8189 (org-promote))
8190 (end-of-line 1))))))
8192 (defun org-tr-level (n)
8193 "Make N odd if required."
8194 (if org-odd-levels-only (1+ (/ n 2)) n))
8196 ;;; Vertical tree motion, cutting and pasting of subtrees
8198 (defun org-move-subtree-up (&optional arg)
8199 "Move the current subtree up past ARG headlines of the same level."
8200 (interactive "p")
8201 (org-move-subtree-down (- (prefix-numeric-value arg))))
8203 (defun org-move-subtree-down (&optional arg)
8204 "Move the current subtree down past ARG headlines of the same level."
8205 (interactive "p")
8206 (setq arg (prefix-numeric-value arg))
8207 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8208 'org-get-last-sibling))
8209 (ins-point (make-marker))
8210 (cnt (abs arg))
8211 (col (current-column))
8212 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8213 ;; Select the tree
8214 (org-back-to-heading)
8215 (setq beg0 (point))
8216 (save-excursion
8217 (setq ne-beg (org-back-over-empty-lines))
8218 (setq beg (point)))
8219 (save-match-data
8220 (save-excursion (outline-end-of-heading)
8221 (setq folded (outline-invisible-p)))
8222 (outline-end-of-subtree))
8223 (outline-next-heading)
8224 (setq ne-end (org-back-over-empty-lines))
8225 (setq end (point))
8226 (goto-char beg0)
8227 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8228 ;; include less whitespace
8229 (save-excursion
8230 (goto-char beg)
8231 (forward-line (- ne-beg ne-end))
8232 (setq beg (point))))
8233 ;; Find insertion point, with error handling
8234 (while (> cnt 0)
8235 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8236 (progn (goto-char beg0)
8237 (user-error "Cannot move past superior level or buffer limit")))
8238 (setq cnt (1- cnt)))
8239 (if (> arg 0)
8240 ;; Moving forward - still need to move over subtree
8241 (progn (org-end-of-subtree t t)
8242 (save-excursion
8243 (org-back-over-empty-lines)
8244 (or (bolp) (newline)))))
8245 (setq ne-ins (org-back-over-empty-lines))
8246 (move-marker ins-point (point))
8247 (setq txt (buffer-substring beg end))
8248 (org-save-markers-in-region beg end)
8249 (delete-region beg end)
8250 (org-remove-empty-overlays-at beg)
8251 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8252 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8253 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8254 (let ((bbb (point)))
8255 (insert-before-markers txt)
8256 (org-reinstall-markers-in-region bbb)
8257 (move-marker ins-point bbb))
8258 (or (bolp) (insert "\n"))
8259 (setq ins-end (point))
8260 (goto-char ins-point)
8261 (org-skip-whitespace)
8262 (when (and (< arg 0)
8263 (org-first-sibling-p)
8264 (> ne-ins ne-beg))
8265 ;; Move whitespace back to beginning
8266 (save-excursion
8267 (goto-char ins-end)
8268 (let ((kill-whole-line t))
8269 (kill-line (- ne-ins ne-beg)) (point)))
8270 (insert (make-string (- ne-ins ne-beg) ?\n)))
8271 (move-marker ins-point nil)
8272 (if folded
8273 (hide-subtree)
8274 (org-show-entry)
8275 (show-children)
8276 (org-cycle-hide-drawers 'children))
8277 (org-clean-visibility-after-subtree-move)
8278 ;; move back to the initial column we were at
8279 (move-to-column col)))
8281 (defvar org-subtree-clip ""
8282 "Clipboard for cut and paste of subtrees.
8283 This is actually only a copy of the kill, because we use the normal kill
8284 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8286 (defvar org-subtree-clip-folded nil
8287 "Was the last copied subtree folded?
8288 This is used to fold the tree back after pasting.")
8290 (defun org-cut-subtree (&optional n)
8291 "Cut the current subtree into the clipboard.
8292 With prefix arg N, cut this many sequential subtrees.
8293 This is a short-hand for marking the subtree and then cutting it."
8294 (interactive "p")
8295 (org-copy-subtree n 'cut))
8297 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8298 "Copy the current subtree it in the clipboard.
8299 With prefix arg N, copy this many sequential subtrees.
8300 This is a short-hand for marking the subtree and then copying it.
8301 If CUT is non-nil, actually cut the subtree.
8302 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8303 of some markers in the region, even if CUT is non-nil. This is
8304 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8305 (interactive "p")
8306 (let (beg end folded (beg0 (point)))
8307 (if (org-called-interactively-p 'any)
8308 (org-back-to-heading nil) ; take what looks like a subtree
8309 (org-back-to-heading t)) ; take what is really there
8310 (setq beg (point))
8311 (skip-chars-forward " \t\r\n")
8312 (save-match-data
8313 (if nosubtrees
8314 (outline-next-heading)
8315 (save-excursion (outline-end-of-heading)
8316 (setq folded (outline-invisible-p)))
8317 (condition-case nil
8318 (org-forward-heading-same-level (1- n) t)
8319 (error nil))
8320 (org-end-of-subtree t t)))
8321 (setq end (point))
8322 (goto-char beg0)
8323 (when (> end beg)
8324 (setq org-subtree-clip-folded folded)
8325 (when (or cut force-store-markers)
8326 (org-save-markers-in-region beg end))
8327 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8328 (setq org-subtree-clip (current-kill 0))
8329 (message "%s: Subtree(s) with %d characters"
8330 (if cut "Cut" "Copied")
8331 (length org-subtree-clip)))))
8333 (defun org-paste-subtree (&optional level tree for-yank)
8334 "Paste the clipboard as a subtree, with modification of headline level.
8335 The entire subtree is promoted or demoted in order to match a new headline
8336 level.
8338 If the cursor is at the beginning of a headline, the same level as
8339 that headline is used to paste the tree.
8341 If not, the new level is derived from the *visible* headings
8342 before and after the insertion point, and taken to be the inferior headline
8343 level of the two. So if the previous visible heading is level 3 and the
8344 next is level 4 (or vice versa), level 4 will be used for insertion.
8345 This makes sure that the subtree remains an independent subtree and does
8346 not swallow low level entries.
8348 You can also force a different level, either by using a numeric prefix
8349 argument, or by inserting the heading marker by hand. For example, if the
8350 cursor is after \"*****\", then the tree will be shifted to level 5.
8352 If optional TREE is given, use this text instead of the kill ring.
8354 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8355 move back over whitespace before inserting, and move point to the end of
8356 the inserted text when done."
8357 (interactive "P")
8358 (setq tree (or tree (and kill-ring (current-kill 0))))
8359 (unless (org-kill-is-subtree-p tree)
8360 (user-error "%s"
8361 (substitute-command-keys
8362 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8363 (org-with-limited-levels
8364 (let* ((visp (not (outline-invisible-p)))
8365 (txt tree)
8366 (^re_ "\\(\\*+\\)[ \t]*")
8367 (old-level (if (string-match org-outline-regexp-bol txt)
8368 (- (match-end 0) (match-beginning 0) 1)
8369 -1))
8370 (force-level (cond (level (prefix-numeric-value level))
8371 ((and (looking-at "[ \t]*$")
8372 (string-match
8373 "^\\*+$" (buffer-substring
8374 (point-at-bol) (point))))
8375 (- (match-end 1) (match-beginning 1)))
8376 ((and (bolp)
8377 (looking-at org-outline-regexp))
8378 (- (match-end 0) (point) 1))))
8379 (previous-level (save-excursion
8380 (condition-case nil
8381 (progn
8382 (outline-previous-visible-heading 1)
8383 (if (looking-at ^re_)
8384 (- (match-end 0) (match-beginning 0) 1)
8386 (error 1))))
8387 (next-level (save-excursion
8388 (condition-case nil
8389 (progn
8390 (or (looking-at org-outline-regexp)
8391 (outline-next-visible-heading 1))
8392 (if (looking-at ^re_)
8393 (- (match-end 0) (match-beginning 0) 1)
8395 (error 1))))
8396 (new-level (or force-level (max previous-level next-level)))
8397 (shift (if (or (= old-level -1)
8398 (= new-level -1)
8399 (= old-level new-level))
8401 (- new-level old-level)))
8402 (delta (if (> shift 0) -1 1))
8403 (func (if (> shift 0) 'org-demote 'org-promote))
8404 (org-odd-levels-only nil)
8405 beg end newend)
8406 ;; Remove the forced level indicator
8407 (if force-level
8408 (delete-region (point-at-bol) (point)))
8409 ;; Paste
8410 (beginning-of-line (if (bolp) 1 2))
8411 (setq beg (point))
8412 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8413 (insert-before-markers txt)
8414 (unless (string-match "\n\\'" txt) (insert "\n"))
8415 (setq newend (point))
8416 (org-reinstall-markers-in-region beg)
8417 (setq end (point))
8418 (goto-char beg)
8419 (skip-chars-forward " \t\n\r")
8420 (setq beg (point))
8421 (if (and (outline-invisible-p) visp)
8422 (save-excursion (outline-show-heading)))
8423 ;; Shift if necessary
8424 (unless (= shift 0)
8425 (save-restriction
8426 (narrow-to-region beg end)
8427 (while (not (= shift 0))
8428 (org-map-region func (point-min) (point-max))
8429 (setq shift (+ delta shift)))
8430 (goto-char (point-min))
8431 (setq newend (point-max))))
8432 (when (or (org-called-interactively-p 'interactive) for-yank)
8433 (message "Clipboard pasted as level %d subtree" new-level))
8434 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8435 kill-ring
8436 (eq org-subtree-clip (current-kill 0))
8437 org-subtree-clip-folded)
8438 ;; The tree was folded before it was killed/copied
8439 (hide-subtree))
8440 (and for-yank (goto-char newend)))))
8442 (defun org-kill-is-subtree-p (&optional txt)
8443 "Check if the current kill is an outline subtree, or a set of trees.
8444 Returns nil if kill does not start with a headline, or if the first
8445 headline level is not the largest headline level in the tree.
8446 So this will actually accept several entries of equal levels as well,
8447 which is OK for `org-paste-subtree'.
8448 If optional TXT is given, check this string instead of the current kill."
8449 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8450 (re (org-get-limited-outline-regexp))
8451 (^re (concat "^" re))
8452 (start-level (and kill
8453 (string-match
8454 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8455 kill)
8456 (- (match-end 2) (match-beginning 2) 1)))
8457 (start (1+ (or (match-beginning 2) -1))))
8458 (if (not start-level)
8459 (progn
8460 nil) ;; does not even start with a heading
8461 (catch 'exit
8462 (while (setq start (string-match ^re kill (1+ start)))
8463 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8464 (throw 'exit nil)))
8465 t))))
8467 (defvar org-markers-to-move nil
8468 "Markers that should be moved with a cut-and-paste operation.
8469 Those markers are stored together with their positions relative to
8470 the start of the region.")
8472 (defun org-save-markers-in-region (beg end)
8473 "Check markers in region.
8474 If these markers are between BEG and END, record their position relative
8475 to BEG, so that after moving the block of text, we can put the markers back
8476 into place.
8477 This function gets called just before an entry or tree gets cut from the
8478 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8479 called immediately, to move the markers with the entries."
8480 (setq org-markers-to-move nil)
8481 (when (featurep 'org-clock)
8482 (org-clock-save-markers-for-cut-and-paste beg end))
8483 (when (featurep 'org-agenda)
8484 (org-agenda-save-markers-for-cut-and-paste beg end)))
8486 (defun org-check-and-save-marker (marker beg end)
8487 "Check if MARKER is between BEG and END.
8488 If yes, remember the marker and the distance to BEG."
8489 (when (and (marker-buffer marker)
8490 (equal (marker-buffer marker) (current-buffer)))
8491 (if (and (>= marker beg) (< marker end))
8492 (push (cons marker (- marker beg)) org-markers-to-move))))
8494 (defun org-reinstall-markers-in-region (beg)
8495 "Move all remembered markers to their position relative to BEG."
8496 (mapc (lambda (x)
8497 (move-marker (car x) (+ beg (cdr x))))
8498 org-markers-to-move)
8499 (setq org-markers-to-move nil))
8501 (defun org-narrow-to-subtree ()
8502 "Narrow buffer to the current subtree."
8503 (interactive)
8504 (save-excursion
8505 (save-match-data
8506 (org-with-limited-levels
8507 (narrow-to-region
8508 (progn (org-back-to-heading t) (point))
8509 (progn (org-end-of-subtree t t)
8510 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8511 (point)))))))
8513 (defun org-narrow-to-block ()
8514 "Narrow buffer to the current block."
8515 (interactive)
8516 (let* ((case-fold-search t)
8517 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8518 "^[ \t]*#\\+end_.*")))
8519 (if blockp
8520 (narrow-to-region (car blockp) (cdr blockp))
8521 (user-error "Not in a block"))))
8523 (eval-when-compile
8524 (defvar org-property-drawer-re))
8526 (defvar org-property-start-re) ;; defined below
8527 (defun org-clone-subtree-with-time-shift (n &optional shift)
8528 "Clone the task (subtree) at point N times.
8529 The clones will be inserted as siblings.
8531 In interactive use, the user will be prompted for the number of
8532 clones to be produced. If the entry has a timestamp, the user
8533 will also be prompted for a time shift, which may be a repeater
8534 as used in time stamps, for example `+3d'. To disable this,
8535 you can call the function with a universal prefix argument.
8537 When a valid repeater is given and the entry contains any time
8538 stamps, the clones will become a sequence in time, with time
8539 stamps in the subtree shifted for each clone produced. If SHIFT
8540 is nil or the empty string, time stamps will be left alone. The
8541 ID property of the original subtree is removed.
8543 If the original subtree did contain time stamps with a repeater,
8544 the following will happen:
8545 - the repeater will be removed in each clone
8546 - an additional clone will be produced, with the current, unshifted
8547 date(s) in the entry.
8548 - the original entry will be placed *after* all the clones, with
8549 repeater intact.
8550 - the start days in the repeater in the original entry will be shifted
8551 to past the last clone.
8552 In this way you can spell out a number of instances of a repeating task,
8553 and still retain the repeater to cover future instances of the task."
8554 (interactive "nNumber of clones to produce: ")
8555 (let ((shift
8556 (or shift
8557 (if (and (not (equal current-prefix-arg '(4)))
8558 (save-excursion
8559 (re-search-forward org-ts-regexp-both
8560 (save-excursion
8561 (org-end-of-subtree t)
8562 (point)) t)))
8563 (read-from-minibuffer
8564 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8565 ""))) ;; No time shift
8566 (n-no-remove -1)
8567 (drawer-re org-drawer-regexp)
8568 beg end template task idprop
8569 shift-n shift-what doshift nmin nmax)
8570 (if (not (and (integerp n) (> n 0)))
8571 (error "Invalid number of replications %s" n))
8572 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8573 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8574 shift)))
8575 (error "Invalid shift specification %s" shift))
8576 (when doshift
8577 (setq shift-n (string-to-number (match-string 1 shift))
8578 shift-what (cdr (assoc (match-string 2 shift)
8579 '(("d" . day) ("w" . week)
8580 ("m" . month) ("y" . year))))))
8581 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8582 (setq nmin 1 nmax n)
8583 (org-back-to-heading t)
8584 (setq beg (point))
8585 (setq idprop (org-entry-get nil "ID"))
8586 (org-end-of-subtree t t)
8587 (or (bolp) (insert "\n"))
8588 (setq end (point))
8589 (setq template (buffer-substring beg end))
8590 (when (and doshift
8591 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8592 (delete-region beg end)
8593 (setq end beg)
8594 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8595 (goto-char end)
8596 (loop for n from nmin to nmax do
8597 ;; prepare clone
8598 (with-temp-buffer
8599 (insert template)
8600 (org-mode)
8601 (goto-char (point-min))
8602 (org-show-subtree)
8603 (and idprop (if org-clone-delete-id
8604 (org-entry-delete nil "ID")
8605 (org-id-get-create t)))
8606 (unless (= n 0)
8607 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8608 (kill-whole-line))
8609 (goto-char (point-min))
8610 (while (re-search-forward drawer-re nil t)
8611 (org-remove-empty-drawer-at (point))))
8612 (goto-char (point-min))
8613 (when doshift
8614 (while (re-search-forward org-ts-regexp-both nil t)
8615 (org-timestamp-change (* n shift-n) shift-what))
8616 (unless (= n n-no-remove)
8617 (goto-char (point-min))
8618 (while (re-search-forward org-ts-regexp nil t)
8619 (save-excursion
8620 (goto-char (match-beginning 0))
8621 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8622 (delete-region (match-beginning 1) (match-end 1)))))))
8623 (setq task (buffer-string)))
8624 (insert task))
8625 (goto-char beg)))
8627 ;;; Outline Sorting
8629 (defun org-sort (with-case)
8630 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8631 Optional argument WITH-CASE means sort case-sensitively."
8632 (interactive "P")
8633 (cond
8634 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8635 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8637 (org-call-with-arg 'org-sort-entries with-case))))
8639 (defun org-sort-remove-invisible (s)
8640 "Remove invisible links from string S."
8641 (remove-text-properties 0 (length s) org-rm-props s)
8642 (while (string-match org-bracket-link-regexp s)
8643 (setq s (replace-match (if (match-end 2)
8644 (match-string 3 s)
8645 (match-string 1 s)) t t s)))
8646 (let ((st (format " %s " s)))
8647 (while (string-match org-emph-re st)
8648 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8649 (setq s (substring st 1 -1)))
8652 (defvar org-priority-regexp) ; defined later in the file
8654 (defvar org-after-sorting-entries-or-items-hook nil
8655 "Hook that is run after a bunch of entries or items have been sorted.
8656 When children are sorted, the cursor is in the parent line when this
8657 hook gets called. When a region or a plain list is sorted, the cursor
8658 will be in the first entry of the sorted region/list.")
8660 (defun org-sort-entries
8661 (&optional with-case sorting-type getkey-func compare-func property)
8662 "Sort entries on a certain level of an outline tree.
8663 If there is an active region, the entries in the region are sorted.
8664 Else, if the cursor is before the first entry, sort the top-level items.
8665 Else, the children of the entry at point are sorted.
8667 Sorting can be alphabetically, numerically, by date/time as given by
8668 a time stamp, by a property, by priority order, or by a custom function.
8670 The command prompts for the sorting type unless it has been given to the
8671 function through the SORTING-TYPE argument, which needs to be a character,
8672 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8673 precise meaning of each character:
8675 n Numerically, by converting the beginning of the entry/item to a number.
8676 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8677 o By order of TODO keywords.
8678 t By date/time, either the first active time stamp in the entry, or, if
8679 none exist, by the first inactive one.
8680 s By the scheduled date/time.
8681 d By deadline date/time.
8682 c By creation time, which is assumed to be the first inactive time stamp
8683 at the beginning of a line.
8684 p By priority according to the cookie.
8685 r By the value of a property.
8687 Capital letters will reverse the sort order.
8689 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8690 called with point at the beginning of the record. It must return either
8691 a string or a number that should serve as the sorting key for that record.
8693 Comparing entries ignores case by default. However, with an optional argument
8694 WITH-CASE, the sorting considers case as well.
8696 Sorting is done against the visible part of the headlines, it ignores hidden
8697 links.
8699 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8700 (interactive "P")
8701 (let ((case-func (if with-case 'identity 'downcase))
8702 (cmstr
8703 ;; The clock marker is lost when using `sort-subr', let's
8704 ;; store the clocking string.
8705 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8706 (save-excursion
8707 (goto-char org-clock-marker)
8708 (looking-back "^.*") (match-string-no-properties 0))))
8709 start beg end stars re re2
8710 txt what tmp)
8711 ;; Find beginning and end of region to sort
8712 (cond
8713 ((org-region-active-p)
8714 ;; we will sort the region
8715 (setq end (region-end)
8716 what "region")
8717 (goto-char (region-beginning))
8718 (if (not (org-at-heading-p)) (outline-next-heading))
8719 (setq start (point)))
8720 ((or (org-at-heading-p)
8721 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8722 ;; we will sort the children of the current headline
8723 (org-back-to-heading)
8724 (setq start (point)
8725 end (progn (org-end-of-subtree t t)
8726 (or (bolp) (insert "\n"))
8727 (org-back-over-empty-lines)
8728 (point))
8729 what "children")
8730 (goto-char start)
8731 (show-subtree)
8732 (outline-next-heading))
8734 ;; we will sort the top-level entries in this file
8735 (goto-char (point-min))
8736 (or (org-at-heading-p) (outline-next-heading))
8737 (setq start (point))
8738 (goto-char (point-max))
8739 (beginning-of-line 1)
8740 (when (looking-at ".*?\\S-")
8741 ;; File ends in a non-white line
8742 (end-of-line 1)
8743 (insert "\n"))
8744 (setq end (point-max))
8745 (setq what "top-level")
8746 (goto-char start)
8747 (show-all)))
8749 (setq beg (point))
8750 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8752 (looking-at "\\(\\*+\\)")
8753 (setq stars (match-string 1)
8754 re (concat "^" (regexp-quote stars) " +")
8755 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8756 txt (buffer-substring beg end))
8757 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8758 (if (and (not (equal stars "*")) (string-match re2 txt))
8759 (user-error "Region to sort contains a level above the first entry"))
8761 (unless sorting-type
8762 (message
8763 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8764 [t]ime [s]cheduled [d]eadline [c]reated
8765 A/N/P/R/O/F/T/S/D/C means reversed:"
8766 what)
8767 (setq sorting-type (read-char-exclusive))
8769 (unless getkey-func
8770 (and (= (downcase sorting-type) ?f)
8771 (setq getkey-func
8772 (org-icompleting-read "Sort using function: "
8773 obarray 'fboundp t nil nil))
8774 (setq getkey-func (intern getkey-func))))
8776 (and (= (downcase sorting-type) ?r)
8777 (not property)
8778 (setq property
8779 (org-icompleting-read "Property: "
8780 (mapcar 'list (org-buffer-property-keys t))
8781 nil t))))
8783 (message "Sorting entries...")
8785 (save-restriction
8786 (narrow-to-region start end)
8787 (let ((dcst (downcase sorting-type))
8788 (case-fold-search nil)
8789 (now (current-time)))
8790 (sort-subr
8791 (/= dcst sorting-type)
8792 ;; This function moves to the beginning character of the "record" to
8793 ;; be sorted.
8794 (lambda nil
8795 (if (re-search-forward re nil t)
8796 (goto-char (match-beginning 0))
8797 (goto-char (point-max))))
8798 ;; This function moves to the last character of the "record" being
8799 ;; sorted.
8800 (lambda nil
8801 (save-match-data
8802 (condition-case nil
8803 (outline-forward-same-level 1)
8804 (error
8805 (goto-char (point-max))))))
8806 ;; This function returns the value that gets sorted against.
8807 (lambda nil
8808 (cond
8809 ((= dcst ?n)
8810 (if (looking-at org-complex-heading-regexp)
8811 (string-to-number (org-sort-remove-invisible (match-string 4)))
8812 nil))
8813 ((= dcst ?a)
8814 (if (looking-at org-complex-heading-regexp)
8815 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8816 nil))
8817 ((= dcst ?t)
8818 (let ((end (save-excursion (outline-next-heading) (point))))
8819 (if (or (re-search-forward org-ts-regexp end t)
8820 (re-search-forward org-ts-regexp-both end t))
8821 (org-time-string-to-seconds (match-string 0))
8822 (org-float-time now))))
8823 ((= dcst ?c)
8824 (let ((end (save-excursion (outline-next-heading) (point))))
8825 (if (re-search-forward
8826 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8827 end t)
8828 (org-time-string-to-seconds (match-string 0))
8829 (org-float-time now))))
8830 ((= dcst ?s)
8831 (let ((end (save-excursion (outline-next-heading) (point))))
8832 (if (re-search-forward org-scheduled-time-regexp end t)
8833 (org-time-string-to-seconds (match-string 1))
8834 (org-float-time now))))
8835 ((= dcst ?d)
8836 (let ((end (save-excursion (outline-next-heading) (point))))
8837 (if (re-search-forward org-deadline-time-regexp end t)
8838 (org-time-string-to-seconds (match-string 1))
8839 (org-float-time now))))
8840 ((= dcst ?p)
8841 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8842 (string-to-char (match-string 2))
8843 org-default-priority))
8844 ((= dcst ?r)
8845 (or (org-entry-get nil property) ""))
8846 ((= dcst ?o)
8847 (if (looking-at org-complex-heading-regexp)
8848 (- 9999 (length (member (match-string 2)
8849 org-todo-keywords-1)))))
8850 ((= dcst ?f)
8851 (if getkey-func
8852 (progn
8853 (setq tmp (funcall getkey-func))
8854 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8855 tmp)
8856 (error "Invalid key function `%s'" getkey-func)))
8857 (t (error "Invalid sorting type `%c'" sorting-type))))
8859 (cond
8860 ((= dcst ?a) 'string<)
8861 ((= dcst ?f) compare-func)
8862 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8863 (run-hooks 'org-after-sorting-entries-or-items-hook)
8864 ;; Reset the clock marker if needed
8865 (when cmstr
8866 (save-excursion
8867 (goto-char start)
8868 (search-forward cmstr nil t)
8869 (move-marker org-clock-marker (point))))
8870 (message "Sorting entries...done")))
8872 (defun org-do-sort (table what &optional with-case sorting-type)
8873 "Sort TABLE of WHAT according to SORTING-TYPE.
8874 The user will be prompted for the SORTING-TYPE if the call to this
8875 function does not specify it. WHAT is only for the prompt, to indicate
8876 what is being sorted. The sorting key will be extracted from
8877 the car of the elements of the table.
8878 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8879 (unless sorting-type
8880 (message
8881 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8882 what)
8883 (setq sorting-type (read-char-exclusive)))
8884 (let ((dcst (downcase sorting-type))
8885 extractfun comparefun)
8886 ;; Define the appropriate functions
8887 (cond
8888 ((= dcst ?n)
8889 (setq extractfun 'string-to-number
8890 comparefun (if (= dcst sorting-type) '< '>)))
8891 ((= dcst ?a)
8892 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8893 (lambda(x) (downcase (org-sort-remove-invisible x))))
8894 comparefun (if (= dcst sorting-type)
8895 'string<
8896 (lambda (a b) (and (not (string< a b))
8897 (not (string= a b)))))))
8898 ((= dcst ?t)
8899 (setq extractfun
8900 (lambda (x)
8901 (if (or (string-match org-ts-regexp x)
8902 (string-match org-ts-regexp-both x))
8903 (org-float-time
8904 (org-time-string-to-time (match-string 0 x)))
8906 comparefun (if (= dcst sorting-type) '< '>)))
8907 (t (error "Invalid sorting type `%c'" sorting-type)))
8909 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8910 table)
8911 (lambda (a b) (funcall comparefun (car a) (car b))))))
8914 ;;; The orgstruct minor mode
8916 ;; Define a minor mode which can be used in other modes in order to
8917 ;; integrate the org-mode structure editing commands.
8919 ;; This is really a hack, because the org-mode structure commands use
8920 ;; keys which normally belong to the major mode. Here is how it
8921 ;; works: The minor mode defines all the keys necessary to operate the
8922 ;; structure commands, but wraps the commands into a function which
8923 ;; tests if the cursor is currently at a headline or a plain list
8924 ;; item. If that is the case, the structure command is used,
8925 ;; temporarily setting many Org-mode variables like regular
8926 ;; expressions for filling etc. However, when any of those keys is
8927 ;; used at a different location, function uses `key-binding' to look
8928 ;; up if the key has an associated command in another currently active
8929 ;; keymap (minor modes, major mode, global), and executes that
8930 ;; command. There might be problems if any of the keys is otherwise
8931 ;; used as a prefix key.
8933 (defcustom orgstruct-heading-prefix-regexp ""
8934 "Regexp that matches the custom prefix of Org headlines in
8935 orgstruct(++)-mode."
8936 :group 'org
8937 :version "24.4"
8938 :package-version '(Org . "8.3")
8939 :type 'regexp)
8940 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8942 (defcustom orgstruct-setup-hook nil
8943 "Hook run after orgstruct-mode-map is filled."
8944 :group 'org
8945 :version "24.4"
8946 :package-version '(Org . "8.0")
8947 :type 'hook)
8949 (defvar orgstruct-initialized nil)
8951 (defvar org-local-vars nil
8952 "List of local variables, for use by `orgstruct-mode'.")
8954 ;;;###autoload
8955 (define-minor-mode orgstruct-mode
8956 "Toggle the minor mode `orgstruct-mode'.
8957 This mode is for using Org-mode structure commands in other
8958 modes. The following keys behave as if Org-mode were active, if
8959 the cursor is on a headline, or on a plain list item (both as
8960 defined by Org-mode)."
8961 nil " OrgStruct" (make-sparse-keymap)
8962 (funcall (if orgstruct-mode
8963 'add-to-invisibility-spec
8964 'remove-from-invisibility-spec)
8965 '(outline . t))
8966 (when orgstruct-mode
8967 (org-load-modules-maybe)
8968 (unless orgstruct-initialized
8969 (orgstruct-setup)
8970 (setq orgstruct-initialized t))))
8972 ;;;###autoload
8973 (defun turn-on-orgstruct ()
8974 "Unconditionally turn on `orgstruct-mode'."
8975 (orgstruct-mode 1))
8977 (defvar org-fb-vars nil)
8978 (make-variable-buffer-local 'org-fb-vars)
8979 (defun orgstruct++-mode (&optional arg)
8980 "Toggle `orgstruct-mode', the enhanced version of it.
8981 In addition to setting orgstruct-mode, this also exports all
8982 indentation and autofilling variables from org-mode into the
8983 buffer. It will also recognize item context in multiline items."
8984 (interactive "P")
8985 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8986 (if (< arg 1)
8987 (progn (orgstruct-mode -1)
8988 (mapc (lambda(v)
8989 (org-set-local (car v)
8990 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8991 org-fb-vars))
8992 (orgstruct-mode 1)
8993 (setq org-fb-vars nil)
8994 (unless org-local-vars
8995 (setq org-local-vars (org-get-local-variables)))
8996 (let (var val)
8997 (mapc
8998 (lambda (x)
8999 (when (string-match
9000 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9001 (symbol-name (car x)))
9002 (setq var (car x) val (nth 1 x))
9003 (push (list var `(quote ,(eval var))) org-fb-vars)
9004 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9005 org-local-vars)
9006 (org-set-local 'orgstruct-is-++ t))))
9008 (defvar orgstruct-is-++ nil
9009 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9010 (make-variable-buffer-local 'orgstruct-is-++)
9012 ;;;###autoload
9013 (defun turn-on-orgstruct++ ()
9014 "Unconditionally turn on `orgstruct++-mode'."
9015 (orgstruct++-mode 1))
9017 (defun orgstruct-error ()
9018 "Error when there is no default binding for a structure key."
9019 (interactive)
9020 (funcall (if (fboundp 'user-error)
9021 'user-error
9022 'error)
9023 "This key has no function outside structure elements"))
9025 (defun orgstruct-setup ()
9026 "Setup orgstruct keymap."
9027 (dolist (cell '((org-demote . t)
9028 (org-metaleft . t)
9029 (org-metaright . t)
9030 (org-promote . t)
9031 (org-shiftmetaleft . t)
9032 (org-shiftmetaright . t)
9033 org-backward-element
9034 org-backward-heading-same-level
9035 org-ctrl-c-ret
9036 org-ctrl-c-minus
9037 org-ctrl-c-star
9038 org-cycle
9039 org-forward-heading-same-level
9040 org-insert-heading
9041 org-insert-heading-respect-content
9042 org-kill-note-or-show-branches
9043 org-mark-subtree
9044 org-meta-return
9045 org-metadown
9046 org-metaup
9047 org-narrow-to-subtree
9048 org-promote-subtree
9049 org-reveal
9050 org-shiftdown
9051 org-shiftleft
9052 org-shiftmetadown
9053 org-shiftmetaup
9054 org-shiftright
9055 org-shifttab
9056 org-shifttab
9057 org-shiftup
9058 org-show-subtree
9059 org-sort
9060 org-up-element
9061 outline-demote
9062 outline-next-visible-heading
9063 outline-previous-visible-heading
9064 outline-promote
9065 outline-up-heading
9066 show-children))
9067 (let ((f (or (car-safe cell) cell))
9068 (disable-when-heading-prefix (cdr-safe cell)))
9069 (when (fboundp f)
9070 (let ((new-bindings))
9071 (dolist (binding (nconc (where-is-internal f org-mode-map)
9072 (where-is-internal f outline-mode-map)))
9073 (push binding new-bindings)
9074 ;; TODO use local-function-key-map
9075 (dolist (rep '(("<tab>" . "TAB")
9076 ("<return>" . "RET")
9077 ("<escape>" . "ESC")
9078 ("<delete>" . "DEL")))
9079 (setq binding (read-kbd-macro
9080 (let ((case-fold-search))
9081 (replace-regexp-in-string
9082 (regexp-quote (cdr rep))
9083 (car rep)
9084 (key-description binding)))))
9085 (pushnew binding new-bindings :test 'equal)))
9086 (dolist (binding new-bindings)
9087 (let ((key (lookup-key orgstruct-mode-map binding)))
9088 (when (or (not key) (numberp key))
9089 (condition-case nil
9090 (org-defkey orgstruct-mode-map
9091 binding
9092 (orgstruct-make-binding f binding disable-when-heading-prefix))
9093 (error nil)))))))))
9094 (run-hooks 'orgstruct-setup-hook))
9096 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9097 "Create a function for binding in the structure minor mode.
9098 FUN is the command to call inside a table. KEY is the key that
9099 should be checked in for a command to execute outside of tables.
9100 Non-nil `disable-when-heading-prefix' means to disable the command
9101 if `orgstruct-heading-prefix-regexp' is not empty."
9102 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9103 (let ((nname name)
9104 (i 0))
9105 (while (fboundp (intern nname))
9106 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9107 (setq name (intern nname)))
9108 (eval
9109 (let ((bindings '((org-heading-regexp
9110 (concat "^"
9111 orgstruct-heading-prefix-regexp
9112 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9113 (org-outline-regexp
9114 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9115 (org-outline-regexp-bol
9116 (concat "^" org-outline-regexp))
9117 (outline-regexp org-outline-regexp)
9118 (outline-heading-end-regexp "\n")
9119 (outline-level 'org-outline-level)
9120 (outline-heading-alist))))
9121 `(defun ,name (arg)
9122 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9123 "Outside of structure, run the binding of `"
9124 (key-description key) "'."
9125 (when disable-when-heading-prefix
9126 (concat
9127 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9128 "back to the default binding due to limitations of Org's implementation of\n"
9129 "`" (symbol-name fun) "'.")))
9130 (interactive "p")
9131 (let* ((disable
9132 ,(and disable-when-heading-prefix
9133 '(not (string= orgstruct-heading-prefix-regexp ""))))
9134 (fallback
9135 (or disable
9136 (not
9137 (let* ,bindings
9138 (org-context-p 'headline 'item
9139 ,(when (memq fun
9140 '(org-insert-heading
9141 org-insert-heading-respect-content
9142 org-meta-return))
9143 '(when orgstruct-is-++
9144 'item-body))))))))
9145 (if fallback
9146 (let* ((orgstruct-mode)
9147 (binding
9148 (loop with key = ,key
9149 for rep in
9150 '(nil
9151 ("<\\([^>]*\\)tab>" . "\\1TAB")
9152 ("<\\([^>]*\\)return>" . "\\1RET")
9153 ("<\\([^>]*\\)escape>" . "\\1ESC")
9154 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9156 (when rep
9157 (setq key (read-kbd-macro
9158 (let ((case-fold-search))
9159 (replace-regexp-in-string
9160 (car rep)
9161 (cdr rep)
9162 (key-description key))))))
9163 thereis (key-binding key))))
9164 (if (keymapp binding)
9165 (org-set-transient-map binding)
9166 (let ((func (or binding
9167 (unless disable
9168 'orgstruct-error))))
9169 (when func
9170 (call-interactively func)))))
9171 (org-run-like-in-org-mode
9172 (lambda ()
9173 (interactive)
9174 (let* ,bindings
9175 (call-interactively ',fun)))))))))
9176 name))
9178 (defun org-contextualize-keys (alist contexts)
9179 "Return valid elements in ALIST depending on CONTEXTS.
9181 `org-agenda-custom-commands' or `org-capture-templates' are the
9182 values used for ALIST, and `org-agenda-custom-commands-contexts'
9183 or `org-capture-templates-contexts' are the associated contexts
9184 definitions."
9185 (let ((contexts
9186 ;; normalize contexts
9187 (mapcar
9188 (lambda(c) (cond ((listp (cadr c))
9189 (list (car c) (car c) (cadr c)))
9190 ((string= "" (cadr c))
9191 (list (car c) (car c) (caddr c)))
9192 (t c))) contexts))
9193 (a alist) c r s)
9194 ;; loop over all commands or templates
9195 (while (setq c (pop a))
9196 (let (vrules repl)
9197 (cond
9198 ((not (assoc (car c) contexts))
9199 (push c r))
9200 ((and (assoc (car c) contexts)
9201 (setq vrules (org-contextualize-validate-key
9202 (car c) contexts)))
9203 (mapc (lambda (vr)
9204 (when (not (equal (car vr) (cadr vr)))
9205 (setq repl vr))) vrules)
9206 (if (not repl) (push c r)
9207 (push (cadr repl) s)
9208 (push
9209 (cons (car c)
9210 (cdr (or (assoc (cadr repl) alist)
9211 (error "Undefined key `%s' as contextual replacement for `%s'"
9212 (cadr repl) (car c)))))
9213 r))))))
9214 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9215 (delq
9217 (delete-dups
9218 (mapcar (lambda (x)
9219 (let ((tpl (car x)))
9220 (when (not (delq
9222 (mapcar (lambda(y)
9223 (equal y tpl)) s))) x)))
9224 (reverse r))))))
9226 (defun org-contextualize-validate-key (key contexts)
9227 "Check CONTEXTS for agenda or capture KEY."
9228 (let (r rr res)
9229 (while (setq r (pop contexts))
9230 (mapc
9231 (lambda (rr)
9232 (when
9233 (and (equal key (car r))
9234 (if (functionp rr) (funcall rr)
9235 (or (and (eq (car rr) 'in-file)
9236 (buffer-file-name)
9237 (string-match (cdr rr) (buffer-file-name)))
9238 (and (eq (car rr) 'in-mode)
9239 (string-match (cdr rr) (symbol-name major-mode)))
9240 (and (eq (car rr) 'in-buffer)
9241 (string-match (cdr rr) (buffer-name)))
9242 (if (and (eq (car rr) 'not-in-file)
9243 (buffer-file-name))
9244 (not (string-match (cdr rr) (buffer-file-name)))
9246 (when (eq (car rr) 'not-in-mode)
9247 (not (string-match (cdr rr) (symbol-name major-mode))))
9248 (when (eq (car rr) 'not-in-buffer)
9249 (not (string-match (cdr rr) (buffer-name)))))))
9250 (push r res)))
9251 (car (last r))))
9252 (delete-dups (delq nil res))))
9254 (defun org-context-p (&rest contexts)
9255 "Check if local context is any of CONTEXTS.
9256 Possible values in the list of contexts are `table', `headline', and `item'."
9257 (let ((pos (point)))
9258 (goto-char (point-at-bol))
9259 (prog1 (or (and (memq 'table contexts)
9260 (looking-at "[ \t]*|"))
9261 (and (memq 'headline contexts)
9262 (looking-at org-outline-regexp))
9263 (and (memq 'item contexts)
9264 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9265 (and (memq 'item-body contexts)
9266 (org-in-item-p)))
9267 (goto-char pos))))
9269 (defun org-get-local-variables ()
9270 "Return a list of all local variables in an Org mode buffer."
9271 (let (varlist)
9272 (with-current-buffer (get-buffer-create "*Org tmp*")
9273 (erase-buffer)
9274 (org-mode)
9275 (setq varlist (buffer-local-variables)))
9276 (kill-buffer "*Org tmp*")
9277 (delq nil
9278 (mapcar
9279 (lambda (x)
9280 (setq x
9281 (if (symbolp x)
9282 (list x)
9283 (list (car x) (cdr x))))
9284 (if (and (not (get (car x) 'org-state))
9285 (string-match
9286 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9287 (symbol-name (car x))))
9288 x nil))
9289 varlist))))
9291 (defun org-clone-local-variables (from-buffer &optional regexp)
9292 "Clone local variables from FROM-BUFFER.
9293 Optional argument REGEXP selects variables to clone."
9294 (mapc
9295 (lambda (pair)
9296 (and (symbolp (car pair))
9297 (or (null regexp)
9298 (string-match regexp (symbol-name (car pair))))
9299 (set (make-local-variable (car pair))
9300 (cdr pair))))
9301 (buffer-local-variables from-buffer)))
9303 ;;;###autoload
9304 (defun org-run-like-in-org-mode (cmd)
9305 "Run a command, pretending that the current buffer is in Org-mode.
9306 This will temporarily bind local variables that are typically bound in
9307 Org-mode to the values they have in Org-mode, and then interactively
9308 call CMD."
9309 (org-load-modules-maybe)
9310 (unless org-local-vars
9311 (setq org-local-vars (org-get-local-variables)))
9312 (let (binds)
9313 (dolist (var org-local-vars)
9314 (when (or (not (boundp (car var)))
9315 (eq (symbol-value (car var))
9316 (default-value (car var))))
9317 (push (list (car var) `(quote ,(cadr var))) binds)))
9318 (eval `(let ,binds
9319 (call-interactively (quote ,cmd))))))
9321 ;;;; Archiving
9323 (defun org-get-category (&optional pos force-refresh)
9324 "Get the category applying to position POS."
9325 (save-match-data
9326 (if force-refresh (org-refresh-category-properties))
9327 (let ((pos (or pos (point))))
9328 (or (get-text-property pos 'org-category)
9329 (progn (org-refresh-category-properties)
9330 (get-text-property pos 'org-category))))))
9332 (defun org-refresh-category-properties ()
9333 "Refresh category text properties in the buffer."
9334 (let ((case-fold-search t)
9335 (inhibit-read-only t)
9336 (def-cat (cond
9337 ((null org-category)
9338 (if buffer-file-name
9339 (file-name-sans-extension
9340 (file-name-nondirectory buffer-file-name))
9341 "???"))
9342 ((symbolp org-category) (symbol-name org-category))
9343 (t org-category)))
9344 beg end cat pos optionp)
9345 (org-with-silent-modifications
9346 (save-excursion
9347 (save-restriction
9348 (widen)
9349 (goto-char (point-min))
9350 (put-text-property (point) (point-max) 'org-category def-cat)
9351 (while (re-search-forward
9352 "^[ \t]*\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9353 (setq pos (match-end 0)
9354 optionp (equal (char-after (match-beginning 0)) ?#)
9355 cat (org-trim (match-string 2)))
9356 (if optionp
9357 (setq beg (point-at-bol) end (point-max))
9358 (org-back-to-heading t)
9359 (setq beg (point) end (org-end-of-subtree t t)))
9360 (put-text-property beg end 'org-category cat)
9361 (put-text-property beg end 'org-category-position beg)
9362 (goto-char pos)))))))
9364 (defun org-refresh-properties (dprop tprop)
9365 "Refresh buffer text properties.
9366 DPROP is the drawer property and TPROP is the corresponding text
9367 property to set."
9368 (let ((case-fold-search t)
9369 (inhibit-read-only t) p)
9370 (org-with-silent-modifications
9371 (save-excursion
9372 (save-restriction
9373 (widen)
9374 (goto-char (point-min))
9375 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9376 (setq p (org-match-string-no-properties 1))
9377 (save-excursion
9378 (org-back-to-heading t)
9379 (put-text-property
9380 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9383 ;;;; Link Stuff
9385 ;;; Link abbreviations
9387 (defun org-link-expand-abbrev (link)
9388 "Apply replacements as defined in `org-link-abbrev-alist'."
9389 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9390 (let* ((key (match-string 1 link))
9391 (as (or (assoc key org-link-abbrev-alist-local)
9392 (assoc key org-link-abbrev-alist)))
9393 (tag (and (match-end 2) (match-string 3 link)))
9394 rpl)
9395 (if (not as)
9396 link
9397 (setq rpl (cdr as))
9398 (cond
9399 ((symbolp rpl) (funcall rpl tag))
9400 ((string-match "%(\\([^)]+\\))" rpl)
9401 (replace-match
9402 (save-match-data
9403 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9404 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9405 ((string-match "%h" rpl)
9406 (replace-match (url-hexify-string (or tag "")) t t rpl))
9407 (t (concat rpl tag)))))
9408 link))
9410 ;;; Storing and inserting links
9412 (defvar org-insert-link-history nil
9413 "Minibuffer history for links inserted with `org-insert-link'.")
9415 (defvar org-stored-links nil
9416 "Contains the links stored with `org-store-link'.")
9418 (defvar org-store-link-plist nil
9419 "Plist with info about the most recently link created with `org-store-link'.")
9421 (defvar org-link-protocols nil
9422 "Link protocols added to Org-mode using `org-add-link-type'.")
9424 (defvar org-store-link-functions nil
9425 "List of functions that are called to create and store a link.
9426 Each function will be called in turn until one returns a non-nil
9427 value. Each function should check if it is responsible for creating
9428 this link (for example by looking at the major mode).
9429 If not, it must exit and return nil.
9430 If yes, it should return a non-nil value after a calling
9431 `org-store-link-props' with a list of properties and values.
9432 Special properties are:
9434 :type The link prefix, like \"http\". This must be given.
9435 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9436 This is obligatory as well.
9437 :description Optional default description for the second pair
9438 of brackets in an Org-mode link. The user can still change
9439 this when inserting this link into an Org-mode buffer.
9441 In addition to these, any additional properties can be specified
9442 and then used in capture templates.")
9444 (defun org-add-link-type (type &optional follow export)
9445 "Add TYPE to the list of `org-link-types'.
9446 Re-compute all regular expressions depending on `org-link-types'
9448 FOLLOW and EXPORT are two functions.
9450 FOLLOW should take the link path as the single argument and do whatever
9451 is necessary to follow the link, for example find a file or display
9452 a mail message.
9454 EXPORT should format the link path for export to one of the export formats.
9455 It should be a function accepting three arguments:
9457 path the path of the link, the text after the prefix (like \"http:\")
9458 desc the description of the link, if any, or a description added by
9459 org-export-normalize-links if there is none
9460 format the export format, a symbol like `html' or `latex' or `ascii'..
9462 The function may use the FORMAT information to return different values
9463 depending on the format. The return value will be put literally into
9464 the exported file. If the return value is nil, this means Org should
9465 do what it normally does with links which do not have EXPORT defined.
9467 Org-mode has a built-in default for exporting links. If you are happy with
9468 this default, there is no need to define an export function for the link
9469 type. For a simple example of an export function, see `org-bbdb.el'."
9470 (add-to-list 'org-link-types type t)
9471 (org-make-link-regexps)
9472 (if (assoc type org-link-protocols)
9473 (setcdr (assoc type org-link-protocols) (list follow export))
9474 (push (list type follow export) org-link-protocols)))
9476 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9477 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9479 ;;;###autoload
9480 (defun org-store-link (arg)
9481 "\\<org-mode-map>Store an org-link to the current location.
9482 This link is added to `org-stored-links' and can later be inserted
9483 into an org-buffer with \\[org-insert-link].
9485 For some link types, a prefix arg is interpreted.
9486 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9487 For file links, arg negates `org-context-in-file-links'.
9489 A double prefix arg force skipping storing functions that are not
9490 part of Org's core.
9492 A triple prefix arg force storing a link for each line in the
9493 active region."
9494 (interactive "P")
9495 (org-load-modules-maybe)
9496 (if (and (equal arg '(64)) (org-region-active-p))
9497 (save-excursion
9498 (let ((end (region-end)))
9499 (goto-char (region-beginning))
9500 (set-mark (point))
9501 (while (< (point-at-eol) end)
9502 (move-end-of-line 1) (activate-mark)
9503 (let (current-prefix-arg)
9504 (call-interactively 'org-store-link))
9505 (move-beginning-of-line 2)
9506 (set-mark (point)))))
9507 (org-with-limited-levels
9508 (setq org-store-link-plist nil)
9509 (let (link cpltxt desc description search
9510 txt custom-id agenda-link sfuns sfunsn)
9511 (cond
9513 ;; Store a link using an external link type
9514 ((and (not (equal arg '(16)))
9515 (setq sfuns
9516 (delq
9517 nil (mapcar (lambda (f)
9518 (let (fs) (if (funcall f) (push f fs))))
9519 org-store-link-functions))
9520 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9521 (or (and (cdr sfuns)
9522 (funcall (intern
9523 (completing-read
9524 "Which function for creating the link? "
9525 sfunsn nil t (car sfunsn)))))
9526 (funcall (caar sfuns)))
9527 (setq link (plist-get org-store-link-plist :link)
9528 desc (or (plist-get org-store-link-plist
9529 :description) link))))
9531 ;; Store a link from a source code buffer
9532 ((org-src-edit-buffer-p)
9533 (let (label gc)
9534 (while (or (not label)
9535 (save-excursion
9536 (save-restriction
9537 (widen)
9538 (goto-char (point-min))
9539 (re-search-forward
9540 (regexp-quote (format org-coderef-label-format label))
9541 nil t))))
9542 (when label (message "Label exists already") (sit-for 2))
9543 (setq label (read-string "Code line label: " label)))
9544 (end-of-line 1)
9545 (setq link (format org-coderef-label-format label))
9546 (setq gc (- 79 (length link)))
9547 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9548 (insert link)
9549 (setq link (concat "(" label ")") desc nil)))
9551 ;; We are in the agenda, link to referenced location
9552 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9553 (let ((m (or (get-text-property (point) 'org-hd-marker)
9554 (get-text-property (point) 'org-marker))))
9555 (when m
9556 (org-with-point-at m
9557 (setq agenda-link
9558 (if (org-called-interactively-p 'any)
9559 (call-interactively 'org-store-link)
9560 (org-store-link nil)))))))
9562 ((eq major-mode 'calendar-mode)
9563 (let ((cd (calendar-cursor-to-date)))
9564 (setq link
9565 (format-time-string
9566 (car org-time-stamp-formats)
9567 (apply 'encode-time
9568 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9569 nil nil nil))))
9570 (org-store-link-props :type "calendar" :date cd)))
9572 ((eq major-mode 'help-mode)
9573 (setq link (concat "help:" (save-excursion
9574 (goto-char (point-min))
9575 (looking-at "^[^ ]+")
9576 (match-string 0))))
9577 (org-store-link-props :type "help"))
9579 ((eq major-mode 'w3-mode)
9580 (setq cpltxt (if (and (buffer-name)
9581 (not (string-match "Untitled" (buffer-name))))
9582 (buffer-name)
9583 (url-view-url t))
9584 link (url-view-url t))
9585 (org-store-link-props :type "w3" :url (url-view-url t)))
9587 ((eq major-mode 'image-mode)
9588 (setq cpltxt (concat "file:"
9589 (abbreviate-file-name buffer-file-name))
9590 link cpltxt)
9591 (org-store-link-props :type "image" :file buffer-file-name))
9593 ;; In dired, store a link to the file of the current line
9594 ((derived-mode-p 'dired-mode)
9595 (let ((file (dired-get-filename nil t)))
9596 (setq file (if file
9597 (abbreviate-file-name
9598 (expand-file-name (dired-get-filename nil t)))
9599 ;; otherwise, no file so use current directory.
9600 default-directory))
9601 (setq cpltxt (concat "file:" file)
9602 link cpltxt)))
9604 ((setq search (run-hook-with-args-until-success
9605 'org-create-file-search-functions))
9606 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9607 "::" search))
9608 (setq cpltxt (or description link)))
9610 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9611 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9612 (cond
9613 ;; Store a link using the target at point
9614 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9615 (setq cpltxt
9616 (concat "file:"
9617 (abbreviate-file-name
9618 (buffer-file-name (buffer-base-buffer)))
9619 "::" (match-string 1))
9620 link cpltxt))
9621 ((and (featurep 'org-id)
9622 (or (eq org-id-link-to-org-use-id t)
9623 (and (org-called-interactively-p 'any)
9624 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9625 (and (eq org-id-link-to-org-use-id
9626 'create-if-interactive-and-no-custom-id)
9627 (not custom-id))))
9628 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9629 ;; Store a link using the ID at point
9630 (setq link (condition-case nil
9631 (prog1 (org-id-store-link)
9632 (setq desc (or (plist-get org-store-link-plist
9633 :description)
9634 "")))
9635 (error
9636 ;; Probably before first headline, link only to file
9637 (concat "file:"
9638 (abbreviate-file-name
9639 (buffer-file-name (buffer-base-buffer))))))))
9641 ;; Just link to current headline
9642 (setq cpltxt (concat "file:"
9643 (abbreviate-file-name
9644 (buffer-file-name (buffer-base-buffer)))))
9645 ;; Add a context search string
9646 (when (org-xor org-context-in-file-links arg)
9647 (let* ((ee (org-element-at-point))
9648 (et (org-element-type ee))
9649 (ev (plist-get (cadr ee) :value))
9650 (ek (plist-get (cadr ee) :key))
9651 (eok (and (stringp ek) (string-match "name" ek))))
9652 (setq txt (cond
9653 ((org-at-heading-p) nil)
9654 ((and (eq et 'keyword) eok) ev)
9655 ((org-region-active-p)
9656 (buffer-substring (region-beginning) (region-end)))))
9657 (when (or (null txt) (string-match "\\S-" txt))
9658 (setq cpltxt
9659 (concat cpltxt "::"
9660 (condition-case nil
9661 (org-make-org-heading-search-string txt)
9662 (error "")))
9663 desc (or (and (eq et 'keyword) eok ev)
9664 (nth 4 (ignore-errors (org-heading-components)))
9665 "NONE")))))
9666 (if (string-match "::\\'" cpltxt)
9667 (setq cpltxt (substring cpltxt 0 -2)))
9668 (setq link cpltxt))))
9670 ((buffer-file-name (buffer-base-buffer))
9671 ;; Just link to this file here.
9672 (setq cpltxt (concat "file:"
9673 (abbreviate-file-name
9674 (buffer-file-name (buffer-base-buffer)))))
9675 ;; Add a context string.
9676 (when (org-xor org-context-in-file-links arg)
9677 (setq txt (if (org-region-active-p)
9678 (buffer-substring (region-beginning) (region-end))
9679 (buffer-substring (point-at-bol) (point-at-eol))))
9680 ;; Only use search option if there is some text.
9681 (when (string-match "\\S-" txt)
9682 (setq cpltxt
9683 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9684 desc "NONE")))
9685 (setq link cpltxt))
9687 ((org-called-interactively-p 'interactive)
9688 (user-error "No method for storing a link from this buffer"))
9690 (t (setq link nil)))
9692 ;; We're done setting link and desc, clean up
9693 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9694 (setq link (or link cpltxt)
9695 desc (or desc cpltxt))
9696 (cond ((equal desc "NONE") (setq desc nil))
9697 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9698 (let ((d0 (match-string 3 desc))
9699 (p0 (match-string 5 desc)))
9700 (setq desc
9701 (replace-regexp-in-string
9702 org-bracket-link-regexp
9703 (concat (or p0 d0)
9704 (if (equal (length (match-string 0 desc))
9705 (length desc)) "*" "")) desc)))))
9707 ;; Return the link
9708 (if (not (and (or (org-called-interactively-p 'any)
9709 executing-kbd-macro) link))
9710 (or agenda-link (and link (org-make-link-string link desc)))
9711 (push (list link desc) org-stored-links)
9712 (message "Stored: %s" (or desc link))
9713 (when custom-id
9714 (setq link (concat "file:" (abbreviate-file-name
9715 (buffer-file-name)) "::#" custom-id))
9716 (push (list link desc) org-stored-links))
9717 (car org-stored-links))))))
9719 (defun org-store-link-props (&rest plist)
9720 "Store link properties, extract names and addresses."
9721 (let (x adr)
9722 (when (setq x (plist-get plist :from))
9723 (setq adr (mail-extract-address-components x))
9724 (setq plist (plist-put plist :fromname (car adr)))
9725 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9726 (when (setq x (plist-get plist :to))
9727 (setq adr (mail-extract-address-components x))
9728 (setq plist (plist-put plist :toname (car adr)))
9729 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9730 (let ((from (plist-get plist :from))
9731 (to (plist-get plist :to)))
9732 (when (and from to org-from-is-user-regexp)
9733 (setq plist
9734 (plist-put plist :fromto
9735 (if (string-match org-from-is-user-regexp from)
9736 (concat "to %t")
9737 (concat "from %f"))))))
9738 (setq org-store-link-plist plist))
9740 (defun org-add-link-props (&rest plist)
9741 "Add these properties to the link property list."
9742 (let (key value)
9743 (while plist
9744 (setq key (pop plist) value (pop plist))
9745 (setq org-store-link-plist
9746 (plist-put org-store-link-plist key value)))))
9748 (defun org-email-link-description (&optional fmt)
9749 "Return the description part of an email link.
9750 This takes information from `org-store-link-plist' and formats it
9751 according to FMT (default from `org-email-link-description-format')."
9752 (setq fmt (or fmt org-email-link-description-format))
9753 (let* ((p org-store-link-plist)
9754 (to (plist-get p :toaddress))
9755 (from (plist-get p :fromaddress))
9756 (table
9757 (list
9758 (cons "%c" (plist-get p :fromto))
9759 (cons "%F" (plist-get p :from))
9760 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9761 (cons "%T" (plist-get p :to))
9762 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9763 (cons "%s" (plist-get p :subject))
9764 (cons "%d" (plist-get p :date))
9765 (cons "%m" (plist-get p :message-id)))))
9766 (when (string-match "%c" fmt)
9767 ;; Check if the user wrote this message
9768 (if (and org-from-is-user-regexp from to
9769 (save-match-data (string-match org-from-is-user-regexp from)))
9770 (setq fmt (replace-match "to %t" t t fmt))
9771 (setq fmt (replace-match "from %f" t t fmt))))
9772 (org-replace-escapes fmt table)))
9774 (defun org-make-org-heading-search-string (&optional string)
9775 "Make search string for the current headline or STRING."
9776 (let ((s (or string
9777 (and (derived-mode-p 'org-mode)
9778 (save-excursion
9779 (org-back-to-heading t)
9780 (org-element-property :raw-value (org-element-at-point))))))
9781 (lines org-context-in-file-links))
9782 (or string (setq s (concat "*" s))) ; Add * for headlines
9783 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9784 (when (and string (integerp lines) (> lines 0))
9785 (let ((slines (org-split-string s "\n")))
9786 (when (< lines (length slines))
9787 (setq s (mapconcat
9788 'identity
9789 (reverse (nthcdr (- (length slines) lines)
9790 (reverse slines))) "\n")))))
9791 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9793 (defun org-make-link-string (link &optional description)
9794 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9795 (unless (string-match "\\S-" link)
9796 (error "Empty link"))
9797 (when (and description
9798 (stringp description)
9799 (not (string-match "\\S-" description)))
9800 (setq description nil))
9801 (when (stringp description)
9802 ;; Remove brackets from the description, they are fatal.
9803 (while (string-match "\\[" description)
9804 (setq description (replace-match "{" t t description)))
9805 (while (string-match "\\]" description)
9806 (setq description (replace-match "}" t t description))))
9807 (when (equal link description)
9808 ;; No description needed, it is identical
9809 (setq description nil))
9810 (when (and (not description)
9811 (not (string-match (org-image-file-name-regexp) link))
9812 (not (equal link (org-link-escape link))))
9813 (setq description (org-extract-attributes link)))
9814 (setq link
9815 (cond ((string-match (org-image-file-name-regexp) link) link)
9816 ((string-match org-link-types-re link)
9817 (concat (match-string 1 link)
9818 (org-link-escape (substring link (match-end 1)))))
9819 (t (org-link-escape link))))
9820 (concat "[[" link "]"
9821 (if description (concat "[" description "]") "")
9822 "]"))
9824 (defconst org-link-escape-chars
9825 ;;%20 %2B %3B %3D %5B %5D
9826 '(?\ ?\+ ?\; ?\= ?\[ ?\])
9827 "List of characters that should be escaped in a link when stored to Org.
9828 This is the list that is used for internal purposes.")
9830 (defconst org-link-escape-chars-browser
9831 ;;%20 %22
9832 '(?\ ?\")
9833 "List of characters to be escaped before handing over to the browser.
9834 If you consider using this constant then you probably want to use
9835 the function `org-link-escape-browser' instead. See there why
9836 this constant is a candidate to be removed once Org drops support
9837 for Emacs 24.1 and 24.2.")
9839 (defun org-link-escape (text &optional table merge)
9840 "Return percent escaped representation of TEXT.
9841 TEXT is a string with the text to escape.
9842 Optional argument TABLE is a list with characters that should be
9843 escaped. When nil, `org-link-escape-chars' is used.
9844 If optional argument MERGE is set, merge TABLE into
9845 `org-link-escape-chars'."
9846 (cond
9847 ((and table merge)
9848 (mapc (lambda (defchr)
9849 (unless (member defchr table)
9850 (setq table (cons defchr table)))) org-link-escape-chars))
9851 ((null table)
9852 (setq table org-link-escape-chars)))
9853 (mapconcat
9854 (lambda (char)
9855 (if (or (member char table)
9856 (and (or (< char 32) (= char ?\%) (> char 126))
9857 org-url-hexify-p))
9858 (mapconcat (lambda (sequence-element)
9859 (format "%%%.2X" sequence-element))
9860 (or (encode-coding-char char 'utf-8)
9861 (error "Unable to percent escape character: %s"
9862 (char-to-string char))) "")
9863 (char-to-string char))) text ""))
9865 (defun org-link-escape-browser (text)
9866 "Escape some characters before handing over to the browser.
9867 This function is a candidate to be removed together with the
9868 constant `org-link-escape-chars-browser' once Org drops support
9869 for Emacs 24.1 and 24.2. All calls to this function will have to
9870 be replaced with `url-encode-url' which is available since Emacs
9871 24.3.1."
9872 ;; Example with the Org link
9873 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
9874 ;; to open the browser with +subject:"Release 8.2" filled into the
9875 ;; query field: In this case the variable TEXT contains the
9876 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
9877 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
9878 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
9879 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
9880 (if (fboundp 'url-encode-url)
9881 (url-encode-url text)
9882 (if (org-string-match-p
9883 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
9884 text)
9885 (org-link-escape text org-link-escape-chars-browser)
9886 text)))
9888 (defun org-link-unescape (str)
9889 "Unhex hexified Unicode strings as returned from the JavaScript function
9890 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9891 (unless (and (null str) (string= "" str))
9892 (let ((pos 0) (case-fold-search t) unhexed)
9893 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9894 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9895 (setq str (replace-match unhexed t t str))
9896 (setq pos (+ pos (length unhexed))))))
9897 str)
9899 (defun org-link-unescape-compound (hex)
9900 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9901 Note: this function also decodes single byte encodings like
9902 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9903 (save-match-data
9904 (let* ((bytes (cdr (split-string hex "%")))
9905 (ret "")
9906 (eat 0)
9907 (sum 0))
9908 (while bytes
9909 (let* ((val (string-to-number (pop bytes) 16))
9910 (shift-xor
9911 (if (= 0 eat)
9912 (cond
9913 ((>= val 252) (cons 6 252))
9914 ((>= val 248) (cons 5 248))
9915 ((>= val 240) (cons 4 240))
9916 ((>= val 224) (cons 3 224))
9917 ((>= val 192) (cons 2 192))
9918 (t (cons 0 0)))
9919 (cons 6 128))))
9920 (if (>= val 192) (setq eat (car shift-xor)))
9921 (setq val (logxor val (cdr shift-xor)))
9922 (setq sum (+ (lsh sum (car shift-xor)) val))
9923 (if (> eat 0) (setq eat (- eat 1)))
9924 (cond
9925 ((= 0 eat) ;multi byte
9926 (setq ret (concat ret (org-char-to-string sum)))
9927 (setq sum 0))
9928 ((not bytes) ; single byte(s)
9929 (setq ret (org-link-unescape-single-byte-sequence hex))))
9930 )) ;; end (while bytes
9931 ret )))
9933 (defun org-link-unescape-single-byte-sequence (hex)
9934 "Unhexify hex-encoded single byte character sequences."
9935 (mapconcat (lambda (byte)
9936 (char-to-string (string-to-number byte 16)))
9937 (cdr (split-string hex "%")) ""))
9939 (defun org-xor (a b)
9940 "Exclusive or."
9941 (if a (not b) b))
9943 (defun org-fixup-message-id-for-http (s)
9944 "Replace special characters in a message id, so it can be used in an http query."
9945 (when (string-match "%" s)
9946 (setq s (mapconcat (lambda (c)
9947 (if (eq c ?%)
9948 "%25"
9949 (char-to-string c)))
9950 s "")))
9951 (while (string-match "<" s)
9952 (setq s (replace-match "%3C" t t s)))
9953 (while (string-match ">" s)
9954 (setq s (replace-match "%3E" t t s)))
9955 (while (string-match "@" s)
9956 (setq s (replace-match "%40" t t s)))
9959 (defun org-link-prettify (link)
9960 "Return a human-readable representation of LINK.
9961 The car of LINK must be a raw link.
9962 The cdr of LINK must be either a link description or nil."
9963 (let ((desc (or (cadr link) "<no description>")))
9964 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9965 "<" (car link) ">")))
9967 ;;;###autoload
9968 (defun org-insert-link-global ()
9969 "Insert a link like Org-mode does.
9970 This command can be called in any mode to insert a link in Org-mode syntax."
9971 (interactive)
9972 (org-load-modules-maybe)
9973 (org-run-like-in-org-mode 'org-insert-link))
9975 (defun org-insert-all-links (arg &optional pre post)
9976 "Insert all links in `org-stored-links'.
9977 When a universal prefix, do not delete the links from `org-stored-links'.
9978 When `ARG' is a number, insert the last N link(s).
9979 `PRE' and `POST' are optional arguments to define a string to
9980 prepend or to append."
9981 (interactive "P")
9982 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9983 (links (copy-seq org-stored-links))
9984 (pr (or pre "- "))
9985 (po (or post "\n"))
9986 (cnt 1) l)
9987 (if (null org-stored-links)
9988 (message "No link to insert")
9989 (while (and (or (listp arg) (>= arg cnt))
9990 (setq l (if (listp arg)
9991 (pop links)
9992 (pop org-stored-links))))
9993 (setq cnt (1+ cnt))
9994 (insert pr)
9995 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9996 (insert po)))))
9998 (defun org-insert-last-stored-link (arg)
9999 "Insert the last link stored in `org-stored-links'."
10000 (interactive "p")
10001 (org-insert-all-links arg "" "\n"))
10003 (defun org-link-fontify-links-to-this-file ()
10004 "Fontify links to the current file in `org-stored-links'."
10005 (let ((f (buffer-file-name)) a b)
10006 (setq a (mapcar (lambda(l)
10007 (let ((ll (car l)))
10008 (when (and (string-match "^file:\\(.+\\)::" ll)
10009 (equal f (expand-file-name (match-string 1 ll))))
10010 ll)))
10011 org-stored-links))
10012 (when (featurep 'org-id)
10013 (setq b (mapcar (lambda(l)
10014 (let ((ll (car l)))
10015 (when (and (string-match "^id:\\(.+\\)$" ll)
10016 (equal f (expand-file-name
10017 (or (org-id-find-id-file
10018 (match-string 1 ll)) ""))))
10019 ll)))
10020 org-stored-links)))
10021 (mapcar (lambda(l)
10022 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10023 (delq nil (append a b)))))
10025 (defvar org-link-links-in-this-file nil)
10026 (defun org-insert-link (&optional complete-file link-location default-description)
10027 "Insert a link. At the prompt, enter the link.
10029 Completion can be used to insert any of the link protocol prefixes like
10030 http or ftp in use.
10032 The history can be used to select a link previously stored with
10033 `org-store-link'. When the empty string is entered (i.e. if you just
10034 press RET at the prompt), the link defaults to the most recently
10035 stored link. As SPC triggers completion in the minibuffer, you need to
10036 use M-SPC or C-q SPC to force the insertion of a space character.
10038 You will also be prompted for a description, and if one is given, it will
10039 be displayed in the buffer instead of the link.
10041 If there is already a link at point, this command will allow you to edit link
10042 and description parts.
10044 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10045 be selected using completion. The path to the file will be relative to the
10046 current directory if the file is in the current directory or a subdirectory.
10047 Otherwise, the link will be the absolute path as completed in the minibuffer
10048 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10049 option `org-link-file-path-type'.
10051 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10052 the current directory or below.
10054 With three \\[universal-argument] prefixes, negate the meaning of
10055 `org-keep-stored-link-after-insertion'.
10057 If `org-make-link-description-function' is non-nil, this function will be
10058 called with the link target, and the result will be the default
10059 link description.
10061 If the LINK-LOCATION parameter is non-nil, this value will be
10062 used as the link location instead of reading one interactively.
10064 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10065 be used as the default description."
10066 (interactive "P")
10067 (let* ((wcf (current-window-configuration))
10068 (origbuf (current-buffer))
10069 (region (if (org-region-active-p)
10070 (buffer-substring (region-beginning) (region-end))))
10071 (remove (and region (list (region-beginning) (region-end))))
10072 (desc region)
10073 tmphist ; byte-compile incorrectly complains about this
10074 (link link-location)
10075 (abbrevs org-link-abbrev-alist-local)
10076 entry file all-prefixes auto-desc)
10077 (cond
10078 (link-location) ; specified by arg, just use it.
10079 ((org-in-regexp org-bracket-link-regexp 1)
10080 ;; We do have a link at point, and we are going to edit it.
10081 (setq remove (list (match-beginning 0) (match-end 0)))
10082 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10083 (setq link (read-string "Link: "
10084 (org-link-unescape
10085 (org-match-string-no-properties 1)))))
10086 ((or (org-in-regexp org-angle-link-re)
10087 (org-in-regexp org-plain-link-re))
10088 ;; Convert to bracket link
10089 (setq remove (list (match-beginning 0) (match-end 0))
10090 link (read-string "Link: "
10091 (org-remove-angle-brackets (match-string 0)))))
10092 ((member complete-file '((4) (16)))
10093 ;; Completing read for file names.
10094 (setq link (org-file-complete-link complete-file)))
10096 ;; Read link, with completion for stored links.
10097 (org-link-fontify-links-to-this-file)
10098 (org-switch-to-buffer-other-window "*Org Links*")
10099 (with-current-buffer "*Org Links*"
10100 (erase-buffer)
10101 (insert "Insert a link.
10102 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10103 (when org-stored-links
10104 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10105 (insert (mapconcat 'org-link-prettify
10106 (reverse org-stored-links) "\n")))
10107 (goto-char (point-min)))
10108 (let ((cw (selected-window)))
10109 (select-window (get-buffer-window "*Org Links*" 'visible))
10110 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10111 (unless (pos-visible-in-window-p (point-max))
10112 (org-fit-window-to-buffer))
10113 (and (window-live-p cw) (select-window cw)))
10114 ;; Fake a link history, containing the stored links.
10115 (setq tmphist (append (mapcar 'car org-stored-links)
10116 org-insert-link-history))
10117 (setq all-prefixes (append (mapcar 'car abbrevs)
10118 (mapcar 'car org-link-abbrev-alist)
10119 org-link-types))
10120 (unwind-protect
10121 (progn
10122 (setq link
10123 (org-completing-read
10124 "Link: "
10125 (append
10126 (mapcar (lambda (x) (concat x ":"))
10127 all-prefixes)
10128 (mapcar 'car org-stored-links))
10129 nil nil nil
10130 'tmphist
10131 (caar org-stored-links)))
10132 (if (not (string-match "\\S-" link))
10133 (user-error "No link selected"))
10134 (mapc (lambda(l)
10135 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10136 org-stored-links)
10137 (if (or (member link all-prefixes)
10138 (and (equal ":" (substring link -1))
10139 (member (substring link 0 -1) all-prefixes)
10140 (setq link (substring link 0 -1))))
10141 (setq link (with-current-buffer origbuf
10142 (org-link-try-special-completion link)))))
10143 (set-window-configuration wcf)
10144 (kill-buffer "*Org Links*"))
10145 (setq entry (assoc link org-stored-links))
10146 (or entry (push link org-insert-link-history))
10147 (setq desc (or desc (nth 1 entry)))))
10149 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10150 (not org-keep-stored-link-after-insertion))
10151 (setq org-stored-links (delq (assoc link org-stored-links)
10152 org-stored-links)))
10154 (if (and (string-match org-plain-link-re link)
10155 (not (string-match org-ts-regexp link)))
10156 ;; URL-like link, normalize the use of angular brackets.
10157 (setq link (org-remove-angle-brackets link)))
10159 ;; Check if we are linking to the current file with a search
10160 ;; option If yes, simplify the link by using only the search
10161 ;; option.
10162 (when (and buffer-file-name
10163 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10164 (let* ((path (match-string 1 link))
10165 (case-fold-search nil)
10166 (search (match-string 2 link)))
10167 (save-match-data
10168 (if (equal (file-truename buffer-file-name) (file-truename path))
10169 ;; We are linking to this same file, with a search option
10170 (setq link search)))))
10172 ;; Check if we can/should use a relative path. If yes, simplify the link
10173 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10174 (let* ((type (match-string 1 link))
10175 (path (match-string 2 link))
10176 (origpath path)
10177 (case-fold-search nil))
10178 (cond
10179 ((or (eq org-link-file-path-type 'absolute)
10180 (equal complete-file '(16)))
10181 (setq path (abbreviate-file-name (expand-file-name path))))
10182 ((eq org-link-file-path-type 'noabbrev)
10183 (setq path (expand-file-name path)))
10184 ((eq org-link-file-path-type 'relative)
10185 (setq path (file-relative-name path)))
10187 (save-match-data
10188 (if (string-match (concat "^" (regexp-quote
10189 (expand-file-name
10190 (file-name-as-directory
10191 default-directory))))
10192 (expand-file-name path))
10193 ;; We are linking a file with relative path name.
10194 (setq path (substring (expand-file-name path)
10195 (match-end 0)))
10196 (setq path (abbreviate-file-name (expand-file-name path)))))))
10197 (setq link (concat type path))
10198 (if (equal desc origpath)
10199 (setq desc path))))
10201 (if org-make-link-description-function
10202 (setq desc
10203 (or (condition-case nil
10204 (funcall org-make-link-description-function link desc)
10205 (error (progn (message "Can't get link description from `%s'"
10206 (symbol-name org-make-link-description-function))
10207 (sit-for 2) nil)))
10208 (read-string "Description: " default-description)))
10209 (if default-description (setq desc default-description)
10210 (setq desc (or (and auto-desc desc)
10211 (read-string "Description: " desc)))))
10213 (unless (string-match "\\S-" desc) (setq desc nil))
10214 (if remove (apply 'delete-region remove))
10215 (insert (org-make-link-string link desc))))
10217 (defun org-link-try-special-completion (type)
10218 "If there is completion support for link type TYPE, offer it."
10219 (let ((fun (intern (concat "org-" type "-complete-link"))))
10220 (if (functionp fun)
10221 (funcall fun)
10222 (read-string "Link (no completion support): " (concat type ":")))))
10224 (defun org-file-complete-link (&optional arg)
10225 "Create a file link using completion."
10226 (let (file link)
10227 (setq file (org-iread-file-name "File: "))
10228 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10229 (pwd1 (file-name-as-directory (abbreviate-file-name
10230 (expand-file-name ".")))))
10231 (cond
10232 ((equal arg '(16))
10233 (setq link (concat
10234 "file:"
10235 (abbreviate-file-name (expand-file-name file)))))
10236 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10237 (setq link (concat "file:" (match-string 1 file))))
10238 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10239 (expand-file-name file))
10240 (setq link (concat
10241 "file:" (match-string 1 (expand-file-name file)))))
10242 (t (setq link (concat "file:" file)))))
10243 link))
10245 (defun org-iread-file-name (&rest args)
10246 "Read-file-name using `ido-mode' speedup if available.
10247 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10248 See `read-file-name' for a description of parameters."
10249 (org-without-partial-completion
10250 (if (and org-completion-use-ido
10251 (fboundp 'ido-read-file-name)
10252 (boundp 'ido-mode) ido-mode
10253 (listp (second args)))
10254 (let ((ido-enter-matching-directory nil))
10255 (apply 'ido-read-file-name args))
10256 (apply 'read-file-name args))))
10258 (defun org-completing-read (&rest args)
10259 "Completing-read with SPACE being a normal character."
10260 (let ((enable-recursive-minibuffers t)
10261 (minibuffer-local-completion-map
10262 (copy-keymap minibuffer-local-completion-map)))
10263 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10264 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10265 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10266 (apply 'org-icompleting-read args)))
10268 (defun org-completing-read-no-i (&rest args)
10269 (let (org-completion-use-ido org-completion-use-iswitchb)
10270 (apply 'org-completing-read args)))
10272 (defun org-iswitchb-completing-read (prompt choices &rest args)
10273 "Use iswitch as a completing-read replacement to choose from choices.
10274 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10275 from."
10276 (let* ((iswitchb-use-virtual-buffers nil)
10277 (iswitchb-make-buflist-hook
10278 (lambda ()
10279 (setq iswitchb-temp-buflist choices))))
10280 (iswitchb-read-buffer prompt)))
10282 (defun org-icompleting-read (&rest args)
10283 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10284 (org-without-partial-completion
10285 (if (and org-completion-use-ido
10286 (fboundp 'ido-completing-read)
10287 (boundp 'ido-mode) ido-mode
10288 (listp (second args)))
10289 (let ((ido-enter-matching-directory nil))
10290 (apply 'ido-completing-read (concat (car args))
10291 (if (consp (car (nth 1 args)))
10292 (mapcar 'car (nth 1 args))
10293 (nth 1 args))
10294 (cddr args)))
10295 (if (and org-completion-use-iswitchb
10296 (boundp 'iswitchb-mode) iswitchb-mode
10297 (listp (second args)))
10298 (apply 'org-iswitchb-completing-read (concat (car args))
10299 (if (consp (car (nth 1 args)))
10300 (mapcar 'car (nth 1 args))
10301 (nth 1 args))
10302 (cddr args))
10303 (apply 'completing-read args)))))
10305 (defun org-extract-attributes (s)
10306 "Extract the attributes cookie from a string and set as text property."
10307 (let (a attr (start 0) key value)
10308 (save-match-data
10309 (when (string-match "{{\\([^}]+\\)}}$" s)
10310 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10311 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10312 (setq key (match-string 1 a) value (match-string 2 a)
10313 start (match-end 0)
10314 attr (plist-put attr (intern key) value))))
10315 (org-add-props s nil 'org-attr attr))
10318 ;;; Opening/following a link
10320 (defvar org-link-search-failed nil)
10322 (defvar org-open-link-functions nil
10323 "Hook for functions finding a plain text link.
10324 These functions must take a single argument, the link content.
10325 They will be called for links that look like [[link text][description]]
10326 when LINK TEXT does not have a protocol like \"http:\" and does not look
10327 like a filename (e.g. \"./blue.png\").
10329 These functions will be called *before* Org attempts to resolve the
10330 link by doing text searches in the current buffer - so if you want a
10331 link \"[[target]]\" to still find \"<<target>>\", your function should
10332 handle this as a special case.
10334 When the function does handle the link, it must return a non-nil value.
10335 If it decides that it is not responsible for this link, it must return
10336 nil to indicate that that Org-mode can continue with other options
10337 like exact and fuzzy text search.")
10339 (defun org-next-link (&optional search-backward)
10340 "Move forward to the next link.
10341 If the link is in hidden text, expose it."
10342 (interactive "P")
10343 (when (and org-link-search-failed (eq this-command last-command))
10344 (goto-char (point-min))
10345 (message "Link search wrapped back to beginning of buffer"))
10346 (setq org-link-search-failed nil)
10347 (let* ((pos (point))
10348 (ct (org-context))
10349 (a (assoc :link ct))
10350 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10351 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10352 ((looking-at org-any-link-re)
10353 ;; Don't stay stuck at link without an org-link face
10354 (forward-char (if search-backward -1 1))))
10355 (if (funcall srch-fun org-any-link-re nil t)
10356 (progn
10357 (goto-char (match-beginning 0))
10358 (if (outline-invisible-p) (org-show-context)))
10359 (goto-char pos)
10360 (setq org-link-search-failed t)
10361 (message "No further link found"))))
10363 (defun org-previous-link ()
10364 "Move backward to the previous link.
10365 If the link is in hidden text, expose it."
10366 (interactive)
10367 (funcall 'org-next-link t))
10369 (defun org-translate-link (s)
10370 "Translate a link string if a translation function has been defined."
10371 (if (and org-link-translation-function
10372 (fboundp org-link-translation-function)
10373 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10374 (progn
10375 (setq s (funcall org-link-translation-function
10376 (match-string 1 s) (match-string 2 s)))
10377 (concat (car s) ":" (cdr s)))
10380 (defun org-translate-link-from-planner (type path)
10381 "Translate a link from Emacs Planner syntax so that Org can follow it.
10382 This is still an experimental function, your mileage may vary."
10383 (cond
10384 ((member type '("http" "https" "news" "ftp"))
10385 ;; standard Internet links are the same.
10386 nil)
10387 ((and (equal type "irc") (string-match "^//" path))
10388 ;; Planner has two / at the beginning of an irc link, we have 1.
10389 ;; We should have zero, actually....
10390 (setq path (substring path 1)))
10391 ((and (equal type "lisp") (string-match "^/" path))
10392 ;; Planner has a slash, we do not.
10393 (setq type "elisp" path (substring path 1)))
10394 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10395 ;; A typical message link. Planner has the id after the final slash,
10396 ;; we separate it with a hash mark
10397 (setq path (concat (match-string 1 path) "#"
10398 (org-remove-angle-brackets (match-string 2 path))))))
10399 (cons type path))
10401 (defun org-find-file-at-mouse (ev)
10402 "Open file link or URL at mouse."
10403 (interactive "e")
10404 (mouse-set-point ev)
10405 (org-open-at-point 'in-emacs))
10407 (defun org-open-at-mouse (ev)
10408 "Open file link or URL at mouse.
10409 See the docstring of `org-open-file' for details."
10410 (interactive "e")
10411 (mouse-set-point ev)
10412 (if (eq major-mode 'org-agenda-mode)
10413 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10414 (org-open-at-point))
10416 (defvar org-window-config-before-follow-link nil
10417 "The window configuration before following a link.
10418 This is saved in case the need arises to restore it.")
10420 (defvar org-open-link-marker (make-marker)
10421 "Marker pointing to the location where `org-open-at-point' was called.")
10423 ;;;###autoload
10424 (defun org-open-at-point-global ()
10425 "Follow a link like Org-mode does.
10426 This command can be called in any mode to follow a link that has
10427 Org-mode syntax."
10428 (interactive)
10429 (org-run-like-in-org-mode 'org-open-at-point))
10431 ;;;###autoload
10432 (defun org-open-link-from-string (s &optional arg reference-buffer)
10433 "Open a link in the string S, as if it was in Org-mode."
10434 (interactive "sLink: \nP")
10435 (let ((reference-buffer (or reference-buffer (current-buffer))))
10436 (with-temp-buffer
10437 (let ((org-inhibit-startup (not reference-buffer)))
10438 (org-mode)
10439 (insert s)
10440 (goto-char (point-min))
10441 (when reference-buffer
10442 (setq org-link-abbrev-alist-local
10443 (with-current-buffer reference-buffer
10444 org-link-abbrev-alist-local)))
10445 (org-open-at-point arg reference-buffer)))))
10447 (defvar org-open-at-point-functions nil
10448 "Hook that is run when following a link at point.
10450 Functions in this hook must return t if they identify and follow
10451 a link at point. If they don't find anything interesting at point,
10452 they must return nil.")
10454 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10455 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10456 (defun org-open-at-point (&optional arg reference-buffer)
10457 "Open link, timestamp, footnote or tags at point.
10459 When point is on a link, follow it. Normally, files will be
10460 opened by an appropriate application. If the optional prefix
10461 argument ARG is non-nil, Emacs will visit the file. With
10462 a double prefix argument, try to open outside of Emacs, in the
10463 application the system uses for this file type.
10465 When point is on a timestamp, open the agenda at the day
10466 specified.
10468 When point is a footnote definition, move to the first reference
10469 found. If it is on a reference, move to the associated
10470 definition.
10472 When point is on a headline, display a list of every link in the
10473 entry, so it is possible to pick one, or all, of them. If point
10474 is on a tag, call `org-tags-view' instead.
10476 When optional argument REFERENCE-BUFFER is non-nil, it should
10477 specify a buffer from where the link search should happen. This
10478 is used internally by `org-open-link-from-string'."
10479 (interactive "P")
10480 ;; On a code block, open block's results.
10481 (unless (call-interactively #'org-babel-open-src-block-result)
10482 (org-load-modules-maybe)
10483 (move-marker org-open-link-marker (point))
10484 (setq org-window-config-before-follow-link (current-window-configuration))
10485 (org-remove-occur-highlights nil nil t)
10486 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10487 (let* ((context (org-element-context)) type)
10488 ;; On an unsupported type, check if point is contained within
10489 ;; a support one.
10490 (while (and (not (memq (setq type (org-element-type context))
10491 '(headline inlinetask link footnote-definition
10492 footnote-reference timestamp)))
10493 (setq context (org-element-property :parent context))))
10494 (cond
10495 ;; Unsupported context: return an error.
10496 ((not context) (user-error "No link found"))
10497 ;; On a headline or an inlinetask, but not on a timestamp,
10498 ;; a link, a footnote reference or on tags.
10499 ((and (memq type '(headline inlinetask))
10500 ;; Not on tags.
10501 (progn (save-excursion (beginning-of-line)
10502 (looking-at org-complex-heading-regexp))
10503 (or (not (match-beginning 5))
10504 (< (point) (match-beginning 5)))))
10505 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10506 (links (car data))
10507 (links-end (cdr data)))
10508 (if links
10509 (dolist (link (if (stringp links) (list links) links))
10510 (search-forward link nil links-end)
10511 (goto-char (match-beginning 0))
10512 (org-open-at-point))
10513 (require 'org-attach)
10514 (org-attach-reveal 'if-exists))))
10515 ;; Do nothing on white spaces after an object, unless point
10516 ;; is right after it.
10517 ((> (point)
10518 (save-excursion
10519 (goto-char (org-element-property :end context))
10520 (skip-chars-backward " \t")
10521 (point)))
10522 (user-error "No link found"))
10523 ((eq type 'timestamp) (org-follow-timestamp-link))
10524 ;; On tags within a headline or an inlinetask.
10525 ((and (memq type '(headline inlinetask))
10526 (progn (save-excursion (beginning-of-line)
10527 (looking-at org-complex-heading-regexp))
10528 (and (match-beginning 5)
10529 (>= (point) (match-beginning 5)))))
10530 (org-tags-view arg (substring (match-string 5) 0 -1)))
10531 ((eq type 'link)
10532 (let ((type (org-element-property :type context))
10533 (path (org-link-unescape (org-element-property :path context))))
10534 ;; Switch back to REFERENCE-BUFFER needed when called in
10535 ;; a temporary buffer through `org-open-link-from-string'.
10536 (with-current-buffer (or reference-buffer (current-buffer))
10537 (cond
10538 ((equal type "file")
10539 (if (string-match "[*?{]" (file-name-nondirectory path))
10540 (dired path)
10541 ;; Look into `org-link-protocols' in order to find
10542 ;; a DEDICATED-FUNCTION to open file. The function
10543 ;; will be applied on raw link instead of parsed
10544 ;; link due to the limitation in `org-add-link-type'
10545 ;; ("open" function called with a single argument).
10546 ;; If no such function is found, fallback to
10547 ;; `org-open-file'.
10549 ;; Note : "file+emacs" and "file+sys" types are
10550 ;; hard-coded in order to escape the previous
10551 ;; limitation.
10552 (let* ((option (org-element-property :search-option context))
10553 (app (org-element-property :application context))
10554 (dedicated-function
10555 (nth 1 (assoc app org-link-protocols))))
10556 (if dedicated-function
10557 (funcall dedicated-function
10558 (concat path
10559 (and option (concat "::" option))))
10560 (apply #'org-open-file
10561 path
10562 (cond (arg)
10563 ((equal app "emacs") 'emacs)
10564 ((equal app "sys") 'system))
10565 (cond ((not option) nil)
10566 ((org-string-match-p "\\`[0-9]+\\'" option)
10567 (list (string-to-number option)))
10568 (t (list nil
10569 (org-link-unescape option)))))))))
10570 ((assoc type org-link-protocols)
10571 (funcall (nth 1 (assoc type org-link-protocols)) path))
10572 ((equal type "help")
10573 (let ((f-or-v (intern path)))
10574 (cond ((fboundp f-or-v) (describe-function f-or-v))
10575 ((boundp f-or-v) (describe-variable f-or-v))
10576 (t (error "Not a known function or variable")))))
10577 ((equal type "mailto")
10578 (let ((cmd (car org-link-mailto-program))
10579 (args (cdr org-link-mailto-program))
10580 (spec
10581 (format-spec-make
10582 ?a path ; %a is address.
10583 ?s (let ((option ; %s is subject.
10584 (org-element-property
10585 :search-option context)))
10586 (if (not option) "" (org-link-escape option)))))
10587 final-args)
10588 (apply cmd
10589 (dolist (arg args (nreverse final-args))
10590 (if (not (stringp arg)) (push arg final-args)
10591 (push (format-spec arg spec) final-args))))))
10592 ((member type '("http" "https" "ftp" "news"))
10593 (browse-url (org-link-escape-browser (concat type ":" path))))
10594 ((equal type "doi")
10595 (browse-url
10596 (org-link-escape-browser (concat org-doi-server-url path))))
10597 ((equal type "message") (browse-url (concat type ":" path)))
10598 ((equal type "shell")
10599 (let ((buf (generate-new-buffer "*Org Shell Output"))
10600 (cmd path))
10601 (if (or (and (org-string-nw-p
10602 org-confirm-shell-link-not-regexp)
10603 (string-match
10604 org-confirm-shell-link-not-regexp cmd))
10605 (not org-confirm-shell-link-function)
10606 (funcall org-confirm-shell-link-function
10607 (format "Execute \"%s\" in shell? "
10608 (org-add-props cmd nil
10609 'face 'org-warning))))
10610 (progn
10611 (message "Executing %s" cmd)
10612 (shell-command cmd buf)
10613 (when (featurep 'midnight)
10614 (setq clean-buffer-list-kill-buffer-names
10615 (cons buf
10616 clean-buffer-list-kill-buffer-names))))
10617 (error "Abort"))))
10618 ((equal type "elisp")
10619 (let ((cmd path))
10620 (if (or (and (org-string-nw-p
10621 org-confirm-elisp-link-not-regexp)
10622 (org-string-match-p
10623 org-confirm-elisp-link-not-regexp cmd))
10624 (not org-confirm-elisp-link-function)
10625 (funcall org-confirm-elisp-link-function
10626 (format "Execute \"%s\" as elisp? "
10627 (org-add-props cmd nil
10628 'face 'org-warning))))
10629 (message "%s => %s" cmd
10630 (if (eq (string-to-char cmd) ?\()
10631 (eval (read cmd))
10632 (call-interactively (read cmd))))
10633 (error "Abort"))))
10634 ((equal type "id")
10635 (require 'ord-id)
10636 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10637 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10638 (unless (run-hook-with-args-until-success
10639 'org-open-link-functions path)
10640 (if (not arg) (org-mark-ring-push)
10641 (switch-to-buffer-other-window
10642 (org-get-buffer-for-internal-link (current-buffer))))
10643 (let ((cmd `(org-link-search
10644 ,(org-element-property :raw-link context)
10645 ,(cond ((equal arg '(4)) ''occur)
10646 ((equal arg '(16)) ''org-occur))
10647 ,(org-element-property :begin context))))
10648 (condition-case nil
10649 (let ((org-link-search-inhibit-query t))
10650 (eval cmd))
10651 (error (progn (widen) (eval cmd)))))))
10652 (t (browse-url-at-point))))))
10653 ;; On a footnote reference or at a footnote definition's label.
10654 ((or (eq type 'footnote-reference)
10655 (and (eq type 'footnote-definition)
10656 (save-excursion
10657 ;; Do not validate action when point is on the
10658 ;; spaces right after the footnote label, in
10659 ;; order to be on par with behaviour on links.
10660 (skip-chars-forward " \t")
10661 (let ((begin
10662 (org-element-property :contents-begin context)))
10663 (if begin (< (point) begin)
10664 (= (org-element-property :post-affiliated context)
10665 (line-beginning-position)))))))
10666 (org-footnote-action))
10667 (t (user-error "No link found")))))
10668 (move-marker org-open-link-marker nil)
10669 (run-hook-with-args 'org-follow-link-hook)))
10671 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10672 "Offer links in the current entry and return the selected link.
10673 If there is only one link, return it.
10674 If NTH is an integer, return the NTH link found.
10675 If ZERO is a string, check also this string for a link, and if
10676 there is one, return it."
10677 (with-current-buffer buffer
10678 (save-excursion
10679 (save-restriction
10680 (widen)
10681 (goto-char marker)
10682 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10683 "\\(" org-angle-link-re "\\)\\|"
10684 "\\(" org-plain-link-re "\\)"))
10685 (cnt ?0)
10686 (in-emacs (if (integerp nth) nil nth))
10687 have-zero end links link c)
10688 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10689 (push (match-string 0 zero) links)
10690 (setq cnt (1- cnt) have-zero t))
10691 (save-excursion
10692 (org-back-to-heading t)
10693 (setq end (save-excursion (outline-next-heading) (point)))
10694 (while (re-search-forward re end t)
10695 (push (match-string 0) links))
10696 (setq links (org-uniquify (reverse links))))
10697 (cond
10698 ((null links)
10699 (message "No links"))
10700 ((equal (length links) 1)
10701 (setq link (car links)))
10702 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10703 (setq link (nth (if have-zero nth (1- nth)) links)))
10704 (t ; we have to select a link
10705 (save-excursion
10706 (save-window-excursion
10707 (delete-other-windows)
10708 (with-output-to-temp-buffer "*Select Link*"
10709 (mapc (lambda (l)
10710 (if (not (string-match org-bracket-link-regexp l))
10711 (princ (format "[%c] %s\n" (incf cnt)
10712 (org-remove-angle-brackets l)))
10713 (if (match-end 3)
10714 (princ (format "[%c] %s (%s)\n" (incf cnt)
10715 (match-string 3 l) (match-string 1 l)))
10716 (princ (format "[%c] %s\n" (incf cnt)
10717 (match-string 1 l))))))
10718 links))
10719 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10720 (message "Select link to open, RET to open all:")
10721 (setq c (read-char-exclusive))
10722 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10723 (when (equal c ?q) (error "Abort"))
10724 (if (equal c ?\C-m)
10725 (setq link links)
10726 (setq nth (- c ?0))
10727 (if have-zero (setq nth (1+ nth)))
10728 (unless (and (integerp nth) (>= (length links) nth))
10729 (user-error "Invalid link selection"))
10730 (setq link (nth (1- nth) links)))))
10731 (cons link end))))))
10733 ;; TODO: These functions are deprecated since `org-open-at-point'
10734 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10735 (defun org-open-file-with-system (path)
10736 "Open file at PATH using the system way of opening it."
10737 (org-open-file path 'system))
10738 (defun org-open-file-with-emacs (path)
10739 "Open file at PATH in Emacs."
10740 (org-open-file path 'emacs))
10743 ;;; File search
10745 (defvar org-create-file-search-functions nil
10746 "List of functions to construct the right search string for a file link.
10747 These functions are called in turn with point at the location to
10748 which the link should point.
10750 A function in the hook should first test if it would like to
10751 handle this file type, for example by checking the `major-mode'
10752 or the file extension. If it decides not to handle this file, it
10753 should just return nil to give other functions a chance. If it
10754 does handle the file, it must return the search string to be used
10755 when following the link. The search string will be part of the
10756 file link, given after a double colon, and `org-open-at-point'
10757 will automatically search for it. If special measures must be
10758 taken to make the search successful, another function should be
10759 added to the companion hook `org-execute-file-search-functions',
10760 which see.
10762 A function in this hook may also use `setq' to set the variable
10763 `description' to provide a suggestion for the descriptive text to
10764 be used for this link when it gets inserted into an Org-mode
10765 buffer with \\[org-insert-link].")
10767 (defvar org-execute-file-search-functions nil
10768 "List of functions to execute a file search triggered by a link.
10770 Functions added to this hook must accept a single argument, the
10771 search string that was part of the file link, the part after the
10772 double colon. The function must first check if it would like to
10773 handle this search, for example by checking the `major-mode' or
10774 the file extension. If it decides not to handle this search, it
10775 should just return nil to give other functions a chance. If it
10776 does handle the search, it must return a non-nil value to keep
10777 other functions from trying.
10779 Each function can access the current prefix argument through the
10780 variable `current-prefix-arg'. Note that a single prefix is used
10781 to force opening a link in Emacs, so it may be good to only use a
10782 numeric or double prefix to guide the search function.
10784 In case this is needed, a function in this hook can also restore
10785 the window configuration before `org-open-at-point' was called using:
10787 (set-window-configuration org-window-config-before-follow-link)")
10789 (defun org-link-search (s &optional type avoid-pos stealth)
10790 "Search for a link search option.
10791 If S is surrounded by forward slashes, it is interpreted as a
10792 regular expression. In org-mode files, this will create an `org-occur'
10793 sparse tree. In ordinary files, `occur' will be used to list matches.
10794 If the current buffer is in `dired-mode', grep will be used to search
10795 in all files. If AVOID-POS is given, ignore matches near that position.
10797 When optional argument STEALTH is non-nil, do not modify
10798 visibility around point, thus ignoring
10799 `org-show-hierarchy-above', `org-show-following-heading' and
10800 `org-show-siblings' variables."
10801 (let ((case-fold-search t)
10802 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10803 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10804 (append '(("") (" ") ("\t") ("\n"))
10805 org-emphasis-alist)
10806 "\\|") "\\)"))
10807 (pos (point))
10808 (pre nil) (post nil)
10809 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10810 (cond
10811 ;; First check if there are any special search functions
10812 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10813 ;; Now try the builtin stuff
10814 ((and (equal (string-to-char s0) ?#)
10815 (> (length s0) 1)
10816 (save-excursion
10817 (goto-char (point-min))
10818 (and
10819 (re-search-forward
10820 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10821 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10822 (setq type 'dedicated
10823 pos (match-beginning 0))))
10824 ;; There is an exact target for this
10825 (goto-char pos)
10826 (org-back-to-heading t)))
10827 ((save-excursion
10828 (goto-char (point-min))
10829 (and
10830 (re-search-forward
10831 (concat "<<" (regexp-quote s0) ">>") nil t)
10832 (setq type 'dedicated
10833 pos (match-beginning 0))))
10834 ;; There is an exact target for this
10835 (goto-char pos))
10836 ((save-excursion
10837 (goto-char (point-min))
10838 (and
10839 (re-search-forward
10840 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10841 (setq type 'dedicated pos (match-beginning 0))))
10842 ;; Found an element with a matching #+name affiliated keyword.
10843 (goto-char pos))
10844 ((and (string-match "^(\\(.*\\))$" s0)
10845 (save-excursion
10846 (goto-char (point-min))
10847 (and
10848 (re-search-forward
10849 (concat "[^[]" (regexp-quote
10850 (format org-coderef-label-format
10851 (match-string 1 s0))))
10852 nil t)
10853 (setq type 'dedicated
10854 pos (1+ (match-beginning 0))))))
10855 ;; There is a coderef target for this
10856 (goto-char pos))
10857 ((string-match "^/\\(.*\\)/$" s)
10858 ;; A regular expression
10859 (cond
10860 ((derived-mode-p 'org-mode)
10861 (org-occur (match-string 1 s)))
10862 (t (org-do-occur (match-string 1 s)))))
10863 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10864 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10865 (goto-char (point-min))
10866 (cond
10867 ((let (case-fold-search)
10868 (re-search-forward (format org-complex-heading-regexp-format
10869 (regexp-quote s))
10870 nil t))
10871 ;; OK, found a match
10872 (setq type 'dedicated)
10873 (goto-char (match-beginning 0)))
10874 ((and (not org-link-search-inhibit-query)
10875 (eq org-link-search-must-match-exact-headline 'query-to-create)
10876 (y-or-n-p "No match - create this as a new heading? "))
10877 (goto-char (point-max))
10878 (or (bolp) (newline))
10879 (insert "* " s "\n")
10880 (beginning-of-line 0))
10882 (goto-char pos)
10883 (error "No match"))))
10885 ;; A normal search string
10886 (when (equal (string-to-char s) ?*)
10887 ;; Anchor on headlines, post may include tags.
10888 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10889 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10890 s (substring s 1)))
10891 (remove-text-properties
10892 0 (length s)
10893 '(face nil mouse-face nil keymap nil fontified nil) s)
10894 ;; Make a series of regular expressions to find a match
10895 (setq words (org-split-string s "[ \n\r\t]+")
10897 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10898 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10899 "\\)" markers)
10900 re2a_ (concat "\\(" (mapconcat 'downcase words
10901 "[ \t\r\n]+") "\\)[ \t\r\n]")
10902 re2a (concat "[ \t\r\n]" re2a_)
10903 re4_ (concat "\\(" (mapconcat 'downcase words
10904 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10905 re4 (concat "[^a-zA-Z_]" re4_)
10907 re1 (concat pre re2 post)
10908 re3 (concat pre (if pre re4_ re4) post)
10909 re5 (concat pre ".*" re4)
10910 re2 (concat pre re2)
10911 re2a (concat pre (if pre re2a_ re2a))
10912 re4 (concat pre (if pre re4_ re4))
10913 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10914 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10915 re5 "\\)"))
10916 (cond
10917 ((eq type 'org-occur) (org-occur reall))
10918 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10919 (t (goto-char (point-min))
10920 (setq type 'fuzzy)
10921 (if (or (and (org-search-not-self 1 re0 nil t)
10922 (setq type 'dedicated))
10923 (org-search-not-self 1 re1 nil t)
10924 (org-search-not-self 1 re2 nil t)
10925 (org-search-not-self 1 re2a nil t)
10926 (org-search-not-self 1 re3 nil t)
10927 (org-search-not-self 1 re4 nil t)
10928 (org-search-not-self 1 re5 nil t))
10929 (goto-char (match-beginning 1))
10930 (goto-char pos)
10931 (error "No match"))))))
10932 (and (derived-mode-p 'org-mode)
10933 (not stealth)
10934 (org-show-context 'link-search))
10935 type))
10937 (defun org-search-not-self (group &rest args)
10938 "Execute `re-search-forward', but only accept matches that do not
10939 enclose the position of `org-open-link-marker'."
10940 (let ((m org-open-link-marker))
10941 (catch 'exit
10942 (while (apply 're-search-forward args)
10943 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10944 (goto-char (match-end group))
10945 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10946 (> (match-beginning 0) (marker-position m))
10947 (< (match-end 0) (marker-position m)))
10948 (save-match-data
10949 (or (not (org-in-regexp
10950 org-bracket-link-analytic-regexp 1))
10951 (not (match-end 4)) ; no description
10952 (and (<= (match-beginning 4) (point))
10953 (>= (match-end 4) (point))))))
10954 (throw 'exit (point))))))))
10956 (defun org-get-buffer-for-internal-link (buffer)
10957 "Return a buffer to be used for displaying the link target of internal links."
10958 (cond
10959 ((not org-display-internal-link-with-indirect-buffer)
10960 buffer)
10961 ((string-match "(Clone)$" (buffer-name buffer))
10962 (message "Buffer is already a clone, not making another one")
10963 ;; we also do not modify visibility in this case
10964 buffer)
10965 (t ; make a new indirect buffer for displaying the link
10966 (let* ((bn (buffer-name buffer))
10967 (ibn (concat bn "(Clone)"))
10968 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10969 (with-current-buffer ib (org-overview))
10970 ib))))
10972 (defun org-do-occur (regexp &optional cleanup)
10973 "Call the Emacs command `occur'.
10974 If CLEANUP is non-nil, remove the printout of the regular expression
10975 in the *Occur* buffer. This is useful if the regex is long and not useful
10976 to read."
10977 (occur regexp)
10978 (when cleanup
10979 (let ((cwin (selected-window)) win beg end)
10980 (when (setq win (get-buffer-window "*Occur*"))
10981 (select-window win))
10982 (goto-char (point-min))
10983 (when (re-search-forward "match[a-z]+" nil t)
10984 (setq beg (match-end 0))
10985 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10986 (setq end (1- (match-beginning 0)))))
10987 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10988 (goto-char (point-min))
10989 (select-window cwin))))
10991 ;;; The mark ring for links jumps
10993 (defvar org-mark-ring nil
10994 "Mark ring for positions before jumps in Org-mode.")
10995 (defvar org-mark-ring-last-goto nil
10996 "Last position in the mark ring used to go back.")
10997 ;; Fill and close the ring
10998 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10999 (loop for i from 1 to org-mark-ring-length do
11000 (push (make-marker) org-mark-ring))
11001 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11002 org-mark-ring)
11004 (defun org-mark-ring-push (&optional pos buffer)
11005 "Put the current position or POS into the mark ring and rotate it."
11006 (interactive)
11007 (setq pos (or pos (point)))
11008 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11009 (move-marker (car org-mark-ring)
11010 (or pos (point))
11011 (or buffer (current-buffer)))
11012 (message "%s"
11013 (substitute-command-keys
11014 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11016 (defun org-mark-ring-goto (&optional n)
11017 "Jump to the previous position in the mark ring.
11018 With prefix arg N, jump back that many stored positions. When
11019 called several times in succession, walk through the entire ring.
11020 Org-mode commands jumping to a different position in the current file,
11021 or to another Org-mode file, automatically push the old position
11022 onto the ring."
11023 (interactive "p")
11024 (let (p m)
11025 (if (eq last-command this-command)
11026 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11027 (setq p org-mark-ring))
11028 (setq org-mark-ring-last-goto p)
11029 (setq m (car p))
11030 (org-pop-to-buffer-same-window (marker-buffer m))
11031 (goto-char m)
11032 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11034 (defun org-remove-angle-brackets (s)
11035 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11036 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11038 (defun org-add-angle-brackets (s)
11039 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11040 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11042 (defun org-remove-double-quotes (s)
11043 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11044 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11047 ;;; Following specific links
11049 (defun org-follow-timestamp-link ()
11050 "Open an agenda view for the time-stamp date/range at point."
11051 (cond
11052 ((org-at-date-range-p t)
11053 (let ((org-agenda-start-on-weekday)
11054 (t1 (match-string 1))
11055 (t2 (match-string 2)) tt1 tt2)
11056 (setq tt1 (time-to-days (org-time-string-to-time t1))
11057 tt2 (time-to-days (org-time-string-to-time t2)))
11058 (let ((org-agenda-buffer-tmp-name
11059 (format "*Org Agenda(a:%s)"
11060 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11061 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11062 ((org-at-timestamp-p t)
11063 (let ((org-agenda-buffer-tmp-name
11064 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11065 (org-agenda-list nil (time-to-days (org-time-string-to-time
11066 (substring (match-string 1) 0 10)))
11067 1)))
11068 (t (error "This should not happen"))))
11071 ;;; Following file links
11072 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11073 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11074 (declare-function mailcap-mime-info
11075 "mailcap" (string &optional request no-decode))
11076 (defvar org-wait nil)
11077 (defun org-open-file (path &optional in-emacs line search)
11078 "Open the file at PATH.
11079 First, this expands any special file name abbreviations. Then the
11080 configuration variable `org-file-apps' is checked if it contains an
11081 entry for this file type, and if yes, the corresponding command is launched.
11083 If no application is found, Emacs simply visits the file.
11085 With optional prefix argument IN-EMACS, Emacs will visit the file.
11086 With a double \\[universal-argument] \\[universal-argument] \
11087 prefix arg, Org tries to avoid opening in Emacs
11088 and to use an external application to visit the file.
11090 Optional LINE specifies a line to go to, optional SEARCH a string
11091 to search for. If LINE or SEARCH is given, the file will be
11092 opened in Emacs, unless an entry from org-file-apps that makes
11093 use of groups in a regexp matches.
11095 If you want to change the way frames are used when following a
11096 link, please customize `org-link-frame-setup'.
11098 If the file does not exist, an error is thrown."
11099 (let* ((file (if (equal path "")
11100 buffer-file-name
11101 (substitute-in-file-name (expand-file-name path))))
11102 (file-apps (append org-file-apps (org-default-apps)))
11103 (apps (org-remove-if
11104 'org-file-apps-entry-match-against-dlink-p file-apps))
11105 (apps-dlink (org-remove-if-not
11106 'org-file-apps-entry-match-against-dlink-p file-apps))
11107 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11108 (dirp (if remp nil (file-directory-p file)))
11109 (file (if (and dirp org-open-directory-means-index-dot-org)
11110 (concat (file-name-as-directory file) "index.org")
11111 file))
11112 (a-m-a-p (assq 'auto-mode apps))
11113 (dfile (downcase file))
11114 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11115 (link (cond ((and (eq line nil)
11116 (eq search nil))
11117 file)
11118 (line
11119 (concat file "::" (number-to-string line)))
11120 (search
11121 (concat file "::" search))))
11122 (dlink (downcase link))
11123 (old-buffer (current-buffer))
11124 (old-pos (point))
11125 (old-mode major-mode)
11126 ext cmd link-match-data)
11127 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11128 (setq ext (match-string 1 dfile))
11129 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11130 (setq ext (match-string 1 dfile))))
11131 (cond
11132 ((member in-emacs '((16) system))
11133 (setq cmd (cdr (assoc 'system apps))))
11134 (in-emacs (setq cmd 'emacs))
11136 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11137 (and dirp (cdr (assoc 'directory apps)))
11138 ; first, try matching against apps-dlink
11139 ; if we get a match here, store the match data for later
11140 (let ((match (assoc-default dlink apps-dlink
11141 'string-match)))
11142 (if match
11143 (progn (setq link-match-data (match-data))
11144 match)
11145 (progn (setq in-emacs (or in-emacs line search))
11146 nil))) ; if we have no match in apps-dlink,
11147 ; always open the file in emacs if line or search
11148 ; is given (for backwards compatibility)
11149 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11150 'string-match)
11151 (cdr (assoc ext apps))
11152 (cdr (assoc t apps))))))
11153 (when (eq cmd 'system)
11154 (setq cmd (cdr (assoc 'system apps))))
11155 (when (eq cmd 'default)
11156 (setq cmd (cdr (assoc t apps))))
11157 (when (eq cmd 'mailcap)
11158 (require 'mailcap)
11159 (mailcap-parse-mailcaps)
11160 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11161 (command (mailcap-mime-info mime-type)))
11162 (if (stringp command)
11163 (setq cmd command)
11164 (setq cmd 'emacs))))
11165 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11166 (not (file-exists-p file))
11167 (not org-open-non-existing-files))
11168 (user-error "No such file: %s" file))
11169 (cond
11170 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11171 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11172 (while (string-match "['\"]%s['\"]" cmd)
11173 (setq cmd (replace-match "%s" t t cmd)))
11174 (while (string-match "%s" cmd)
11175 (setq cmd (replace-match
11176 (save-match-data
11177 (shell-quote-argument
11178 (convert-standard-filename file)))
11179 t t cmd)))
11181 ;; Replace "%1", "%2" etc. in command with group matches from regex
11182 (save-match-data
11183 (let ((match-index 1)
11184 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11185 (set-match-data link-match-data)
11186 (while (<= match-index number-of-groups)
11187 (let ((regex (concat "%" (number-to-string match-index)))
11188 (replace-with (match-string match-index dlink)))
11189 (while (string-match regex cmd)
11190 (setq cmd (replace-match replace-with t t cmd))))
11191 (setq match-index (+ match-index 1)))))
11193 (save-window-excursion
11194 (message "Running %s...done" cmd)
11195 (start-process-shell-command cmd nil cmd)
11196 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11197 ((or (stringp cmd)
11198 (eq cmd 'emacs))
11199 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11200 (widen)
11201 (if line (progn (org-goto-line line)
11202 (if (derived-mode-p 'org-mode)
11203 (org-reveal)))
11204 (if search (org-link-search search))))
11205 ((consp cmd)
11206 (let ((file (convert-standard-filename file)))
11207 (save-match-data
11208 (set-match-data link-match-data)
11209 (eval cmd))))
11210 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11211 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11212 (or (not (equal old-buffer (current-buffer)))
11213 (not (equal old-pos (point))))
11214 (org-mark-ring-push old-pos old-buffer))))
11216 (defun org-file-apps-entry-match-against-dlink-p (entry)
11217 "This function returns non-nil if `entry' uses a regular
11218 expression which should be matched against the whole link by
11219 org-open-file.
11221 It assumes that is the case when the entry uses a regular
11222 expression which has at least one grouping construct and the
11223 action is either a lisp form or a command string containing
11224 '%1', i.e. using at least one subexpression match as a
11225 parameter."
11226 (let ((selector (car entry))
11227 (action (cdr entry)))
11228 (if (stringp selector)
11229 (and (> (regexp-opt-depth selector) 0)
11230 (or (and (stringp action)
11231 (string-match "%[0-9]" action))
11232 (consp action)))
11233 nil)))
11235 (defun org-default-apps ()
11236 "Return the default applications for this operating system."
11237 (cond
11238 ((eq system-type 'darwin)
11239 org-file-apps-defaults-macosx)
11240 ((eq system-type 'windows-nt)
11241 org-file-apps-defaults-windowsnt)
11242 (t org-file-apps-defaults-gnu)))
11244 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11245 "Convert extensions to regular expressions in the cars of LIST.
11246 Also, weed out any non-string entries, because the return value is used
11247 only for regexp matching.
11248 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11249 point to the symbol `emacs', indicating that the file should
11250 be opened in Emacs."
11251 (append
11252 (delq nil
11253 (mapcar (lambda (x)
11254 (if (not (stringp (car x)))
11256 (if (string-match "\\W" (car x))
11258 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11259 list))
11260 (if add-auto-mode
11261 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11263 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11264 (defun org-file-remote-p (file)
11265 "Test whether FILE specifies a location on a remote system.
11266 Return non-nil if the location is indeed remote.
11268 For example, the filename \"/user@host:/foo\" specifies a location
11269 on the system \"/user@host:\"."
11270 (cond ((fboundp 'file-remote-p)
11271 (file-remote-p file))
11272 ((fboundp 'tramp-handle-file-remote-p)
11273 (tramp-handle-file-remote-p file))
11274 ((and (boundp 'ange-ftp-name-format)
11275 (string-match (car ange-ftp-name-format) file))
11276 t)))
11279 ;;;; Refiling
11281 (defun org-get-org-file ()
11282 "Read a filename, with default directory `org-directory'."
11283 (let ((default (or org-default-notes-file remember-data-file)))
11284 (read-file-name (format "File name [%s]: " default)
11285 (file-name-as-directory org-directory)
11286 default)))
11288 (defun org-notes-order-reversed-p ()
11289 "Check if the current file should receive notes in reversed order."
11290 (cond
11291 ((not org-reverse-note-order) nil)
11292 ((eq t org-reverse-note-order) t)
11293 ((not (listp org-reverse-note-order)) nil)
11294 (t (catch 'exit
11295 (let ((all org-reverse-note-order)
11296 entry)
11297 (while (setq entry (pop all))
11298 (if (string-match (car entry) buffer-file-name)
11299 (throw 'exit (cdr entry))))
11300 nil)))))
11302 (defvar org-refile-target-table nil
11303 "The list of refile targets, created by `org-refile'.")
11305 (defvar org-agenda-new-buffers nil
11306 "Buffers created to visit agenda files.")
11308 (defvar org-refile-cache nil
11309 "Cache for refile targets.")
11311 (defvar org-refile-markers nil
11312 "All the markers used for caching refile locations.")
11314 (defun org-refile-marker (pos)
11315 "Get a new refile marker, but only if caching is in use."
11316 (if (not org-refile-use-cache)
11318 (let ((m (make-marker)))
11319 (move-marker m pos)
11320 (push m org-refile-markers)
11321 m)))
11323 (defun org-refile-cache-clear ()
11324 "Clear the refile cache and disable all the markers."
11325 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11326 (setq org-refile-markers nil)
11327 (setq org-refile-cache nil)
11328 (message "Refile cache has been cleared"))
11330 (defun org-refile-cache-check-set (set)
11331 "Check if all the markers in the cache still have live buffers."
11332 (let (marker)
11333 (catch 'exit
11334 (while (and set (setq marker (nth 3 (pop set))))
11335 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11336 (when (and marker (null (marker-buffer marker)))
11337 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11338 (sit-for 3)
11339 (throw 'exit nil)))
11340 t)))
11342 (defun org-refile-cache-put (set &rest identifiers)
11343 "Push the refile targets SET into the cache, under IDENTIFIERS."
11344 (let* ((key (sha1 (prin1-to-string identifiers)))
11345 (entry (assoc key org-refile-cache)))
11346 (if entry
11347 (setcdr entry set)
11348 (push (cons key set) org-refile-cache))))
11350 (defun org-refile-cache-get (&rest identifiers)
11351 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11352 (cond
11353 ((not org-refile-cache) nil)
11354 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11356 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11357 org-refile-cache))))
11358 (and set (org-refile-cache-check-set set) set)))))
11360 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11361 "Produce a table with refile targets."
11362 (let ((case-fold-search nil)
11363 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11364 (entries (or org-refile-targets '((nil . (:level . 1)))))
11365 targets tgs txt re files f desc descre fast-path-p level pos0)
11366 (message "Getting targets...")
11367 (with-current-buffer (or default-buffer (current-buffer))
11368 (while (setq entry (pop entries))
11369 (setq files (car entry) desc (cdr entry))
11370 (setq fast-path-p nil)
11371 (cond
11372 ((null files) (setq files (list (current-buffer))))
11373 ((eq files 'org-agenda-files)
11374 (setq files (org-agenda-files 'unrestricted)))
11375 ((and (symbolp files) (fboundp files))
11376 (setq files (funcall files)))
11377 ((and (symbolp files) (boundp files))
11378 (setq files (symbol-value files))))
11379 (if (stringp files) (setq files (list files)))
11380 (cond
11381 ((eq (car desc) :tag)
11382 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11383 ((eq (car desc) :todo)
11384 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11385 ((eq (car desc) :regexp)
11386 (setq descre (cdr desc)))
11387 ((eq (car desc) :level)
11388 (setq descre (concat "^\\*\\{" (number-to-string
11389 (if org-odd-levels-only
11390 (1- (* 2 (cdr desc)))
11391 (cdr desc)))
11392 "\\}[ \t]")))
11393 ((eq (car desc) :maxlevel)
11394 (setq fast-path-p t)
11395 (setq descre (concat "^\\*\\{1," (number-to-string
11396 (if org-odd-levels-only
11397 (1- (* 2 (cdr desc)))
11398 (cdr desc)))
11399 "\\}[ \t]")))
11400 (t (error "Bad refiling target description %s" desc)))
11401 (while (setq f (pop files))
11402 (with-current-buffer
11403 (if (bufferp f) f (org-get-agenda-file-buffer f))
11405 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11406 (progn
11407 (if (bufferp f) (setq f (buffer-file-name
11408 (buffer-base-buffer f))))
11409 (setq f (and f (expand-file-name f)))
11410 (if (eq org-refile-use-outline-path 'file)
11411 (push (list (file-name-nondirectory f) f nil nil) tgs))
11412 (save-excursion
11413 (save-restriction
11414 (widen)
11415 (goto-char (point-min))
11416 (while (re-search-forward descre nil t)
11417 (goto-char (setq pos0 (point-at-bol)))
11418 (catch 'next
11419 (when org-refile-target-verify-function
11420 (save-match-data
11421 (or (funcall org-refile-target-verify-function)
11422 (throw 'next t))))
11423 (when (and (looking-at org-complex-heading-regexp)
11424 (not (member (match-string 4) excluded-entries))
11425 (match-string 4))
11426 (setq level (org-reduced-level
11427 (- (match-end 1) (match-beginning 1)))
11428 txt (org-link-display-format (match-string 4))
11429 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11430 re (format org-complex-heading-regexp-format
11431 (regexp-quote (match-string 4))))
11432 (when org-refile-use-outline-path
11433 (setq txt (mapconcat
11434 'org-protect-slash
11435 (append
11436 (if (eq org-refile-use-outline-path
11437 'file)
11438 (list (file-name-nondirectory
11439 (buffer-file-name
11440 (buffer-base-buffer))))
11441 (if (eq org-refile-use-outline-path
11442 'full-file-path)
11443 (list (buffer-file-name
11444 (buffer-base-buffer)))))
11445 (org-get-outline-path fast-path-p
11446 level txt)
11447 (list txt))
11448 "/")))
11449 (push (list txt f re (org-refile-marker (point)))
11450 tgs)))
11451 (when (= (point) pos0)
11452 ;; verification function has not moved point
11453 (goto-char (point-at-eol))))))))
11454 (when org-refile-use-cache
11455 (org-refile-cache-put tgs (buffer-file-name) descre))
11456 (setq targets (append tgs targets))))))
11457 (message "Getting targets...done")
11458 (nreverse targets)))
11460 (defun org-protect-slash (s)
11461 (while (string-match "/" s)
11462 (setq s (replace-match "\\" t t s)))
11465 (defvar org-olpa (make-vector 20 nil))
11467 (defun org-get-outline-path (&optional fastp level heading)
11468 "Return the outline path to the current entry, as a list.
11470 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11471 routine which makes outline path derivations for an entire file,
11472 avoiding backtracing. Refile target collection makes use of that."
11473 (if fastp
11474 (progn
11475 (if (> level 19)
11476 (error "Outline path failure, more than 19 levels"))
11477 (loop for i from level upto 19 do
11478 (aset org-olpa i nil))
11479 (prog1
11480 (delq nil (append org-olpa nil))
11481 (aset org-olpa level heading)))
11482 (let (rtn case-fold-search)
11483 (save-excursion
11484 (save-restriction
11485 (widen)
11486 (while (org-up-heading-safe)
11487 (when (looking-at org-complex-heading-regexp)
11488 (push (org-trim
11489 (replace-regexp-in-string
11490 ;; Remove statistical/checkboxes cookies
11491 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11492 (org-match-string-no-properties 4)))
11493 rtn)))
11494 rtn)))))
11496 (defun org-format-outline-path (path &optional width prefix separator)
11497 "Format the outline path PATH for display.
11498 WIDTH is the maximum number of characters that is available.
11499 PREFIX is a prefix to be included in the returned string,
11500 such as the file name.
11501 SEPARATOR is inserted between the different parts of the path,
11502 the default is \"/\"."
11503 (setq width (or width 79))
11504 (if prefix (setq width (- width (length prefix))))
11505 (if (not path)
11506 (or prefix "")
11507 (let* ((nsteps (length path))
11508 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11509 (maxwidth (if (<= total-width width)
11510 10000 ;; everything fits
11511 ;; we need to shorten the level headings
11512 (/ (- width nsteps) nsteps)))
11513 (org-odd-levels-only nil)
11514 (n 0)
11515 (total (1+ (length prefix))))
11516 (setq maxwidth (max maxwidth 10))
11517 (concat prefix
11518 (if prefix (or separator "/"))
11519 (mapconcat
11520 (lambda (h)
11521 (setq n (1+ n))
11522 (if (and (= n nsteps) (< maxwidth 10000))
11523 (setq maxwidth (- total-width total)))
11524 (if (< (length h) maxwidth)
11525 (progn (setq total (+ total (length h) 1)) h)
11526 (setq h (substring h 0 (- maxwidth 2))
11527 total (+ total maxwidth 1))
11528 (if (string-match "[ \t]+\\'" h)
11529 (setq h (substring h 0 (match-beginning 0))))
11530 (setq h (concat h "..")))
11531 (org-add-props h nil 'face
11532 (nth (% (1- n) org-n-level-faces)
11533 org-level-faces))
11535 path (or separator "/"))))))
11537 (defun org-display-outline-path (&optional file current separator just-return-string)
11538 "Display the current outline path in the echo area.
11540 If FILE is non-nil, prepend the output with the file name.
11541 If CURRENT is non-nil, append the current heading to the output.
11542 SEPARATOR is passed through to `org-format-outline-path'. It separates
11543 the different parts of the path and defaults to \"/\".
11544 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11545 (interactive "P")
11546 (let* (case-fold-search
11547 (bfn (buffer-file-name (buffer-base-buffer)))
11548 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11549 res)
11550 (if current (setq path (append path
11551 (save-excursion
11552 (org-back-to-heading t)
11553 (if (looking-at org-complex-heading-regexp)
11554 (list (match-string 4)))))))
11555 (setq res
11556 (org-format-outline-path
11557 path
11558 (1- (frame-width))
11559 (and file bfn (concat (file-name-nondirectory bfn) separator))
11560 separator))
11561 (if just-return-string
11562 (org-no-properties res)
11563 (org-unlogged-message "%s" res))))
11565 (defvar org-refile-history nil
11566 "History for refiling operations.")
11568 (defvar org-after-refile-insert-hook nil
11569 "Hook run after `org-refile' has inserted its stuff at the new location.
11570 Note that this is still *before* the stuff will be removed from
11571 the *old* location.")
11573 (defvar org-capture-last-stored-marker)
11574 (defvar org-refile-keep nil
11575 "Non-nil means `org-refile' will copy instead of refile.")
11577 (defun org-copy ()
11578 "Like `org-refile', but copy."
11579 (interactive)
11580 (let ((org-refile-keep t))
11581 (funcall 'org-refile nil nil nil "Copy")))
11583 (defun org-refile (&optional arg default-buffer rfloc msg)
11584 "Move the entry or entries at point to another heading.
11585 The list of target headings is compiled using the information in
11586 `org-refile-targets', which see.
11588 At the target location, the entry is filed as a subitem of the
11589 target heading. Depending on `org-reverse-note-order', the new
11590 subitem will either be the first or the last subitem.
11592 If there is an active region, all entries in that region will be
11593 refiled. However, the region must fulfill the requirement that
11594 the first heading sets the top-level of the moved text.
11596 With prefix arg ARG, the command will only visit the target
11597 location and not actually move anything.
11599 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11600 refiling operation has put the subtree.
11602 With a numeric prefix argument of `2', refile to the running clock.
11604 With a numeric prefix argument of `3', emulate `org-refile-keep'
11605 being set to `t' and copy to the target location, don't move it.
11606 Beware that keeping refiled entries may result in duplicated ID
11607 properties.
11609 RFLOC can be a refile location obtained in a different way.
11611 MSG is a string to replace \"Refile\" in the default prompt with
11612 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11614 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11616 If you are using target caching (see `org-refile-use-cache'), you
11617 have to clear the target cache in order to find new targets.
11618 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11619 prefix argument (`C-u C-u C-u C-c C-w')."
11620 (interactive "P")
11621 (if (member arg '(0 (64)))
11622 (org-refile-cache-clear)
11623 (let* ((actionmsg (cond (msg msg)
11624 ((equal arg 3) "Refile (and keep)")
11625 (t "Refile")))
11626 (cbuf (current-buffer))
11627 (regionp (org-region-active-p))
11628 (region-start (and regionp (region-beginning)))
11629 (region-end (and regionp (region-end)))
11630 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11631 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11632 pos it nbuf file re level reversed)
11633 (setq last-command nil)
11634 (when regionp
11635 (goto-char region-start)
11636 (or (bolp) (goto-char (point-at-bol)))
11637 (setq region-start (point))
11638 (unless (or (org-kill-is-subtree-p
11639 (buffer-substring region-start region-end))
11640 (prog1 org-refile-active-region-within-subtree
11641 (let ((s (point-at-eol)))
11642 (org-toggle-heading)
11643 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11644 (user-error "The region is not a (sequence of) subtree(s)")))
11645 (if (equal arg '(16))
11646 (org-refile-goto-last-stored)
11647 (when (or
11648 (and (equal arg 2)
11649 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11650 (prog1
11651 (setq it (list (or org-clock-heading "running clock")
11652 (buffer-file-name
11653 (marker-buffer org-clock-hd-marker))
11655 (marker-position org-clock-hd-marker)))
11656 (setq arg nil)))
11657 (setq it (or rfloc
11658 (let (heading-text)
11659 (save-excursion
11660 (unless (and arg (listp arg))
11661 (org-back-to-heading t)
11662 (setq heading-text
11663 (replace-regexp-in-string
11664 org-bracket-link-regexp
11665 "\\3"
11666 (nth 4 (org-heading-components)))))
11667 (org-refile-get-location
11668 (cond ((and arg (listp arg)) "Goto")
11669 (regionp (concat actionmsg " region to"))
11670 (t (concat actionmsg " subtree \""
11671 heading-text "\" to")))
11672 default-buffer
11673 (and (not (equal '(4) arg))
11674 org-refile-allow-creating-parent-nodes)
11675 arg))))))
11676 (setq file (nth 1 it)
11677 re (nth 2 it)
11678 pos (nth 3 it))
11679 (if (and (not arg)
11681 (equal (buffer-file-name) file)
11682 (if regionp
11683 (and (>= pos region-start)
11684 (<= pos region-end))
11685 (and (>= pos (point))
11686 (< pos (save-excursion
11687 (org-end-of-subtree t t))))))
11688 (error "Cannot refile to position inside the tree or region"))
11689 (setq nbuf (or (find-buffer-visiting file)
11690 (find-file-noselect file)))
11691 (if (and arg (not (equal arg 3)))
11692 (progn
11693 (org-pop-to-buffer-same-window nbuf)
11694 (goto-char pos)
11695 (org-show-context 'org-goto))
11696 (if regionp
11697 (progn
11698 (org-kill-new (buffer-substring region-start region-end))
11699 (org-save-markers-in-region region-start region-end))
11700 (org-copy-subtree 1 nil t))
11701 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11702 (find-file-noselect file)))
11703 (setq reversed (org-notes-order-reversed-p))
11704 (save-excursion
11705 (save-restriction
11706 (widen)
11707 (if pos
11708 (progn
11709 (goto-char pos)
11710 (looking-at org-outline-regexp)
11711 (setq level (org-get-valid-level (funcall outline-level) 1))
11712 (goto-char
11713 (if reversed
11714 (or (outline-next-heading) (point-max))
11715 (or (save-excursion (org-get-next-sibling))
11716 (org-end-of-subtree t t)
11717 (point-max)))))
11718 (setq level 1)
11719 (if (not reversed)
11720 (goto-char (point-max))
11721 (goto-char (point-min))
11722 (or (outline-next-heading) (goto-char (point-max)))))
11723 (if (not (bolp)) (newline))
11724 (org-paste-subtree level)
11725 (when org-log-refile
11726 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11727 (unless (eq org-log-refile 'note)
11728 (save-excursion (org-add-log-note))))
11729 (and org-auto-align-tags
11730 (let ((org-loop-over-headlines-in-active-region nil))
11731 (org-set-tags nil t)))
11732 (let ((bookmark-name (plist-get org-bookmark-names-plist
11733 :last-refile)))
11734 (when bookmark-name
11735 (with-demoted-errors
11736 (bookmark-set bookmark-name))))
11737 ;; If we are refiling for capture, make sure that the
11738 ;; last-capture pointers point here
11739 (when (org-bound-and-true-p org-refile-for-capture)
11740 (let ((bookmark-name (plist-get org-bookmark-names-plist
11741 :last-capture-marker)))
11742 (when bookmark-name
11743 (with-demoted-errors
11744 (bookmark-set bookmark-name))))
11745 (move-marker org-capture-last-stored-marker (point)))
11746 (if (fboundp 'deactivate-mark) (deactivate-mark))
11747 (run-hooks 'org-after-refile-insert-hook))))
11748 (unless org-refile-keep
11749 (if regionp
11750 (delete-region (point) (+ (point) (- region-end region-start)))
11751 (delete-region
11752 (and (org-back-to-heading t) (point))
11753 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11754 (when (featurep 'org-inlinetask)
11755 (org-inlinetask-remove-END-maybe))
11756 (setq org-markers-to-move nil)
11757 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11759 (defun org-refile-goto-last-stored ()
11760 "Go to the location where the last refile was stored."
11761 (interactive)
11762 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11763 (message "This is the location of the last refile"))
11765 (defun org-refile--get-location (refloc tbl)
11766 "When user refile to REFLOC, find the associated target in TBL.
11767 Also check `org-refile-target-table'."
11768 (car (delq
11770 (mapcar
11771 (lambda (r) (or (assoc r tbl)
11772 (assoc r org-refile-target-table)))
11773 (list (replace-regexp-in-string "/$" "" refloc)
11774 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11776 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11777 no-exclude)
11778 "Prompt the user for a refile location, using PROMPT.
11779 PROMPT should not be suffixed with a colon and a space, because
11780 this function appends the default value from
11781 `org-refile-history' automatically, if that is not empty.
11782 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11783 this is used for the GOTO interface."
11784 (let ((org-refile-targets org-refile-targets)
11785 (org-refile-use-outline-path org-refile-use-outline-path)
11786 excluded-entries)
11787 (when (and (derived-mode-p 'org-mode)
11788 (not org-refile-use-cache)
11789 (not no-exclude))
11790 (org-map-tree
11791 (lambda()
11792 (setq excluded-entries
11793 (append excluded-entries (list (org-get-heading t t)))))))
11794 (setq org-refile-target-table
11795 (org-refile-get-targets default-buffer excluded-entries)))
11796 (unless org-refile-target-table
11797 (user-error "No refile targets"))
11798 (let* ((cbuf (current-buffer))
11799 (partial-completion-mode nil)
11800 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11801 (cfunc (if (and org-refile-use-outline-path
11802 org-outline-path-complete-in-steps)
11803 'org-olpath-completing-read
11804 'org-icompleting-read))
11805 (extra (if org-refile-use-outline-path "/" ""))
11806 (cbnex (concat (buffer-name) extra))
11807 (filename (and cfn (expand-file-name cfn)))
11808 (tbl (mapcar
11809 (lambda (x)
11810 (if (and (not (member org-refile-use-outline-path
11811 '(file full-file-path)))
11812 (not (equal filename (nth 1 x))))
11813 (cons (concat (car x) extra " ("
11814 (file-name-nondirectory (nth 1 x)) ")")
11815 (cdr x))
11816 (cons (concat (car x) extra) (cdr x))))
11817 org-refile-target-table))
11818 (completion-ignore-case t)
11819 cdef
11820 (prompt (concat prompt
11821 (or (and (car org-refile-history)
11822 (concat " (default " (car org-refile-history) ")"))
11823 (and (assoc cbnex tbl) (setq cdef cbnex)
11824 (concat " (default " cbnex ")"))) ": "))
11825 pa answ parent-target child parent old-hist)
11826 (setq old-hist org-refile-history)
11827 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11828 nil 'org-refile-history (or cdef (car org-refile-history))))
11829 (if (setq pa (org-refile--get-location answ tbl))
11830 (progn
11831 (org-refile-check-position pa)
11832 (when (or (not org-refile-history)
11833 (not (eq old-hist org-refile-history))
11834 (not (equal (car pa) (car org-refile-history))))
11835 (setq org-refile-history
11836 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11837 org-refile-history
11838 (cdr org-refile-history))))
11839 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11840 (pop org-refile-history)))
11842 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11843 (progn
11844 (setq parent (match-string 1 answ)
11845 child (match-string 2 answ))
11846 (setq parent-target (org-refile--get-location parent tbl))
11847 (when (and parent-target
11848 (or (eq new-nodes t)
11849 (and (eq new-nodes 'confirm)
11850 (y-or-n-p (format "Create new node \"%s\"? "
11851 child)))))
11852 (org-refile-new-child parent-target child)))
11853 (user-error "Invalid target location")))))
11855 (declare-function org-string-nw-p "org-macs" (s))
11856 (defun org-refile-check-position (refile-pointer)
11857 "Check if the refile pointer matches the headline to which it points."
11858 (let* ((file (nth 1 refile-pointer))
11859 (re (nth 2 refile-pointer))
11860 (pos (nth 3 refile-pointer))
11861 buffer)
11862 (if (and (not (markerp pos)) (not file))
11863 (if file
11864 (user-error "Please save the buffer to a file before refiling")
11865 (user-error "Please indicate a target file in the refile path"))
11866 (when (org-string-nw-p re)
11867 (setq buffer (if (markerp pos)
11868 (marker-buffer pos)
11869 (or (find-buffer-visiting file)
11870 (find-file-noselect file))))
11871 (with-current-buffer buffer
11872 (save-excursion
11873 (save-restriction
11874 (widen)
11875 (goto-char pos)
11876 (beginning-of-line 1)
11877 (unless (org-looking-at-p re)
11878 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11880 (defun org-refile-new-child (parent-target child)
11881 "Use refile target PARENT-TARGET to add new CHILD below it."
11882 (unless parent-target
11883 (error "Cannot find parent for new node"))
11884 (let ((file (nth 1 parent-target))
11885 (pos (nth 3 parent-target))
11886 level)
11887 (with-current-buffer (or (find-buffer-visiting file)
11888 (find-file-noselect file))
11889 (save-excursion
11890 (save-restriction
11891 (widen)
11892 (if pos
11893 (goto-char pos)
11894 (goto-char (point-max))
11895 (if (not (bolp)) (newline)))
11896 (when (looking-at org-outline-regexp)
11897 (setq level (funcall outline-level))
11898 (org-end-of-subtree t t))
11899 (org-back-over-empty-lines)
11900 (insert "\n" (make-string
11901 (if pos (org-get-valid-level level 1) 1) ?*)
11902 " " child "\n")
11903 (beginning-of-line 0)
11904 (list (concat (car parent-target) "/" child) file "" (point)))))))
11906 (defun org-olpath-completing-read (prompt collection &rest args)
11907 "Read an outline path like a file name."
11908 (let ((thetable collection)
11909 (org-completion-use-ido nil) ; does not work with ido.
11910 (org-completion-use-iswitchb nil)) ; or iswitchb
11911 (apply
11912 'org-icompleting-read prompt
11913 (lambda (string predicate &optional flag)
11914 (let (rtn r f (l (length string)))
11915 (cond
11916 ((eq flag nil)
11917 ;; try completion
11918 (try-completion string thetable))
11919 ((eq flag t)
11920 ;; all-completions
11921 (setq rtn (all-completions string thetable predicate))
11922 (mapcar
11923 (lambda (x)
11924 (setq r (substring x l))
11925 (if (string-match " ([^)]*)$" x)
11926 (setq f (match-string 0 x))
11927 (setq f ""))
11928 (if (string-match "/" r)
11929 (concat string (substring r 0 (match-end 0)) f)
11931 rtn))
11932 ((eq flag 'lambda)
11933 ;; exact match?
11934 (assoc string thetable)))))
11935 args)))
11937 ;;;; Dynamic blocks
11939 (defun org-find-dblock (name)
11940 "Find the first dynamic block with name NAME in the buffer.
11941 If not found, stay at current position and return nil."
11942 (let ((case-fold-search t) pos)
11943 (save-excursion
11944 (goto-char (point-min))
11945 (setq pos (and (re-search-forward
11946 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11947 (match-beginning 0))))
11948 (if pos (goto-char pos))
11949 pos))
11951 (defun org-create-dblock (plist)
11952 "Create a dynamic block section, with parameters taken from PLIST.
11953 PLIST must contain a :name entry which is used as name of the block."
11954 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11955 (end-of-line 1)
11956 (newline))
11957 (let ((col (current-column))
11958 (name (plist-get plist :name)))
11959 (insert "#+BEGIN: " name)
11960 (while plist
11961 (if (eq (car plist) :name)
11962 (setq plist (cddr plist))
11963 (insert " " (prin1-to-string (pop plist)))))
11964 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11965 (beginning-of-line -2)))
11967 (defun org-prepare-dblock ()
11968 "Prepare dynamic block for refresh.
11969 This empties the block, puts the cursor at the insert position and returns
11970 the property list including an extra property :name with the block name."
11971 (unless (looking-at org-dblock-start-re)
11972 (user-error "Not at a dynamic block"))
11973 (let* ((begdel (1+ (match-end 0)))
11974 (name (org-no-properties (match-string 1)))
11975 (params (append (list :name name)
11976 (read (concat "(" (match-string 3) ")")))))
11977 (save-excursion
11978 (beginning-of-line 1)
11979 (skip-chars-forward " \t")
11980 (setq params (plist-put params :indentation-column (current-column))))
11981 (unless (re-search-forward org-dblock-end-re nil t)
11982 (error "Dynamic block not terminated"))
11983 (setq params
11984 (append params
11985 (list :content (buffer-substring
11986 begdel (match-beginning 0)))))
11987 (delete-region begdel (match-beginning 0))
11988 (goto-char begdel)
11989 (open-line 1)
11990 params))
11992 (defun org-map-dblocks (&optional command)
11993 "Apply COMMAND to all dynamic blocks in the current buffer.
11994 If COMMAND is not given, use `org-update-dblock'."
11995 (let ((cmd (or command 'org-update-dblock)))
11996 (save-excursion
11997 (goto-char (point-min))
11998 (while (re-search-forward org-dblock-start-re nil t)
11999 (goto-char (match-beginning 0))
12000 (save-excursion
12001 (condition-case nil
12002 (funcall cmd)
12003 (error (message "Error during update of dynamic block"))))
12004 (unless (re-search-forward org-dblock-end-re nil t)
12005 (error "Dynamic block not terminated"))))))
12007 (defun org-dblock-update (&optional arg)
12008 "User command for updating dynamic blocks.
12009 Update the dynamic block at point. With prefix ARG, update all dynamic
12010 blocks in the buffer."
12011 (interactive "P")
12012 (if arg
12013 (org-update-all-dblocks)
12014 (or (looking-at org-dblock-start-re)
12015 (org-beginning-of-dblock))
12016 (org-update-dblock)))
12018 (defun org-update-dblock ()
12019 "Update the dynamic block at point.
12020 This means to empty the block, parse for parameters and then call
12021 the correct writing function."
12022 (interactive)
12023 (save-window-excursion
12024 (let* ((pos (point))
12025 (line (org-current-line))
12026 (params (org-prepare-dblock))
12027 (name (plist-get params :name))
12028 (indent (plist-get params :indentation-column))
12029 (cmd (intern (concat "org-dblock-write:" name))))
12030 (message "Updating dynamic block `%s' at line %d..." name line)
12031 (funcall cmd params)
12032 (message "Updating dynamic block `%s' at line %d...done" name line)
12033 (goto-char pos)
12034 (when (and indent (> indent 0))
12035 (setq indent (make-string indent ?\ ))
12036 (save-excursion
12037 (org-beginning-of-dblock)
12038 (forward-line 1)
12039 (while (not (looking-at org-dblock-end-re))
12040 (insert indent)
12041 (beginning-of-line 2))
12042 (when (looking-at org-dblock-end-re)
12043 (and (looking-at "[ \t]+")
12044 (replace-match ""))
12045 (insert indent)))))))
12047 (defun org-beginning-of-dblock ()
12048 "Find the beginning of the dynamic block at point.
12049 Error if there is no such block at point."
12050 (let ((pos (point))
12051 beg)
12052 (end-of-line 1)
12053 (if (and (re-search-backward org-dblock-start-re nil t)
12054 (setq beg (match-beginning 0))
12055 (re-search-forward org-dblock-end-re nil t)
12056 (> (match-end 0) pos))
12057 (goto-char beg)
12058 (goto-char pos)
12059 (error "Not in a dynamic block"))))
12061 (defun org-update-all-dblocks ()
12062 "Update all dynamic blocks in the buffer.
12063 This function can be used in a hook."
12064 (interactive)
12065 (when (derived-mode-p 'org-mode)
12066 (org-map-dblocks 'org-update-dblock)))
12069 ;;;; Completion
12071 (declare-function org-export-backend-name "org-export" (cl-x))
12072 (declare-function org-export-backend-options "org-export" (cl-x))
12073 (defun org-get-export-keywords ()
12074 "Return a list of all currently understood export keywords.
12075 Export keywords include options, block names, attributes and
12076 keywords relative to each registered export back-end."
12077 (let (keywords)
12078 (dolist (backend
12079 (org-bound-and-true-p org-export--registered-backends)
12080 (delq nil keywords))
12081 ;; Back-end name (for keywords, like #+LATEX:)
12082 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12083 (dolist (option-entry (org-export-backend-options backend))
12084 ;; Back-end options.
12085 (push (nth 1 option-entry) keywords)))))
12087 (defconst org-options-keywords
12088 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12089 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12090 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12091 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12092 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12094 (defcustom org-structure-template-alist
12095 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12096 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12097 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12098 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12099 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12100 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12101 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12102 "<literal style=\"latex\">\n?\n</literal>")
12103 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12104 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12105 "<literal style=\"html\">\n?\n</literal>")
12106 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12107 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12108 ("A" "#+ASCII: " "")
12109 ("i" "#+INDEX: ?" "#+INDEX: ?")
12110 ("I" "#+INCLUDE: %file ?"
12111 "<include file=%file markup=\"?\">"))
12112 "Structure completion elements.
12113 This is a list of abbreviation keys and values. The value gets inserted
12114 if you type `<' followed by the key and then press the completion key,
12115 usually `M-TAB'. %file will be replaced by a file name after prompting
12116 for the file using completion. The cursor will be placed at the position
12117 of the `?` in the template.
12118 There are two templates for each key, the first uses the original Org syntax,
12119 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12120 the default when the /org-mtags.el/ module has been loaded. See also the
12121 variable `org-mtags-prefer-muse-templates'."
12122 :group 'org-completion
12123 :type '(repeat
12124 (list
12125 (string :tag "Key")
12126 (string :tag "Template")
12127 (string :tag "Muse Template"))))
12129 (defun org-try-structure-completion ()
12130 "Try to complete a structure template before point.
12131 This looks for strings like \"<e\" on an otherwise empty line and
12132 expands them."
12133 (let ((l (buffer-substring (point-at-bol) (point)))
12135 (when (and (looking-at "[ \t]*$")
12136 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12137 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12138 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12139 (match-beginning 1)) a)
12140 t)))
12142 (defun org-complete-expand-structure-template (start cell)
12143 "Expand a structure template."
12144 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12145 (rpl (nth (if musep 2 1) cell))
12146 (ind ""))
12147 (delete-region start (point))
12148 (when (string-match "\\`[ \t]*#\\+" rpl)
12149 (cond
12150 ((bolp))
12151 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12152 (setq ind (buffer-substring (point-at-bol) (point))))
12153 (t (newline))))
12154 (setq start (point))
12155 (if (string-match "%file" rpl)
12156 (setq rpl (replace-match
12157 (concat
12158 "\""
12159 (save-match-data
12160 (abbreviate-file-name (read-file-name "Include file: ")))
12161 "\"")
12162 t t rpl)))
12163 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12164 (concat "\n" ind)))
12165 (insert rpl)
12166 (if (re-search-backward "\\?" start t) (delete-char 1))))
12168 ;;;; TODO, DEADLINE, Comments
12170 (defun org-toggle-comment ()
12171 "Change the COMMENT state of an entry."
12172 (interactive)
12173 (save-excursion
12174 (org-back-to-heading)
12175 (let (case-fold-search)
12176 (cond
12177 ((looking-at (format org-heading-keyword-regexp-format
12178 org-comment-string))
12179 (goto-char (match-end 1))
12180 (looking-at (concat " +" org-comment-string))
12181 (replace-match "" t t)
12182 (when (eolp) (insert " ")))
12183 ((looking-at org-outline-regexp)
12184 (goto-char (match-end 0))
12185 (insert org-comment-string " "))))))
12187 (defvar org-last-todo-state-is-todo nil
12188 "This is non-nil when the last TODO state change led to a TODO state.
12189 If the last change removed the TODO tag or switched to DONE, then
12190 this is nil.")
12192 (defvar org-setting-tags nil) ; dynamically skipped
12194 (defvar org-todo-setup-filter-hook nil
12195 "Hook for functions that pre-filter todo specs.
12196 Each function takes a todo spec and returns either nil or the spec
12197 transformed into canonical form." )
12199 (defvar org-todo-get-default-hook nil
12200 "Hook for functions that get a default item for todo.
12201 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12202 nil or a string to be used for the todo mark." )
12204 (defvar org-agenda-headline-snapshot-before-repeat)
12206 (defun org-current-effective-time ()
12207 "Return current time adjusted for `org-extend-today-until' variable."
12208 (let* ((ct (org-current-time))
12209 (dct (decode-time ct))
12210 (ct1
12211 (cond
12212 (org-use-last-clock-out-time-as-effective-time
12213 (or (org-clock-get-last-clock-out-time) ct))
12214 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12215 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12216 (t ct))))
12217 ct1))
12219 (defun org-todo-yesterday (&optional arg)
12220 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12221 (interactive "P")
12222 (if (eq major-mode 'org-agenda-mode)
12223 (apply 'org-agenda-todo-yesterday arg)
12224 (let* ((hour (third (decode-time
12225 (org-current-time))))
12226 (org-extend-today-until (1+ hour)))
12227 (org-todo arg))))
12229 (defvar org-block-entry-blocking ""
12230 "First entry preventing the TODO state change.")
12232 (defun org-cancel-repeater ()
12233 "Cancel a repeater by setting its numeric value to zero."
12234 (interactive)
12235 (save-excursion
12236 (org-back-to-heading t)
12237 (let ((bound1 (point))
12238 (bound0 (save-excursion (outline-next-heading) (point))))
12239 (when (re-search-forward
12240 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12241 org-deadline-time-regexp "\\)\\|\\("
12242 org-ts-regexp "\\)")
12243 bound0 t)
12244 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12245 (replace-match "0" t nil nil 1))))))
12247 (defun org-todo (&optional arg)
12248 "Change the TODO state of an item.
12249 The state of an item is given by a keyword at the start of the heading,
12250 like
12251 *** TODO Write paper
12252 *** DONE Call mom
12254 The different keywords are specified in the variable `org-todo-keywords'.
12255 By default the available states are \"TODO\" and \"DONE\".
12256 So for this example: when the item starts with TODO, it is changed to DONE.
12257 When it starts with DONE, the DONE is removed. And when neither TODO nor
12258 DONE are present, add TODO at the beginning of the heading.
12260 With \\[universal-argument] prefix arg, use completion to determine the new \
12261 state.
12262 With numeric prefix arg, switch to that state.
12263 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12264 keywords (nextset).
12265 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12266 With a numeric prefix arg of 0, inhibit note taking for the change.
12267 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12269 When called through ELisp, arg is also interpreted in the following way:
12270 'none -> empty state
12271 \"\"(empty string) -> switch to empty state
12272 'done -> switch to DONE
12273 'nextset -> switch to the next set of keywords
12274 'previousset -> switch to the previous set of keywords
12275 \"WAITING\" -> switch to the specified keyword, but only if it
12276 really is a member of `org-todo-keywords'."
12277 (interactive "P")
12278 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12279 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12280 'region-start-level 'region))
12281 org-loop-over-headlines-in-active-region)
12282 (org-map-entries
12283 `(org-todo ,arg)
12284 org-loop-over-headlines-in-active-region
12285 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12286 (if (equal arg '(16)) (setq arg 'nextset))
12287 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12288 (let ((org-blocker-hook org-blocker-hook)
12289 commentp
12290 case-fold-search)
12291 (when (equal arg '(64))
12292 (setq arg nil org-blocker-hook nil))
12293 (when (and org-blocker-hook
12294 (or org-inhibit-blocking
12295 (org-entry-get nil "NOBLOCKING")))
12296 (setq org-blocker-hook nil))
12297 (save-excursion
12298 (catch 'exit
12299 (org-back-to-heading t)
12300 (when (looking-at (concat "^\\*+ " org-comment-string))
12301 (org-toggle-comment)
12302 (setq commentp t))
12303 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12304 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12305 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12306 (let* ((match-data (match-data))
12307 (startpos (point-at-bol))
12308 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12309 (org-log-done org-log-done)
12310 (org-log-repeat org-log-repeat)
12311 (org-todo-log-states org-todo-log-states)
12312 (org-inhibit-logging
12313 (if (equal arg 0)
12314 (progn (setq arg nil) 'note) org-inhibit-logging))
12315 (this (match-string 1))
12316 (hl-pos (match-beginning 0))
12317 (head (org-get-todo-sequence-head this))
12318 (ass (assoc head org-todo-kwd-alist))
12319 (interpret (nth 1 ass))
12320 (done-word (nth 3 ass))
12321 (final-done-word (nth 4 ass))
12322 (org-last-state (or this ""))
12323 (completion-ignore-case t)
12324 (member (member this org-todo-keywords-1))
12325 (tail (cdr member))
12326 (org-state (cond
12327 ((and org-todo-key-trigger
12328 (or (and (equal arg '(4))
12329 (eq org-use-fast-todo-selection 'prefix))
12330 (and (not arg) org-use-fast-todo-selection
12331 (not (eq org-use-fast-todo-selection
12332 'prefix)))))
12333 ;; Use fast selection
12334 (org-fast-todo-selection))
12335 ((and (equal arg '(4))
12336 (or (not org-use-fast-todo-selection)
12337 (not org-todo-key-trigger)))
12338 ;; Read a state with completion
12339 (org-icompleting-read
12340 "State: " (mapcar 'list org-todo-keywords-1)
12341 nil t))
12342 ((eq arg 'right)
12343 (if this
12344 (if tail (car tail) nil)
12345 (car org-todo-keywords-1)))
12346 ((eq arg 'left)
12347 (if (equal member org-todo-keywords-1)
12349 (if this
12350 (nth (- (length org-todo-keywords-1)
12351 (length tail) 2)
12352 org-todo-keywords-1)
12353 (org-last org-todo-keywords-1))))
12354 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12355 (setq arg nil))) ; hack to fall back to cycling
12356 (arg
12357 ;; user or caller requests a specific state
12358 (cond
12359 ((equal arg "") nil)
12360 ((eq arg 'none) nil)
12361 ((eq arg 'done) (or done-word (car org-done-keywords)))
12362 ((eq arg 'nextset)
12363 (or (car (cdr (member head org-todo-heads)))
12364 (car org-todo-heads)))
12365 ((eq arg 'previousset)
12366 (let ((org-todo-heads (reverse org-todo-heads)))
12367 (or (car (cdr (member head org-todo-heads)))
12368 (car org-todo-heads))))
12369 ((car (member arg org-todo-keywords-1)))
12370 ((stringp arg)
12371 (user-error "State `%s' not valid in this file" arg))
12372 ((nth (1- (prefix-numeric-value arg))
12373 org-todo-keywords-1))))
12374 ((null member) (or head (car org-todo-keywords-1)))
12375 ((equal this final-done-word) nil) ;; -> make empty
12376 ((null tail) nil) ;; -> first entry
12377 ((memq interpret '(type priority))
12378 (if (eq this-command last-command)
12379 (car tail)
12380 (if (> (length tail) 0)
12381 (or done-word (car org-done-keywords))
12382 nil)))
12384 (car tail))))
12385 (org-state (or
12386 (run-hook-with-args-until-success
12387 'org-todo-get-default-hook org-state org-last-state)
12388 org-state))
12389 (next (if org-state (concat " " org-state " ") " "))
12390 (change-plist (list :type 'todo-state-change :from this :to org-state
12391 :position startpos))
12392 dolog now-done-p)
12393 (when org-blocker-hook
12394 (setq org-last-todo-state-is-todo
12395 (not (member this org-done-keywords)))
12396 (unless (save-excursion
12397 (save-match-data
12398 (org-with-wide-buffer
12399 (run-hook-with-args-until-failure
12400 'org-blocker-hook change-plist))))
12401 (if (org-called-interactively-p 'interactive)
12402 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12403 this org-state org-block-entry-blocking)
12404 ;; fail silently
12405 (message "TODO state change from %s to %s blocked (by \"%s\")"
12406 this org-state org-block-entry-blocking)
12407 (throw 'exit nil))))
12408 (store-match-data match-data)
12409 (replace-match next t t)
12410 (unless (pos-visible-in-window-p hl-pos)
12411 (message "TODO state changed to %s" (org-trim next)))
12412 (unless head
12413 (setq head (org-get-todo-sequence-head org-state)
12414 ass (assoc head org-todo-kwd-alist)
12415 interpret (nth 1 ass)
12416 done-word (nth 3 ass)
12417 final-done-word (nth 4 ass)))
12418 (when (memq arg '(nextset previousset))
12419 (message "Keyword-Set %d/%d: %s"
12420 (- (length org-todo-sets) -1
12421 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12422 (length org-todo-sets)
12423 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12424 (setq org-last-todo-state-is-todo
12425 (not (member org-state org-done-keywords)))
12426 (setq now-done-p (and (member org-state org-done-keywords)
12427 (not (member this org-done-keywords))))
12428 (and logging (org-local-logging logging))
12429 (when (and (or org-todo-log-states org-log-done)
12430 (not (eq org-inhibit-logging t))
12431 (not (memq arg '(nextset previousset))))
12432 ;; we need to look at recording a time and note
12433 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12434 (nth 2 (assoc this org-todo-log-states))))
12435 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12436 (setq dolog 'time))
12437 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12438 (and org-state
12439 (member org-state org-not-done-keywords)
12440 (not (member this org-not-done-keywords))))
12441 ;; This is now a todo state and was not one before
12442 ;; If there was a CLOSED time stamp, get rid of it.
12443 (org-add-planning-info nil nil 'closed))
12444 (when (and now-done-p org-log-done)
12445 ;; It is now done, and it was not done before
12446 (org-add-planning-info 'closed (org-current-effective-time))
12447 (if (and (not dolog) (eq 'note org-log-done))
12448 (org-add-log-setup 'done org-state this 'findpos 'note)))
12449 (when (and org-state dolog)
12450 ;; This is a non-nil state, and we need to log it
12451 (org-add-log-setup 'state org-state this 'findpos dolog)))
12452 ;; Fixup tag positioning
12453 (org-todo-trigger-tag-changes org-state)
12454 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12455 (when org-provide-todo-statistics
12456 (org-update-parent-todo-statistics))
12457 (run-hooks 'org-after-todo-state-change-hook)
12458 (if (and arg (not (member org-state org-done-keywords)))
12459 (setq head (org-get-todo-sequence-head org-state)))
12460 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12461 ;; Do we need to trigger a repeat?
12462 (when now-done-p
12463 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12464 ;; This is for the agenda, take a snapshot of the headline.
12465 (save-match-data
12466 (setq org-agenda-headline-snapshot-before-repeat
12467 (org-get-heading))))
12468 (org-auto-repeat-maybe org-state))
12469 ;; Fixup cursor location if close to the keyword
12470 (if (and (outline-on-heading-p)
12471 (not (bolp))
12472 (save-excursion (beginning-of-line 1)
12473 (looking-at org-todo-line-regexp))
12474 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12475 (progn
12476 (goto-char (or (match-end 2) (match-end 1)))
12477 (and (looking-at " ") (just-one-space))))
12478 (when org-trigger-hook
12479 (save-excursion
12480 (run-hook-with-args 'org-trigger-hook change-plist)))
12481 (when commentp (org-toggle-comment))))))))
12483 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12484 "Block turning an entry into a TODO, using the hierarchy.
12485 This checks whether the current task should be blocked from state
12486 changes. Such blocking occurs when:
12488 1. The task has children which are not all in a completed state.
12490 2. A task has a parent with the property :ORDERED:, and there
12491 are siblings prior to the current task with incomplete
12492 status.
12494 3. The parent of the task is blocked because it has siblings that should
12495 be done first, or is child of a block grandparent TODO entry."
12497 (if (not org-enforce-todo-dependencies)
12498 t ; if locally turned off don't block
12499 (catch 'dont-block
12500 ;; If this is not a todo state change, or if this entry is already DONE,
12501 ;; do not block
12502 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12503 (member (plist-get change-plist :from)
12504 (cons 'done org-done-keywords))
12505 (member (plist-get change-plist :to)
12506 (cons 'todo org-not-done-keywords))
12507 (not (plist-get change-plist :to)))
12508 (throw 'dont-block t))
12509 ;; If this task has children, and any are undone, it's blocked
12510 (save-excursion
12511 (org-back-to-heading t)
12512 (let ((this-level (funcall outline-level)))
12513 (outline-next-heading)
12514 (let ((child-level (funcall outline-level)))
12515 (while (and (not (eobp))
12516 (> child-level this-level))
12517 ;; this todo has children, check whether they are all
12518 ;; completed
12519 (if (and (not (org-entry-is-done-p))
12520 (org-entry-is-todo-p))
12521 (progn (setq org-block-entry-blocking (org-get-heading))
12522 (throw 'dont-block nil)))
12523 (outline-next-heading)
12524 (setq child-level (funcall outline-level))))))
12525 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12526 ;; any previous siblings are undone, it's blocked
12527 (save-excursion
12528 (org-back-to-heading t)
12529 (let* ((pos (point))
12530 (parent-pos (and (org-up-heading-safe) (point))))
12531 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12532 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12533 (forward-line 1)
12534 (re-search-forward org-not-done-heading-regexp pos t))
12535 (setq org-block-entry-blocking (match-string 0))
12536 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12537 ;; Search further up the hierarchy, to see if an ancestor is blocked
12538 (while t
12539 (goto-char parent-pos)
12540 (if (not (looking-at org-not-done-heading-regexp))
12541 (throw 'dont-block t)) ; do not block, parent is not a TODO
12542 (setq pos (point))
12543 (setq parent-pos (and (org-up-heading-safe) (point)))
12544 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12545 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12546 (forward-line 1)
12547 (re-search-forward org-not-done-heading-regexp pos t)
12548 (setq org-block-entry-blocking (org-get-heading)))
12549 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12551 (defcustom org-track-ordered-property-with-tag nil
12552 "Should the ORDERED property also be shown as a tag?
12553 The ORDERED property decides if an entry should require subtasks to be
12554 completed in sequence. Since a property is not very visible, setting
12555 this option means that toggling the ORDERED property with the command
12556 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12557 not relevant for the behavior, but it makes things more visible.
12559 Note that toggling the tag with tags commands will not change the property
12560 and therefore not influence behavior!
12562 This can be t, meaning the tag ORDERED should be used, It can also be a
12563 string to select a different tag for this task."
12564 :group 'org-todo
12565 :type '(choice
12566 (const :tag "No tracking" nil)
12567 (const :tag "Track with ORDERED tag" t)
12568 (string :tag "Use other tag")))
12570 (defun org-toggle-ordered-property ()
12571 "Toggle the ORDERED property of the current entry.
12572 For better visibility, you can track the value of this property with a tag.
12573 See variable `org-track-ordered-property-with-tag'."
12574 (interactive)
12575 (let* ((t1 org-track-ordered-property-with-tag)
12576 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12577 (save-excursion
12578 (org-back-to-heading)
12579 (if (org-entry-get nil "ORDERED")
12580 (progn
12581 (org-delete-property "ORDERED")
12582 (and tag (org-toggle-tag tag 'off))
12583 (message "Subtasks can be completed in arbitrary order"))
12584 (org-entry-put nil "ORDERED" "t")
12585 (and tag (org-toggle-tag tag 'on))
12586 (message "Subtasks must be completed in sequence")))))
12588 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12589 (defun org-block-todo-from-checkboxes (change-plist)
12590 "Block turning an entry into a TODO, using checkboxes.
12591 This checks whether the current task should be blocked from state
12592 changes because there are unchecked boxes in this entry."
12593 (if (not org-enforce-todo-checkbox-dependencies)
12594 t ; if locally turned off don't block
12595 (catch 'dont-block
12596 ;; If this is not a todo state change, or if this entry is already DONE,
12597 ;; do not block
12598 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12599 (member (plist-get change-plist :from)
12600 (cons 'done org-done-keywords))
12601 (member (plist-get change-plist :to)
12602 (cons 'todo org-not-done-keywords))
12603 (not (plist-get change-plist :to)))
12604 (throw 'dont-block t))
12605 ;; If this task has checkboxes that are not checked, it's blocked
12606 (save-excursion
12607 (org-back-to-heading t)
12608 (let ((beg (point)) end)
12609 (outline-next-heading)
12610 (setq end (point))
12611 (goto-char beg)
12612 (if (org-list-search-forward
12613 (concat (org-item-beginning-re)
12614 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12615 "\\[[- ]\\]")
12616 end t)
12617 (progn
12618 (if (boundp 'org-blocked-by-checkboxes)
12619 (setq org-blocked-by-checkboxes t))
12620 (throw 'dont-block nil)))))
12621 t))) ; do not block
12623 (defun org-entry-blocked-p ()
12624 "Is the current entry blocked?"
12625 (org-with-silent-modifications
12626 (if (org-entry-get nil "NOBLOCKING")
12627 nil ;; Never block this entry
12628 (not (run-hook-with-args-until-failure
12629 'org-blocker-hook
12630 (list :type 'todo-state-change
12631 :position (point)
12632 :from 'todo
12633 :to 'done))))))
12635 (defun org-update-statistics-cookies (all)
12636 "Update the statistics cookie, either from TODO or from checkboxes.
12637 This should be called with the cursor in a line with a statistics cookie."
12638 (interactive "P")
12639 (if all
12640 (progn
12641 (org-update-checkbox-count 'all)
12642 (org-map-entries 'org-update-parent-todo-statistics))
12643 (if (not (org-at-heading-p))
12644 (org-update-checkbox-count)
12645 (let ((pos (point-marker))
12646 end l1 l2)
12647 (ignore-errors (org-back-to-heading t))
12648 (if (not (org-at-heading-p))
12649 (org-update-checkbox-count)
12650 (setq l1 (org-outline-level))
12651 (setq end (save-excursion
12652 (outline-next-heading)
12653 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12654 (point)))
12655 (if (and (save-excursion
12656 (re-search-forward
12657 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12658 (not (save-excursion (re-search-forward
12659 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12660 (org-update-checkbox-count)
12661 (if (and l2 (> l2 l1))
12662 (progn
12663 (goto-char end)
12664 (org-update-parent-todo-statistics))
12665 (goto-char pos)
12666 (beginning-of-line 1)
12667 (while (re-search-forward
12668 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12669 (point-at-eol) t)
12670 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12671 (goto-char pos)
12672 (move-marker pos nil)))))
12674 (defvar org-entry-property-inherited-from) ;; defined below
12675 (defun org-update-parent-todo-statistics ()
12676 "Update any statistics cookie in the parent of the current headline.
12677 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12678 the entire subtree and this will travel up the hierarchy and update
12679 statistics everywhere."
12680 (let* ((prop (save-excursion (org-up-heading-safe)
12681 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12682 (recursive (or (not org-hierarchical-todo-statistics)
12683 (and prop (string-match "\\<recursive\\>" prop))))
12684 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12686 (first t)
12687 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12688 level ltoggle l1 new ndel
12689 (cnt-all 0) (cnt-done 0) is-percent kwd
12690 checkbox-beg ov ovs ove cookie-present)
12691 (catch 'exit
12692 (save-excursion
12693 (beginning-of-line 1)
12694 (setq ltoggle (funcall outline-level))
12695 ;; Three situations are to consider:
12697 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12698 ;; to the top-level ancestor on the headline;
12700 ;; 2. If parent has "recursive" property, repeat up to the
12701 ;; headline setting that property, taking inheritance into
12702 ;; account;
12704 ;; 3. Else, move up to direct parent and proceed only once.
12705 (while (and (setq level (org-up-heading-safe))
12706 (or recursive first)
12707 (>= (point) lim))
12708 (setq first nil cookie-present nil)
12709 (unless (and level
12710 (not (string-match
12711 "\\<checkbox\\>"
12712 (downcase (or (org-entry-get nil "COOKIE_DATA")
12713 "")))))
12714 (throw 'exit nil))
12715 (while (re-search-forward box-re (point-at-eol) t)
12716 (setq cnt-all 0 cnt-done 0 cookie-present t)
12717 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12718 (save-match-data
12719 (unless (outline-next-heading) (throw 'exit nil))
12720 (while (and (looking-at org-complex-heading-regexp)
12721 (> (setq l1 (length (match-string 1))) level))
12722 (setq kwd (and (or recursive (= l1 ltoggle))
12723 (match-string 2)))
12724 (if (or (eq org-provide-todo-statistics 'all-headlines)
12725 (and (eq org-provide-todo-statistics t)
12726 (or (member kwd org-done-keywords)))
12727 (and (listp org-provide-todo-statistics)
12728 (stringp (car org-provide-todo-statistics))
12729 (or (member kwd org-provide-todo-statistics)
12730 (member kwd org-done-keywords)))
12731 (and (listp org-provide-todo-statistics)
12732 (listp (car org-provide-todo-statistics))
12733 (or (member kwd (car org-provide-todo-statistics))
12734 (and (member kwd org-done-keywords)
12735 (member kwd (cadr org-provide-todo-statistics))))))
12736 (setq cnt-all (1+ cnt-all))
12737 (if (eq org-provide-todo-statistics t)
12738 (and kwd (setq cnt-all (1+ cnt-all)))))
12739 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12740 (member kwd org-done-keywords))
12741 (and (listp org-provide-todo-statistics)
12742 (listp (car org-provide-todo-statistics))
12743 (member kwd org-done-keywords)
12744 (member kwd (cadr org-provide-todo-statistics)))
12745 (and (listp org-provide-todo-statistics)
12746 (stringp (car org-provide-todo-statistics))
12747 (member kwd org-done-keywords)))
12748 (setq cnt-done (1+ cnt-done)))
12749 (outline-next-heading)))
12750 (setq new
12751 (if is-percent
12752 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12753 (format "[%d/%d]" cnt-done cnt-all))
12754 ndel (- (match-end 0) checkbox-beg))
12755 ;; handle overlays when updating cookie from column view
12756 (when (setq ov (car (overlays-at checkbox-beg)))
12757 (setq ovs (overlay-start ov) ove (overlay-end ov))
12758 (delete-overlay ov))
12759 (goto-char checkbox-beg)
12760 (insert new)
12761 (delete-region (point) (+ (point) ndel))
12762 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12763 (when ov (move-overlay ov ovs ove)))
12764 (when cookie-present
12765 (run-hook-with-args 'org-after-todo-statistics-hook
12766 cnt-done (- cnt-all cnt-done))))))
12767 (run-hooks 'org-todo-statistics-hook)))
12769 (defvar org-after-todo-statistics-hook nil
12770 "Hook that is called after a TODO statistics cookie has been updated.
12771 Each function is called with two arguments: the number of not-done entries
12772 and the number of done entries.
12774 For example, the following function, when added to this hook, will switch
12775 an entry to DONE when all children are done, and back to TODO when new
12776 entries are set to a TODO status. Note that this hook is only called
12777 when there is a statistics cookie in the headline!
12779 (defun org-summary-todo (n-done n-not-done)
12780 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12781 (let (org-log-done org-log-states) ; turn off logging
12782 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12785 (defvar org-todo-statistics-hook nil
12786 "Hook that is run whenever Org thinks TODO statistics should be updated.
12787 This hook runs even if there is no statistics cookie present, in which case
12788 `org-after-todo-statistics-hook' would not run.")
12790 (defun org-todo-trigger-tag-changes (state)
12791 "Apply the changes defined in `org-todo-state-tags-triggers'."
12792 (let ((l org-todo-state-tags-triggers)
12793 changes)
12794 (when (or (not state) (equal state ""))
12795 (setq changes (append changes (cdr (assoc "" l)))))
12796 (when (and (stringp state) (> (length state) 0))
12797 (setq changes (append changes (cdr (assoc state l)))))
12798 (when (member state org-not-done-keywords)
12799 (setq changes (append changes (cdr (assoc 'todo l)))))
12800 (when (member state org-done-keywords)
12801 (setq changes (append changes (cdr (assoc 'done l)))))
12802 (dolist (c changes)
12803 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12805 (defun org-local-logging (value)
12806 "Get logging settings from a property VALUE."
12807 (let* (words w a)
12808 ;; directly set the variables, they are already local.
12809 (setq org-log-done nil
12810 org-log-repeat nil
12811 org-todo-log-states nil)
12812 (setq words (org-split-string value))
12813 (while (setq w (pop words))
12814 (cond
12815 ((setq a (assoc w org-startup-options))
12816 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12817 (set (nth 1 a) (nth 2 a))))
12818 ((setq a (org-extract-log-state-settings w))
12819 (and (member (car a) org-todo-keywords-1)
12820 (push a org-todo-log-states)))))))
12822 (defun org-get-todo-sequence-head (kwd)
12823 "Return the head of the TODO sequence to which KWD belongs.
12824 If KWD is not set, check if there is a text property remembering the
12825 right sequence."
12826 (let (p)
12827 (cond
12828 ((not kwd)
12829 (or (get-text-property (point-at-bol) 'org-todo-head)
12830 (progn
12831 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12832 nil (point-at-eol)))
12833 (get-text-property p 'org-todo-head))))
12834 ((not (member kwd org-todo-keywords-1))
12835 (car org-todo-keywords-1))
12836 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12838 (defun org-fast-todo-selection ()
12839 "Fast TODO keyword selection with single keys.
12840 Returns the new TODO keyword, or nil if no state change should occur."
12841 (let* ((fulltable org-todo-key-alist)
12842 (done-keywords org-done-keywords) ;; needed for the faces.
12843 (maxlen (apply 'max (mapcar
12844 (lambda (x)
12845 (if (stringp (car x)) (string-width (car x)) 0))
12846 fulltable)))
12847 (expert nil)
12848 (fwidth (+ maxlen 3 1 3))
12849 (ncol (/ (- (window-width) 4) fwidth))
12850 tg cnt e c tbl
12851 groups ingroup)
12852 (save-excursion
12853 (save-window-excursion
12854 (if expert
12855 (set-buffer (get-buffer-create " *Org todo*"))
12856 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12857 (erase-buffer)
12858 (org-set-local 'org-done-keywords done-keywords)
12859 (setq tbl fulltable cnt 0)
12860 (while (setq e (pop tbl))
12861 (cond
12862 ((equal e '(:startgroup))
12863 (push '() groups) (setq ingroup t)
12864 (when (not (= cnt 0))
12865 (setq cnt 0)
12866 (insert "\n"))
12867 (insert "{ "))
12868 ((equal e '(:endgroup))
12869 (setq ingroup nil cnt 0)
12870 (insert "}\n"))
12871 ((equal e '(:newline))
12872 (when (not (= cnt 0))
12873 (setq cnt 0)
12874 (insert "\n")
12875 (setq e (car tbl))
12876 (while (equal (car tbl) '(:newline))
12877 (insert "\n")
12878 (setq tbl (cdr tbl)))))
12880 (setq tg (car e) c (cdr e))
12881 (if ingroup (push tg (car groups)))
12882 (setq tg (org-add-props tg nil 'face
12883 (org-get-todo-face tg)))
12884 (if (and (= cnt 0) (not ingroup)) (insert " "))
12885 (insert "[" c "] " tg (make-string
12886 (- fwidth 4 (length tg)) ?\ ))
12887 (when (= (setq cnt (1+ cnt)) ncol)
12888 (insert "\n")
12889 (if ingroup (insert " "))
12890 (setq cnt 0)))))
12891 (insert "\n")
12892 (goto-char (point-min))
12893 (if (not expert) (org-fit-window-to-buffer))
12894 (message "[a-z..]:Set [SPC]:clear")
12895 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12896 (cond
12897 ((or (= c ?\C-g)
12898 (and (= c ?q) (not (rassoc c fulltable))))
12899 (setq quit-flag t))
12900 ((= c ?\ ) nil)
12901 ((setq e (rassoc c fulltable) tg (car e))
12903 (t (setq quit-flag t)))))))
12905 (defun org-entry-is-todo-p ()
12906 (member (org-get-todo-state) org-not-done-keywords))
12908 (defun org-entry-is-done-p ()
12909 (member (org-get-todo-state) org-done-keywords))
12911 (defun org-get-todo-state ()
12912 "Return the TODO keyword of the current subtree."
12913 (save-excursion
12914 (org-back-to-heading t)
12915 (and (looking-at org-todo-line-regexp)
12916 (match-end 2)
12917 (match-string 2))))
12919 (defun org-at-date-range-p (&optional inactive-ok)
12920 "Is the cursor inside a date range?"
12921 (interactive)
12922 (save-excursion
12923 (catch 'exit
12924 (let ((pos (point)))
12925 (skip-chars-backward "^[<\r\n")
12926 (skip-chars-backward "<[")
12927 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12928 (>= (match-end 0) pos)
12929 (throw 'exit t))
12930 (skip-chars-backward "^<[\r\n")
12931 (skip-chars-backward "<[")
12932 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12933 (>= (match-end 0) pos)
12934 (throw 'exit t)))
12935 nil)))
12937 (defun org-get-repeat (&optional tagline)
12938 "Check if there is a deadline/schedule with repeater in this entry."
12939 (save-match-data
12940 (save-excursion
12941 (org-back-to-heading t)
12942 (and (re-search-forward (if tagline
12943 (concat tagline "\\s-*" org-repeat-re)
12944 org-repeat-re)
12945 (org-entry-end-position) t)
12946 (match-string-no-properties 1)))))
12948 (defvar org-last-changed-timestamp)
12949 (defvar org-last-inserted-timestamp)
12950 (defvar org-log-post-message)
12951 (defvar org-log-note-purpose)
12952 (defvar org-log-note-how)
12953 (defvar org-log-note-extra)
12954 (defun org-auto-repeat-maybe (done-word)
12955 "Check if the current headline contains a repeated deadline/schedule.
12956 If yes, set TODO state back to what it was and change the base date
12957 of repeating deadline/scheduled time stamps to new date.
12958 This function is run automatically after each state change to a DONE state."
12959 ;; last-state is dynamically scoped into this function
12960 (let* ((repeat (org-get-repeat))
12961 (aa (assoc org-last-state org-todo-kwd-alist))
12962 (interpret (nth 1 aa))
12963 (head (nth 2 aa))
12964 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12965 (msg "Entry repeats: ")
12966 (org-log-done nil)
12967 (org-todo-log-states nil)
12968 re type n what ts time to-state)
12969 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12970 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12971 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12972 org-todo-repeat-to-state))
12973 (unless (and to-state (member to-state org-todo-keywords-1))
12974 (setq to-state (if (eq interpret 'type) org-last-state head)))
12975 (org-todo to-state)
12976 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12977 (org-entry-put nil "LAST_REPEAT" (format-time-string
12978 (org-time-stamp-format t t))))
12979 (when org-log-repeat
12980 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12981 (memq 'org-add-log-note post-command-hook))
12982 ;; OK, we are already setup for some record
12983 (if (eq org-log-repeat 'note)
12984 ;; make sure we take a note, not only a time stamp
12985 (setq org-log-note-how 'note))
12986 ;; Set up for taking a record
12987 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12988 org-last-state
12989 'findpos org-log-repeat)))
12990 (org-back-to-heading t)
12991 (org-add-planning-info nil nil 'closed)
12992 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12993 org-deadline-time-regexp "\\)\\|\\("
12994 org-ts-regexp "\\)"))
12995 (while (re-search-forward
12996 re (save-excursion (outline-next-heading) (point)) t)
12997 (setq type (if (match-end 1) org-scheduled-string
12998 (if (match-end 3) org-deadline-string "Plain:"))
12999 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13000 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
13001 (setq n (string-to-number (match-string 2 ts))
13002 what (match-string 3 ts))
13003 (if (equal what "w") (setq n (* n 7) what "d"))
13004 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13005 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13006 ;; Preparation, see if we need to modify the start date for the change
13007 (when (match-end 1)
13008 (setq time (save-match-data (org-time-string-to-time ts)))
13009 (cond
13010 ((equal (match-string 1 ts) ".")
13011 ;; Shift starting date to today
13012 (org-timestamp-change
13013 (- (org-today) (time-to-days time))
13014 'day))
13015 ((equal (match-string 1 ts) "+")
13016 (let ((nshiftmax 10) (nshift 0))
13017 (while (or (= nshift 0)
13018 (<= (time-to-days time)
13019 (time-to-days (current-time))))
13020 (when (= (incf nshift) nshiftmax)
13021 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13022 (error "Abort")))
13023 (org-timestamp-change n (cdr (assoc what whata)))
13024 (org-at-timestamp-p t)
13025 (setq ts (match-string 1))
13026 (setq time (save-match-data (org-time-string-to-time ts)))))
13027 (org-timestamp-change (- n) (cdr (assoc what whata)))
13028 ;; rematch, so that we have everything in place for the real shift
13029 (org-at-timestamp-p t)
13030 (setq ts (match-string 1))
13031 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13032 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13033 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13034 (setq org-log-post-message msg)
13035 (message "%s" msg))))
13037 (defun org-show-todo-tree (arg)
13038 "Make a compact tree which shows all headlines marked with TODO.
13039 The tree will show the lines where the regexp matches, and all higher
13040 headlines above the match.
13041 With a \\[universal-argument] prefix, prompt for a regexp to match.
13042 With a numeric prefix N, construct a sparse tree for the Nth element
13043 of `org-todo-keywords-1'."
13044 (interactive "P")
13045 (let ((case-fold-search nil)
13046 (kwd-re
13047 (cond ((null arg) org-not-done-regexp)
13048 ((equal arg '(4))
13049 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13050 (mapcar 'list org-todo-keywords-1))))
13051 (concat "\\("
13052 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13053 "\\)\\>")))
13054 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13055 (regexp-quote (nth (1- (prefix-numeric-value arg))
13056 org-todo-keywords-1)))
13057 (t (user-error "Invalid prefix argument: %s" arg)))))
13058 (message "%d TODO entries found"
13059 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13061 (defun org-deadline (arg &optional time)
13062 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13063 With one universal prefix argument, remove any deadline from the item.
13064 With two universal prefix arguments, prompt for a warning delay.
13065 With argument TIME, set the deadline at the corresponding date. TIME
13066 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13067 (interactive "P")
13068 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13069 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13070 'region-start-level 'region))
13071 org-loop-over-headlines-in-active-region)
13072 (org-map-entries
13073 `(org-deadline ',arg ,time)
13074 org-loop-over-headlines-in-active-region
13075 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13076 (let* ((old-date (org-entry-get nil "DEADLINE"))
13077 (old-date-time (if old-date (org-time-string-to-time old-date)))
13078 (repeater (and old-date
13079 (string-match
13080 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13081 old-date)
13082 (match-string 1 old-date))))
13083 (cond
13084 ((equal arg '(4))
13085 (when (and old-date org-log-redeadline)
13086 (org-add-log-setup 'deldeadline nil old-date 'findpos
13087 org-log-redeadline))
13088 (org-remove-timestamp-with-keyword org-deadline-string)
13089 (message "Item no longer has a deadline."))
13090 ((equal arg '(16))
13091 (save-excursion
13092 (org-back-to-heading t)
13093 (if (re-search-forward
13094 org-deadline-time-regexp
13095 (save-excursion (outline-next-heading) (point)) t)
13096 (let* ((rpl0 (match-string 1))
13097 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13098 (replace-match
13099 (concat org-deadline-string
13100 " <" rpl
13101 (format " -%dd"
13102 (abs
13103 (- (time-to-days
13104 (save-match-data
13105 (org-read-date nil t nil "Warn starting from" old-date-time)))
13106 (time-to-days old-date-time))))
13107 ">") t t))
13108 (user-error "No deadline information to update"))))
13110 (org-add-planning-info 'deadline time 'closed)
13111 (when (and old-date org-log-redeadline
13112 (not (equal old-date
13113 (substring org-last-inserted-timestamp 1 -1))))
13114 (org-add-log-setup 'redeadline nil old-date 'findpos
13115 org-log-redeadline))
13116 (when repeater
13117 (save-excursion
13118 (org-back-to-heading t)
13119 (when (re-search-forward (concat org-deadline-string " "
13120 org-last-inserted-timestamp)
13121 (save-excursion
13122 (outline-next-heading) (point)) t)
13123 (goto-char (1- (match-end 0)))
13124 (insert " " repeater)
13125 (setq org-last-inserted-timestamp
13126 (concat (substring org-last-inserted-timestamp 0 -1)
13127 " " repeater
13128 (substring org-last-inserted-timestamp -1))))))
13129 (message "Deadline on %s" org-last-inserted-timestamp))))))
13131 (defun org-schedule (arg &optional time)
13132 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13133 With one universal prefix argument, remove any scheduling date from the item.
13134 With two universal prefix arguments, prompt for a delay cookie.
13135 With argument TIME, scheduled at the corresponding date. TIME can
13136 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13137 (interactive "P")
13138 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13139 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13140 'region-start-level 'region))
13141 org-loop-over-headlines-in-active-region)
13142 (org-map-entries
13143 `(org-schedule ',arg ,time)
13144 org-loop-over-headlines-in-active-region
13145 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13146 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13147 (old-date-time (if old-date (org-time-string-to-time old-date)))
13148 (repeater (and old-date
13149 (string-match
13150 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13151 old-date)
13152 (match-string 1 old-date))))
13153 (cond
13154 ((equal arg '(4))
13155 (progn
13156 (when (and old-date org-log-reschedule)
13157 (org-add-log-setup 'delschedule nil old-date 'findpos
13158 org-log-reschedule))
13159 (org-remove-timestamp-with-keyword org-scheduled-string)
13160 (message "Item is no longer scheduled.")))
13161 ((equal arg '(16))
13162 (save-excursion
13163 (org-back-to-heading t)
13164 (if (re-search-forward
13165 org-scheduled-time-regexp
13166 (save-excursion (outline-next-heading) (point)) t)
13167 (let* ((rpl0 (match-string 1))
13168 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13169 (replace-match
13170 (concat org-scheduled-string
13171 " <" rpl
13172 (format " -%dd"
13173 (abs
13174 (- (time-to-days
13175 (save-match-data
13176 (org-read-date nil t nil "Delay until" old-date-time)))
13177 (time-to-days old-date-time))))
13178 ">") t t))
13179 (user-error "No scheduled information to update"))))
13181 (org-add-planning-info 'scheduled time 'closed)
13182 (when (and old-date org-log-reschedule
13183 (not (equal old-date
13184 (substring org-last-inserted-timestamp 1 -1))))
13185 (org-add-log-setup 'reschedule nil old-date 'findpos
13186 org-log-reschedule))
13187 (when repeater
13188 (save-excursion
13189 (org-back-to-heading t)
13190 (when (re-search-forward (concat org-scheduled-string " "
13191 org-last-inserted-timestamp)
13192 (save-excursion
13193 (outline-next-heading) (point)) t)
13194 (goto-char (1- (match-end 0)))
13195 (insert " " repeater)
13196 (setq org-last-inserted-timestamp
13197 (concat (substring org-last-inserted-timestamp 0 -1)
13198 " " repeater
13199 (substring org-last-inserted-timestamp -1))))))
13200 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13202 (defun org-get-scheduled-time (pom &optional inherit)
13203 "Get the scheduled time as a time tuple, of a format suitable
13204 for calling org-schedule with, or if there is no scheduling,
13205 returns nil."
13206 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13207 (when time
13208 (apply 'encode-time (org-parse-time-string time)))))
13210 (defun org-get-deadline-time (pom &optional inherit)
13211 "Get the deadline as a time tuple, of a format suitable for
13212 calling org-deadline with, or if there is no scheduling, returns
13213 nil."
13214 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13215 (when time
13216 (apply 'encode-time (org-parse-time-string time)))))
13218 (defun org-remove-timestamp-with-keyword (keyword)
13219 "Remove all time stamps with KEYWORD in the current entry."
13220 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13221 beg)
13222 (save-excursion
13223 (org-back-to-heading t)
13224 (setq beg (point))
13225 (outline-next-heading)
13226 (while (re-search-backward re beg t)
13227 (replace-match "")
13228 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13229 (equal (char-before) ?\ ))
13230 (backward-delete-char 1)
13231 (if (string-match "^[ \t]*$" (buffer-substring
13232 (point-at-bol) (point-at-eol)))
13233 (delete-region (point-at-bol)
13234 (min (point-max) (1+ (point-at-eol))))))))))
13236 (defvar org-time-was-given) ; dynamically scoped parameter
13237 (defvar org-end-time-was-given) ; dynamically scoped parameter
13239 (defun org-add-planning-info (what &optional time &rest remove)
13240 "Insert new timestamp with keyword in the line directly after the headline.
13241 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13242 If non is given, the user is prompted for a date.
13243 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13244 be removed."
13245 (interactive)
13246 (let (org-time-was-given org-end-time-was-given ts
13247 end default-time default-input)
13249 (catch 'exit
13250 (when (and (memq what '(scheduled deadline))
13251 (or (not time)
13252 (and (stringp time)
13253 (string-match "^[-+]+[0-9]" time))))
13254 ;; Try to get a default date/time from existing timestamp
13255 (save-excursion
13256 (org-back-to-heading t)
13257 (setq end (save-excursion (outline-next-heading) (point)))
13258 (when (re-search-forward (if (eq what 'scheduled)
13259 org-scheduled-time-regexp
13260 org-deadline-time-regexp)
13261 end t)
13262 (setq ts (match-string 1)
13263 default-time
13264 (apply 'encode-time (org-parse-time-string ts))
13265 default-input (and ts (org-get-compact-tod ts))))))
13266 (when what
13267 (setq time
13268 (if (stringp time)
13269 ;; This is a string (relative or absolute), set proper date
13270 (apply 'encode-time
13271 (org-read-date-analyze
13272 time default-time (decode-time default-time)))
13273 ;; If necessary, get the time from the user
13274 (or time (org-read-date nil 'to-time nil nil
13275 default-time default-input)))))
13277 (when (and org-insert-labeled-timestamps-at-point
13278 (member what '(scheduled deadline)))
13279 (insert
13280 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13281 (org-insert-time-stamp time org-time-was-given
13282 nil nil nil (list org-end-time-was-given))
13283 (setq what nil))
13284 (save-excursion
13285 (save-restriction
13286 (let (col list elt ts buffer-invisibility-spec)
13287 (org-back-to-heading t)
13288 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13289 (goto-char (match-end 1))
13290 (setq col (current-column))
13291 (goto-char (match-end 0))
13292 (if (eobp) (insert "\n") (forward-char 1))
13293 (when (and (not what)
13294 (not (looking-at
13295 (concat "[ \t]*"
13296 org-keyword-time-not-clock-regexp))))
13297 ;; Nothing to add, nothing to remove...... :-)
13298 (throw 'exit nil))
13299 (if (and (not (looking-at org-outline-regexp))
13300 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13301 "[^\r\n]*"))
13302 (not (equal (match-string 1) org-clock-string)))
13303 (narrow-to-region (match-beginning 0) (match-end 0))
13304 (insert-before-markers "\n")
13305 (backward-char 1)
13306 (narrow-to-region (point) (point))
13307 (and org-adapt-indentation (org-indent-to-column col)))
13308 ;; Check if we have to remove something.
13309 (setq list (cons what remove))
13310 (while list
13311 (setq elt (pop list))
13312 (when (or (and (eq elt 'scheduled)
13313 (re-search-forward org-scheduled-time-regexp nil t))
13314 (and (eq elt 'deadline)
13315 (re-search-forward org-deadline-time-regexp nil t))
13316 (and (eq elt 'closed)
13317 (re-search-forward org-closed-time-regexp nil t)))
13318 (replace-match "")
13319 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13320 (and (looking-at "[ \t]+") (replace-match ""))
13321 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13322 (when what
13323 (insert
13324 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13325 (cond ((eq what 'scheduled) org-scheduled-string)
13326 ((eq what 'deadline) org-deadline-string)
13327 ((eq what 'closed) org-closed-string))
13328 " ")
13329 (setq ts (org-insert-time-stamp
13330 time
13331 (or org-time-was-given
13332 (and (eq what 'closed) org-log-done-with-time))
13333 (eq what 'closed)
13334 nil nil (list org-end-time-was-given)))
13335 (insert
13336 (if (not (or (bolp) (eq (char-before) ?\ )
13337 (memq (char-after) '(32 10))
13338 (eobp))) " " ""))
13339 (end-of-line 1))
13340 (goto-char (point-min))
13341 (widen)
13342 (if (and (looking-at "[ \t]*\n")
13343 (equal (char-before) ?\n))
13344 (delete-region (1- (point)) (point-at-eol)))
13345 ts))))))
13347 (defvar org-log-note-marker (make-marker))
13348 (defvar org-log-note-purpose nil)
13349 (defvar org-log-note-state nil)
13350 (defvar org-log-note-previous-state nil)
13351 (defvar org-log-note-how nil)
13352 (defvar org-log-note-extra nil)
13353 (defvar org-log-note-window-configuration nil)
13354 (defvar org-log-note-return-to (make-marker))
13355 (defvar org-log-note-effective-time nil
13356 "Remembered current time so that dynamically scoped
13357 `org-extend-today-until' affects tha timestamps in state change
13358 log")
13360 (defvar org-log-post-message nil
13361 "Message to be displayed after a log note has been stored.
13362 The auto-repeater uses this.")
13364 (defun org-add-note ()
13365 "Add a note to the current entry.
13366 This is done in the same way as adding a state change note."
13367 (interactive)
13368 (org-add-log-setup 'note nil nil 'findpos nil))
13370 (defvar org-property-end-re)
13371 (defun org-add-log-setup (&optional purpose state prev-state
13372 findpos how extra)
13373 "Set up the post command hook to take a note.
13374 If this is about to TODO state change, the new state is expected in STATE.
13375 When FINDPOS is non-nil, find the correct position for the note in
13376 the current entry. If not, assume that it can be inserted at point.
13377 HOW is an indicator what kind of note should be created.
13378 EXTRA is additional text that will be inserted into the notes buffer."
13379 (let* ((org-log-into-drawer (org-log-into-drawer))
13380 (drawer (cond ((stringp org-log-into-drawer)
13381 org-log-into-drawer)
13382 (org-log-into-drawer "LOGBOOK"))))
13383 (save-restriction
13384 (save-excursion
13385 (when findpos
13386 (org-back-to-heading t)
13387 (narrow-to-region (point) (save-excursion
13388 (outline-next-heading) (point)))
13389 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13390 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13391 "[^\r\n]*\\)?"))
13392 (goto-char (match-end 0))
13393 (cond
13394 (drawer
13395 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13396 nil t)
13397 (progn
13398 (goto-char (match-end 0))
13399 (or org-log-states-order-reversed
13400 (and (re-search-forward org-property-end-re nil t)
13401 (goto-char (1- (match-beginning 0))))))
13402 (insert "\n:" drawer ":\n:END:")
13403 (beginning-of-line 0)
13404 (org-indent-line)
13405 (beginning-of-line 2)
13406 (org-indent-line)
13407 (end-of-line 0)))
13408 ((and org-log-state-notes-insert-after-drawers
13409 (save-excursion
13410 (forward-line) (looking-at org-drawer-regexp)))
13411 (forward-line)
13412 (while (looking-at org-drawer-regexp)
13413 (goto-char (match-end 0))
13414 (re-search-forward org-property-end-re (point-max) t)
13415 (forward-line))
13416 (forward-line -1)))
13417 (unless org-log-states-order-reversed
13418 (and (= (char-after) ?\n) (forward-char 1))
13419 (org-skip-over-state-notes)
13420 (skip-chars-backward " \t\n\r")))
13421 (move-marker org-log-note-marker (point))
13422 (setq org-log-note-purpose purpose
13423 org-log-note-state state
13424 org-log-note-previous-state prev-state
13425 org-log-note-how how
13426 org-log-note-extra extra
13427 org-log-note-effective-time (org-current-effective-time))
13428 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13430 (defun org-skip-over-state-notes ()
13431 "Skip past the list of State notes in an entry."
13432 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13433 (when (ignore-errors (goto-char (org-in-item-p)))
13434 (let* ((struct (org-list-struct))
13435 (prevs (org-list-prevs-alist struct)))
13436 (while (looking-at "[ \t]*- State")
13437 (goto-char (or (org-list-get-next-item (point) struct prevs)
13438 (org-list-get-item-end (point) struct)))))))
13440 (defun org-add-log-note (&optional purpose)
13441 "Pop up a window for taking a note, and add this note later at point."
13442 (remove-hook 'post-command-hook 'org-add-log-note)
13443 (setq org-log-note-window-configuration (current-window-configuration))
13444 (delete-other-windows)
13445 (move-marker org-log-note-return-to (point))
13446 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13447 (goto-char org-log-note-marker)
13448 (org-switch-to-buffer-other-window "*Org Note*")
13449 (erase-buffer)
13450 (if (memq org-log-note-how '(time state))
13451 (let (current-prefix-arg) (org-store-log-note))
13452 (let ((org-inhibit-startup t)) (org-mode))
13453 (insert (format "# Insert note for %s.
13454 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13455 (cond
13456 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13457 ((eq org-log-note-purpose 'done) "closed todo item")
13458 ((eq org-log-note-purpose 'state)
13459 (format "state change from \"%s\" to \"%s\""
13460 (or org-log-note-previous-state "")
13461 (or org-log-note-state "")))
13462 ((eq org-log-note-purpose 'reschedule)
13463 "rescheduling")
13464 ((eq org-log-note-purpose 'delschedule)
13465 "no longer scheduled")
13466 ((eq org-log-note-purpose 'redeadline)
13467 "changing deadline")
13468 ((eq org-log-note-purpose 'deldeadline)
13469 "removing deadline")
13470 ((eq org-log-note-purpose 'refile)
13471 "refiling")
13472 ((eq org-log-note-purpose 'note)
13473 "this entry")
13474 (t (error "This should not happen")))))
13475 (if org-log-note-extra (insert org-log-note-extra))
13476 (org-set-local 'org-finish-function 'org-store-log-note)
13477 (run-hooks 'org-log-buffer-setup-hook)))
13479 (defvar org-note-abort nil) ; dynamically scoped
13480 (defun org-store-log-note ()
13481 "Finish taking a log note, and insert it to where it belongs."
13482 (let ((txt (buffer-string)))
13483 (kill-buffer (current-buffer))
13484 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13485 lines ind bul)
13486 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13487 (setq txt (replace-match "" t t txt)))
13488 (if (string-match "\\s-+\\'" txt)
13489 (setq txt (replace-match "" t t txt)))
13490 (setq lines (org-split-string txt "\n"))
13491 (when (and note (string-match "\\S-" note))
13492 (setq note
13493 (org-replace-escapes
13494 note
13495 (list (cons "%u" (user-login-name))
13496 (cons "%U" user-full-name)
13497 (cons "%t" (format-time-string
13498 (org-time-stamp-format 'long 'inactive)
13499 org-log-note-effective-time))
13500 (cons "%T" (format-time-string
13501 (org-time-stamp-format 'long nil)
13502 org-log-note-effective-time))
13503 (cons "%d" (format-time-string
13504 (org-time-stamp-format nil 'inactive)
13505 org-log-note-effective-time))
13506 (cons "%D" (format-time-string
13507 (org-time-stamp-format nil nil)
13508 org-log-note-effective-time))
13509 (cons "%s" (if org-log-note-state
13510 (concat "\"" org-log-note-state "\"")
13511 ""))
13512 (cons "%S" (if org-log-note-previous-state
13513 (concat "\"" org-log-note-previous-state "\"")
13514 "\"\"")))))
13515 (if lines (setq note (concat note " \\\\")))
13516 (push note lines))
13517 (when (or current-prefix-arg org-note-abort)
13518 (when org-log-into-drawer
13519 (org-remove-empty-drawer-at org-log-note-marker))
13520 (setq lines nil))
13521 (when lines
13522 (with-current-buffer (marker-buffer org-log-note-marker)
13523 (save-excursion
13524 (goto-char org-log-note-marker)
13525 (move-marker org-log-note-marker nil)
13526 (end-of-line 1)
13527 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13528 (setq ind (save-excursion
13529 (if (ignore-errors (goto-char (org-in-item-p)))
13530 (let ((struct (org-list-struct)))
13531 (org-list-get-ind
13532 (org-list-get-top-point struct) struct))
13533 (skip-chars-backward " \r\t\n")
13534 (cond
13535 ((and (org-at-heading-p)
13536 org-adapt-indentation)
13537 (1+ (org-current-level)))
13538 ((org-at-heading-p) 0)
13539 (t (org-get-indentation))))))
13540 (setq bul (org-list-bullet-string "-"))
13541 (org-indent-line-to ind)
13542 (insert bul (pop lines))
13543 (let ((ind-body (+ (length bul) ind)))
13544 (while lines
13545 (insert "\n")
13546 (org-indent-line-to ind-body)
13547 (insert (pop lines))))
13548 (message "Note stored")
13549 (org-back-to-heading t)
13550 (org-cycle-hide-drawers 'children))
13551 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13552 ;; from within `org-add-log-note' because `buffer-undo-list'
13553 ;; is then modified outside of `org-with-remote-undo'.
13554 (when (eq this-command 'org-agenda-todo)
13555 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13556 ;; Don't add undo information when called from `org-agenda-todo'
13557 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13558 (set-window-configuration org-log-note-window-configuration)
13559 (with-current-buffer (marker-buffer org-log-note-return-to)
13560 (goto-char org-log-note-return-to))
13561 (move-marker org-log-note-return-to nil)
13562 (and org-log-post-message (message "%s" org-log-post-message))))
13564 (defun org-remove-empty-drawer-at (pos)
13565 "Remove an empty drawer at position POS.
13566 POS may also be a marker."
13567 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13568 (org-with-wide-buffer
13569 (goto-char pos)
13570 (let ((drawer (org-element-at-point)))
13571 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13572 (not (org-element-property :contents-begin drawer)))
13573 (delete-region (org-element-property :begin drawer)
13574 (progn (goto-char (org-element-property :end drawer))
13575 (skip-chars-backward " \r\t\n")
13576 (forward-line)
13577 (point))))))))
13579 (defvar org-ts-type nil)
13580 (defun org-sparse-tree (&optional arg type)
13581 "Create a sparse tree, prompt for the details.
13582 This command can create sparse trees. You first need to select the type
13583 of match used to create the tree:
13585 t Show all TODO entries.
13586 T Show entries with a specific TODO keyword.
13587 m Show entries selected by a tags/property match.
13588 p Enter a property name and its value (both with completion on existing
13589 names/values) and show entries with that property.
13590 r Show entries matching a regular expression (`/' can be used as well).
13591 b Show deadlines and scheduled items before a date.
13592 a Show deadlines and scheduled items after a date.
13593 d Show deadlines due within `org-deadline-warning-days'.
13594 D Show deadlines and scheduled items between a date range."
13595 (interactive "P")
13596 (let (ans kwd value ts-type)
13597 (setq type (or type org-sparse-tree-default-date-type))
13598 (setq org-ts-type type)
13599 (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"
13600 (cond ((eq type 'all) "all timestamps")
13601 ((eq type 'scheduled) "only scheduled")
13602 ((eq type 'deadline) "only deadline")
13603 ((eq type 'active) "only active timestamps")
13604 ((eq type 'inactive) "only inactive timestamps")
13605 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13606 ((eq type 'closed) "with a closed time-stamp")
13607 (t "scheduled/deadline")))
13608 (setq ans (read-char-exclusive))
13609 (cond
13610 ((equal ans ?c)
13611 (org-sparse-tree
13612 arg (cadr (member type '(scheduled-or-deadline
13613 all scheduled deadline active inactive closed)))))
13614 ((equal ans ?d)
13615 (call-interactively 'org-check-deadlines))
13616 ((equal ans ?b)
13617 (call-interactively 'org-check-before-date))
13618 ((equal ans ?a)
13619 (call-interactively 'org-check-after-date))
13620 ((equal ans ?D)
13621 (call-interactively 'org-check-dates-range))
13622 ((equal ans ?t)
13623 (call-interactively 'org-show-todo-tree))
13624 ((equal ans ?T)
13625 (org-show-todo-tree '(4)))
13626 ((member ans '(?T ?m))
13627 (call-interactively 'org-match-sparse-tree))
13628 ((member ans '(?p ?P))
13629 (setq kwd (org-icompleting-read "Property: "
13630 (mapcar 'list (org-buffer-property-keys))))
13631 (setq value (org-icompleting-read "Value: "
13632 (mapcar 'list (org-property-values kwd))))
13633 (unless (string-match "\\`{.*}\\'" value)
13634 (setq value (concat "\"" value "\"")))
13635 (org-match-sparse-tree arg (concat kwd "=" value)))
13636 ((member ans '(?r ?R ?/))
13637 (call-interactively 'org-occur))
13638 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13640 (defvar org-occur-highlights nil
13641 "List of overlays used for occur matches.")
13642 (make-variable-buffer-local 'org-occur-highlights)
13643 (defvar org-occur-parameters nil
13644 "Parameters of the active org-occur calls.
13645 This is a list, each call to org-occur pushes as cons cell,
13646 containing the regular expression and the callback, onto the list.
13647 The list can contain several entries if `org-occur' has been called
13648 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13649 will only contain one set of parameters. When the highlights are
13650 removed (for example with `C-c C-c', or with the next edit (depending
13651 on `org-remove-highlights-with-change'), this variable is emptied
13652 as well.")
13653 (make-variable-buffer-local 'org-occur-parameters)
13655 (defun org-occur (regexp &optional keep-previous callback)
13656 "Make a compact tree which shows all matches of REGEXP.
13657 The tree will show the lines where the regexp matches, and all higher
13658 headlines above the match. It will also show the heading after the match,
13659 to make sure editing the matching entry is easy.
13660 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13661 call to `org-occur' will be kept, to allow stacking of calls to this
13662 command.
13663 If CALLBACK is non-nil, it is a function which is called to confirm
13664 that the match should indeed be shown."
13665 (interactive "sRegexp: \nP")
13666 (when (equal regexp "")
13667 (user-error "Regexp cannot be empty"))
13668 (unless keep-previous
13669 (org-remove-occur-highlights nil nil t))
13670 (push (cons regexp callback) org-occur-parameters)
13671 (let ((cnt 0))
13672 (save-excursion
13673 (goto-char (point-min))
13674 (if (or (not keep-previous) ; do not want to keep
13675 (not org-occur-highlights)) ; no previous matches
13676 ;; hide everything
13677 (org-overview))
13678 (while (re-search-forward regexp nil t)
13679 (when (or (not callback)
13680 (save-match-data (funcall callback)))
13681 (setq cnt (1+ cnt))
13682 (when org-highlight-sparse-tree-matches
13683 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13684 (org-show-context 'occur-tree))))
13685 (when org-remove-highlights-with-change
13686 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13687 nil 'local))
13688 (unless org-sparse-tree-open-archived-trees
13689 (org-hide-archived-subtrees (point-min) (point-max)))
13690 (run-hooks 'org-occur-hook)
13691 (if (org-called-interactively-p 'interactive)
13692 (message "%d match(es) for regexp %s" cnt regexp))
13693 cnt))
13695 (defun org-occur-next-match (&optional n reset)
13696 "Function for `next-error-function' to find sparse tree matches.
13697 N is the number of matches to move, when negative move backwards.
13698 RESET is entirely ignored - this function always goes back to the
13699 starting point when no match is found."
13700 (let* ((limit (if (< n 0) (point-min) (point-max)))
13701 (search-func (if (< n 0)
13702 'previous-single-char-property-change
13703 'next-single-char-property-change))
13704 (n (abs n))
13705 (pos (point))
13707 (catch 'exit
13708 (while (setq p1 (funcall search-func (point) 'org-type))
13709 (when (equal p1 limit)
13710 (goto-char pos)
13711 (error "No more matches"))
13712 (when (equal (get-char-property p1 'org-type) 'org-occur)
13713 (setq n (1- n))
13714 (when (= n 0)
13715 (goto-char p1)
13716 (throw 'exit (point))))
13717 (goto-char p1))
13718 (goto-char p1)
13719 (error "No more matches"))))
13721 (defun org-show-context (&optional key)
13722 "Make sure point and context are visible.
13723 How much context is shown depends upon the variables
13724 `org-show-hierarchy-above', `org-show-following-heading',
13725 `org-show-entry-below' and `org-show-siblings'."
13726 (let ((heading-p (org-at-heading-p t))
13727 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13728 (following-p (org-get-alist-option org-show-following-heading key))
13729 (entry-p (org-get-alist-option org-show-entry-below key))
13730 (siblings-p (org-get-alist-option org-show-siblings key)))
13731 ;; Show heading or entry text
13732 (if (and heading-p (not entry-p))
13733 (org-flag-heading nil) ; only show the heading
13734 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13735 (org-show-hidden-entry))) ; show entire entry
13736 (when following-p
13737 ;; Show next sibling, or heading below text
13738 (save-excursion
13739 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13740 (org-flag-heading nil))))
13741 (when siblings-p (org-show-siblings))
13742 (when hierarchy-p
13743 ;; show all higher headings, possibly with siblings
13744 (save-excursion
13745 (while (and (condition-case nil
13746 (progn (org-up-heading-all 1) t)
13747 (error nil))
13748 (not (bobp)))
13749 (org-flag-heading nil)
13750 (when siblings-p (org-show-siblings)))))
13751 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13753 (defvar org-reveal-start-hook nil
13754 "Hook run before revealing a location.")
13756 (defun org-reveal (&optional siblings)
13757 "Show current entry, hierarchy above it, and the following headline.
13758 This can be used to show a consistent set of context around locations
13759 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13760 not t for the search context.
13762 With optional argument SIBLINGS, on each level of the hierarchy all
13763 siblings are shown. This repairs the tree structure to what it would
13764 look like when opened with hierarchical calls to `org-cycle'.
13765 With double optional argument \\[universal-argument] \\[universal-argument], \
13766 go to the parent and show the
13767 entire tree."
13768 (interactive "P")
13769 (run-hooks 'org-reveal-start-hook)
13770 (let ((org-show-hierarchy-above t)
13771 (org-show-following-heading t)
13772 (org-show-siblings (if siblings t org-show-siblings)))
13773 (org-show-context nil))
13774 (when (equal siblings '(16))
13775 (save-excursion
13776 (when (org-up-heading-safe)
13777 (org-show-subtree)
13778 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13780 (defun org-highlight-new-match (beg end)
13781 "Highlight from BEG to END and mark the highlight is an occur headline."
13782 (let ((ov (make-overlay beg end)))
13783 (overlay-put ov 'face 'secondary-selection)
13784 (overlay-put ov 'org-type 'org-occur)
13785 (push ov org-occur-highlights)))
13787 (defun org-remove-occur-highlights (&optional beg end noremove)
13788 "Remove the occur highlights from the buffer.
13789 BEG and END are ignored. If NOREMOVE is nil, remove this function
13790 from the `before-change-functions' in the current buffer."
13791 (interactive)
13792 (unless org-inhibit-highlight-removal
13793 (mapc 'delete-overlay org-occur-highlights)
13794 (setq org-occur-highlights nil)
13795 (setq org-occur-parameters nil)
13796 (unless noremove
13797 (remove-hook 'before-change-functions
13798 'org-remove-occur-highlights 'local))))
13800 ;;;; Priorities
13802 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13803 "Regular expression matching the priority indicator.")
13805 (defvar org-remove-priority-next-time nil)
13807 (defun org-priority-up ()
13808 "Increase the priority of the current item."
13809 (interactive)
13810 (org-priority 'up))
13812 (defun org-priority-down ()
13813 "Decrease the priority of the current item."
13814 (interactive)
13815 (org-priority 'down))
13817 (defun org-priority (&optional action show)
13818 "Change the priority of an item.
13819 ACTION can be `set', `up', `down', or a character."
13820 (interactive "P")
13821 (if (equal action '(4))
13822 (org-show-priority)
13823 (unless org-enable-priority-commands
13824 (user-error "Priority commands are disabled"))
13825 (setq action (or action 'set))
13826 (let (current new news have remove)
13827 (save-excursion
13828 (org-back-to-heading t)
13829 (if (looking-at org-priority-regexp)
13830 (setq current (string-to-char (match-string 2))
13831 have t))
13832 (cond
13833 ((eq action 'remove)
13834 (setq remove t new ?\ ))
13835 ((or (eq action 'set)
13836 (if (featurep 'xemacs) (characterp action) (integerp action)))
13837 (if (not (eq action 'set))
13838 (setq new action)
13839 (message "Priority %c-%c, SPC to remove: "
13840 org-highest-priority org-lowest-priority)
13841 (save-match-data
13842 (setq new (read-char-exclusive))))
13843 (if (and (= (upcase org-highest-priority) org-highest-priority)
13844 (= (upcase org-lowest-priority) org-lowest-priority))
13845 (setq new (upcase new)))
13846 (cond ((equal new ?\ ) (setq remove t))
13847 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13848 (user-error "Priority must be between `%c' and `%c'"
13849 org-highest-priority org-lowest-priority))))
13850 ((eq action 'up)
13851 (setq new (if have
13852 (1- current) ; normal cycling
13853 ;; last priority was empty
13854 (if (eq last-command this-command)
13855 org-lowest-priority ; wrap around empty to lowest
13856 ;; default
13857 (if org-priority-start-cycle-with-default
13858 org-default-priority
13859 (1- org-default-priority))))))
13860 ((eq action 'down)
13861 (setq new (if have
13862 (1+ current) ; normal cycling
13863 ;; last priority was empty
13864 (if (eq last-command this-command)
13865 org-highest-priority ; wrap around empty to highest
13866 ;; default
13867 (if org-priority-start-cycle-with-default
13868 org-default-priority
13869 (1+ org-default-priority))))))
13870 (t (user-error "Invalid action")))
13871 (if (or (< (upcase new) org-highest-priority)
13872 (> (upcase new) org-lowest-priority))
13873 (if (and (memq action '(up down))
13874 (not have) (not (eq last-command this-command)))
13875 ;; `new' is from default priority
13876 (error
13877 "The default can not be set, see `org-default-priority' why")
13878 ;; normal cycling: `new' is beyond highest/lowest priority
13879 ;; and is wrapped around to the empty priority
13880 (setq remove t)))
13881 (setq news (format "%c" new))
13882 (if have
13883 (if remove
13884 (replace-match "" t t nil 1)
13885 (replace-match news t t nil 2))
13886 (if remove
13887 (user-error "No priority cookie found in line")
13888 (let ((case-fold-search nil))
13889 (looking-at org-todo-line-regexp))
13890 (if (match-end 2)
13891 (progn
13892 (goto-char (match-end 2))
13893 (insert " [#" news "]"))
13894 (goto-char (match-beginning 3))
13895 (insert "[#" news "] "))))
13896 (org-set-tags nil 'align))
13897 (if remove
13898 (message "Priority removed")
13899 (message "Priority of current item set to %s" news)))))
13901 (defun org-show-priority ()
13902 "Show the priority of the current item.
13903 This priority is composed of the main priority given with the [#A] cookies,
13904 and by additional input from the age of a schedules or deadline entry."
13905 (interactive)
13906 (let ((pri (if (eq major-mode 'org-agenda-mode)
13907 (org-get-at-bol 'priority)
13908 (save-excursion
13909 (save-match-data
13910 (beginning-of-line)
13911 (and (looking-at org-heading-regexp)
13912 (org-get-priority (match-string 0))))))))
13913 (message "Priority is %d" (if pri pri -1000))))
13915 (defun org-get-priority (s)
13916 "Find priority cookie and return priority."
13917 (save-match-data
13918 (if (functionp org-get-priority-function)
13919 (funcall org-get-priority-function)
13920 (if (not (string-match org-priority-regexp s))
13921 (* 1000 (- org-lowest-priority org-default-priority))
13922 (* 1000 (- org-lowest-priority
13923 (string-to-char (match-string 2 s))))))))
13925 ;;;; Tags
13927 (defvar org-agenda-archives-mode)
13928 (defvar org-map-continue-from nil
13929 "Position from where mapping should continue.
13930 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13932 (defvar org-scanner-tags nil
13933 "The current tag list while the tags scanner is running.")
13934 (defvar org-trust-scanner-tags nil
13935 "Should `org-get-tags-at' use the tags for the scanner.
13936 This is for internal dynamical scoping only.
13937 When this is non-nil, the function `org-get-tags-at' will return the value
13938 of `org-scanner-tags' instead of building the list by itself. This
13939 can lead to large speed-ups when the tags scanner is used in a file with
13940 many entries, and when the list of tags is retrieved, for example to
13941 obtain a list of properties. Building the tags list for each entry in such
13942 a file becomes an N^2 operation - but with this variable set, it scales
13943 as N.")
13945 (defun org-scan-tags (action matcher todo-only &optional start-level)
13946 "Sca headline tags with inheritance and produce output ACTION.
13948 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13949 or `agenda' to produce an entry list for an agenda view. It can also be
13950 a Lisp form or a function that should be called at each matched headline, in
13951 this case the return value is a list of all return values from these calls.
13953 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13954 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13955 only lines with a not-done TODO keyword are included in the output.
13956 This should be the same variable that was scoped into
13957 and set by `org-make-tags-matcher' when it constructed MATCHER.
13959 START-LEVEL can be a string with asterisks, reducing the scope to
13960 headlines matching this string."
13961 (require 'org-agenda)
13962 (let* ((re (concat "^"
13963 (if start-level
13964 ;; Get the correct level to match
13965 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13966 org-outline-regexp)
13967 " *\\(\\<\\("
13968 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13969 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13970 (props (list 'face 'default
13971 'done-face 'org-agenda-done
13972 'undone-face 'default
13973 'mouse-face 'highlight
13974 'org-not-done-regexp org-not-done-regexp
13975 'org-todo-regexp org-todo-regexp
13976 'org-complex-heading-regexp org-complex-heading-regexp
13977 'help-echo
13978 (format "mouse-2 or RET jump to org file %s"
13979 (abbreviate-file-name
13980 (or (buffer-file-name (buffer-base-buffer))
13981 (buffer-name (buffer-base-buffer)))))))
13982 (org-map-continue-from nil)
13983 lspos tags tags-list
13984 (tags-alist (list (cons 0 org-file-tags)))
13985 (llast 0) rtn rtn1 level category i txt
13986 todo marker entry priority)
13987 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13988 (setq action (list 'lambda nil action)))
13989 (save-excursion
13990 (goto-char (point-min))
13991 (when (eq action 'sparse-tree)
13992 (org-overview)
13993 (org-remove-occur-highlights))
13994 (while (let (case-fold-search)
13995 (re-search-forward re nil t))
13996 (setq org-map-continue-from nil)
13997 (catch :skip
13998 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13999 tags (if (match-end 4) (org-match-string-no-properties 4)))
14000 (goto-char (setq lspos (match-beginning 0)))
14001 (setq level (org-reduced-level (org-outline-level))
14002 category (org-get-category))
14003 (setq i llast llast level)
14004 ;; remove tag lists from same and sublevels
14005 (while (>= i level)
14006 (when (setq entry (assoc i tags-alist))
14007 (setq tags-alist (delete entry tags-alist)))
14008 (setq i (1- i)))
14009 ;; add the next tags
14010 (when tags
14011 (setq tags (org-split-string tags ":")
14012 tags-alist
14013 (cons (cons level tags) tags-alist)))
14014 ;; compile tags for current headline
14015 (setq tags-list
14016 (if org-use-tag-inheritance
14017 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14018 tags)
14019 org-scanner-tags tags-list)
14020 (when org-use-tag-inheritance
14021 (setcdr (car tags-alist)
14022 (mapcar (lambda (x)
14023 (setq x (copy-sequence x))
14024 (org-add-prop-inherited x))
14025 (cdar tags-alist))))
14026 (when (and tags org-use-tag-inheritance
14027 (or (not (eq t org-use-tag-inheritance))
14028 org-tags-exclude-from-inheritance))
14029 ;; selective inheritance, remove uninherited ones
14030 (setcdr (car tags-alist)
14031 (org-remove-uninherited-tags (cdar tags-alist))))
14032 (when (and
14034 ;; eval matcher only when the todo condition is OK
14035 (and (or (not todo-only) (member todo org-not-done-keywords))
14036 (let ((case-fold-search t) (org-trust-scanner-tags t))
14037 (eval matcher)))
14039 ;; Call the skipper, but return t if it does not skip,
14040 ;; so that the `and' form continues evaluating
14041 (progn
14042 (unless (eq action 'sparse-tree) (org-agenda-skip))
14045 ;; Check if timestamps are deselecting this entry
14046 (or (not todo-only)
14047 (and (member todo org-not-done-keywords)
14048 (or (not org-agenda-tags-todo-honor-ignore-options)
14049 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14051 ;; select this headline
14052 (cond
14053 ((eq action 'sparse-tree)
14054 (and org-highlight-sparse-tree-matches
14055 (org-get-heading) (match-end 0)
14056 (org-highlight-new-match
14057 (match-beginning 1) (match-end 1)))
14058 (org-show-context 'tags-tree))
14059 ((eq action 'agenda)
14060 (setq txt (org-agenda-format-item
14062 (concat
14063 (if (eq org-tags-match-list-sublevels 'indented)
14064 (make-string (1- level) ?.) "")
14065 (org-get-heading))
14066 level category
14067 tags-list)
14068 priority (org-get-priority txt))
14069 (goto-char lspos)
14070 (setq marker (org-agenda-new-marker))
14071 (org-add-props txt props
14072 'org-marker marker 'org-hd-marker marker 'org-category category
14073 'todo-state todo
14074 'priority priority 'type "tagsmatch")
14075 (push txt rtn))
14076 ((functionp action)
14077 (setq org-map-continue-from nil)
14078 (save-excursion
14079 (setq rtn1 (funcall action))
14080 (push rtn1 rtn)))
14081 (t (user-error "Invalid action")))
14083 ;; if we are to skip sublevels, jump to end of subtree
14084 (unless org-tags-match-list-sublevels
14085 (org-end-of-subtree t)
14086 (backward-char 1))))
14087 ;; Get the correct position from where to continue
14088 (if org-map-continue-from
14089 (goto-char org-map-continue-from)
14090 (and (= (point) lspos) (end-of-line 1)))))
14091 (when (and (eq action 'sparse-tree)
14092 (not org-sparse-tree-open-archived-trees))
14093 (org-hide-archived-subtrees (point-min) (point-max)))
14094 (nreverse rtn)))
14096 (defun org-remove-uninherited-tags (tags)
14097 "Remove all tags that are not inherited from the list TAGS."
14098 (cond
14099 ((eq org-use-tag-inheritance t)
14100 (if org-tags-exclude-from-inheritance
14101 (org-delete-all org-tags-exclude-from-inheritance tags)
14102 tags))
14103 ((not org-use-tag-inheritance) nil)
14104 ((stringp org-use-tag-inheritance)
14105 (delq nil (mapcar
14106 (lambda (x)
14107 (if (and (string-match org-use-tag-inheritance x)
14108 (not (member x org-tags-exclude-from-inheritance)))
14109 x nil))
14110 tags)))
14111 ((listp org-use-tag-inheritance)
14112 (delq nil (mapcar
14113 (lambda (x)
14114 (if (member x org-use-tag-inheritance) x nil))
14115 tags)))))
14117 (defun org-match-sparse-tree (&optional todo-only match)
14118 "Create a sparse tree according to tags string MATCH.
14119 MATCH can contain positive and negative selection of tags, like
14120 \"+WORK+URGENT-WITHBOSS\".
14121 If optional argument TODO-ONLY is non-nil, only select lines that are
14122 also TODO lines."
14123 (interactive "P")
14124 (org-agenda-prepare-buffers (list (current-buffer)))
14125 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14127 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14129 (defvar org-cached-props nil)
14130 (defun org-cached-entry-get (pom property)
14131 (if (or (eq t org-use-property-inheritance)
14132 (and (stringp org-use-property-inheritance)
14133 (string-match org-use-property-inheritance property))
14134 (and (listp org-use-property-inheritance)
14135 (member property org-use-property-inheritance)))
14136 ;; Caching is not possible, check it directly
14137 (org-entry-get pom property 'inherit)
14138 ;; Get all properties, so that we can do complicated checks easily
14139 (cdr (assoc property (or org-cached-props
14140 (setq org-cached-props
14141 (org-entry-properties pom)))))))
14143 (defun org-global-tags-completion-table (&optional files)
14144 "Return the list of all tags in all agenda buffer/files.
14145 Optional FILES argument is a list of files which can be used
14146 instead of the agenda files."
14147 (save-excursion
14148 (org-uniquify
14149 (delq nil
14150 (apply 'append
14151 (mapcar
14152 (lambda (file)
14153 (set-buffer (find-file-noselect file))
14154 (append (org-get-buffer-tags)
14155 (mapcar (lambda (x) (if (stringp (car-safe x))
14156 (list (car-safe x)) nil))
14157 org-tag-alist)))
14158 (if (and files (car files))
14159 files
14160 (org-agenda-files))))))))
14162 (defun org-make-tags-matcher (match)
14163 "Create the TAGS/TODO matcher form for the selection string MATCH.
14165 The variable `todo-only' is scoped dynamically into this function.
14166 It will be set to t if the matcher restricts matching to TODO entries,
14167 otherwise will not be touched.
14169 Returns a cons of the selection string MATCH and the constructed
14170 lisp form implementing the matcher. The matcher is to be evaluated
14171 at an Org entry, with point on the headline, and returns t if the
14172 entry matches the selection string MATCH. The returned lisp form
14173 references two variables with information about the entry, which
14174 must be bound around the form's evaluation: todo, the TODO keyword
14175 at the entry (or nil of none); and tags-list, the list of all tags
14176 at the entry including inherited ones. Additionally, the category
14177 of the entry (if any) must be specified as the text property
14178 'org-category on the headline.
14180 See also `org-scan-tags'.
14182 (declare (special todo-only))
14183 (unless (boundp 'todo-only)
14184 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14185 (unless match
14186 ;; Get a new match request, with completion against the global
14187 ;; tags table and the local tags in current buffer
14188 (let ((org-last-tags-completion-table
14189 (org-uniquify
14190 (delq nil (append (org-get-buffer-tags)
14191 (org-global-tags-completion-table))))))
14192 (setq match (org-completing-read-no-i
14193 "Match: " 'org-tags-completion-function nil nil nil
14194 'org-tags-history))))
14196 ;; Parse the string and create a lisp form
14197 (let ((match0 match)
14198 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14199 minus tag mm
14200 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14201 orterms term orlist re-p str-p level-p level-op time-p
14202 prop-p pn pv po gv rest (start 0) (ss 0))
14203 ;; Expand group tags
14204 (setq match (org-tags-expand match))
14206 ;; Check if there is a TODO part of this match, which would be the
14207 ;; part after a "/". TO make sure that this slash is not part of
14208 ;; a property value to be matched against, we also check that there
14209 ;; is no " after that slash.
14210 ;; First, find the last slash
14211 (while (string-match "/+" match ss)
14212 (setq start (match-beginning 0) ss (match-end 0)))
14213 (if (and (string-match "/+" match start)
14214 (not (save-match-data (string-match "\"" match start))))
14215 ;; match contains also a todo-matching request
14216 (progn
14217 (setq tagsmatch (substring match 0 (match-beginning 0))
14218 todomatch (substring match (match-end 0)))
14219 (if (string-match "^!" todomatch)
14220 (setq todo-only t todomatch (substring todomatch 1)))
14221 (if (string-match "^\\s-*$" todomatch)
14222 (setq todomatch nil)))
14223 ;; only matching tags
14224 (setq tagsmatch match todomatch nil))
14226 ;; Make the tags matcher
14227 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14228 (setq tagsmatcher t)
14229 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14230 (while (setq term (pop orterms))
14231 (while (and (equal (substring term -1) "\\") orterms)
14232 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14233 (while (string-match re term)
14234 (setq rest (substring term (match-end 0))
14235 minus (and (match-end 1)
14236 (equal (match-string 1 term) "-"))
14237 tag (save-match-data (replace-regexp-in-string
14238 "\\\\-" "-"
14239 (match-string 2 term)))
14240 re-p (equal (string-to-char tag) ?{)
14241 level-p (match-end 4)
14242 prop-p (match-end 5)
14243 mm (cond
14244 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14245 (level-p
14246 (setq level-op (org-op-to-function (match-string 3 term)))
14247 `(,level-op level ,(string-to-number
14248 (match-string 4 term))))
14249 (prop-p
14250 (setq pn (match-string 5 term)
14251 po (match-string 6 term)
14252 pv (match-string 7 term)
14253 re-p (equal (string-to-char pv) ?{)
14254 str-p (equal (string-to-char pv) ?\")
14255 time-p (save-match-data
14256 (string-match "^\"[[<].*[]>]\"$" pv))
14257 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14258 (if time-p (setq pv (org-matcher-time pv)))
14259 (setq po (org-op-to-function po (if time-p 'time str-p)))
14260 (cond
14261 ((equal pn "CATEGORY")
14262 (setq gv '(get-text-property (point) 'org-category)))
14263 ((equal pn "TODO")
14264 (setq gv 'todo))
14266 (setq gv `(org-cached-entry-get nil ,pn))))
14267 (if re-p
14268 (if (eq po 'org<>)
14269 `(not (string-match ,pv (or ,gv "")))
14270 `(string-match ,pv (or ,gv "")))
14271 (if str-p
14272 `(,po (or ,gv "") ,pv)
14273 `(,po (string-to-number (or ,gv ""))
14274 ,(string-to-number pv) ))))
14275 (t `(member ,tag tags-list)))
14276 mm (if minus (list 'not mm) mm)
14277 term rest)
14278 (push mm tagsmatcher))
14279 (push (if (> (length tagsmatcher) 1)
14280 (cons 'and tagsmatcher)
14281 (car tagsmatcher))
14282 orlist)
14283 (setq tagsmatcher nil))
14284 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14285 (setq tagsmatcher
14286 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14287 ;; Make the todo matcher
14288 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14289 (setq todomatcher t)
14290 (setq orterms (org-split-string todomatch "|") orlist nil)
14291 (while (setq term (pop orterms))
14292 (while (string-match re term)
14293 (setq minus (and (match-end 1)
14294 (equal (match-string 1 term) "-"))
14295 kwd (match-string 2 term)
14296 re-p (equal (string-to-char kwd) ?{)
14297 term (substring term (match-end 0))
14298 mm (if re-p
14299 `(string-match ,(substring kwd 1 -1) todo)
14300 (list 'equal 'todo kwd))
14301 mm (if minus (list 'not mm) mm))
14302 (push mm todomatcher))
14303 (push (if (> (length todomatcher) 1)
14304 (cons 'and todomatcher)
14305 (car todomatcher))
14306 orlist)
14307 (setq todomatcher nil))
14308 (setq todomatcher (if (> (length orlist) 1)
14309 (cons 'or orlist) (car orlist))))
14311 ;; Return the string and lisp forms of the matcher
14312 (setq matcher (if todomatcher
14313 (list 'and tagsmatcher todomatcher)
14314 tagsmatcher))
14315 (when todo-only
14316 (setq matcher (list 'and '(member todo org-not-done-keywords)
14317 matcher)))
14318 (cons match0 matcher)))
14320 (defun org-tags-expand (match &optional single-as-list downcased)
14321 "Expand group tags in MATCH.
14323 This replaces every group tag in MATCH with a regexp tag search.
14324 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14325 will be replaced like this:
14327 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14328 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14329 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14331 Replacing by a regexp preserves the structure of the match.
14332 E.g., this expansion
14334 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14336 will match anything tagged with \"Lab\" and \"Home\", or tagged
14337 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14339 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14340 assumed to be a single group tag, and the function will return
14341 the list of tags in this group.
14343 When DOWNCASE is non-nil, expand downcased TAGS."
14344 (if org-group-tags
14345 (let* ((case-fold-search t)
14346 (stable org-mode-syntax-table)
14347 (tal (or org-tag-groups-alist-for-agenda
14348 org-tag-groups-alist))
14349 (tal (if downcased
14350 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14351 (tml (mapcar 'car tal))
14352 (rtnmatch match) rpl)
14353 ;; @ and _ are allowed as word-components in tags
14354 (modify-syntax-entry ?@ "w" stable)
14355 (modify-syntax-entry ?_ "w" stable)
14356 (while (and tml
14357 (with-syntax-table stable
14358 (string-match
14359 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14360 (regexp-opt tml) "\\>\\)") rtnmatch)))
14361 (let* ((dir (match-string 1 rtnmatch))
14362 (tag (match-string 2 rtnmatch))
14363 (tag (if downcased (downcase tag) tag)))
14364 (setq tml (delete tag tml))
14365 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14366 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14367 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14368 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14369 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14370 (if single-as-list
14371 (or (reverse rpl) (list rtnmatch))
14372 rtnmatch))
14373 (if single-as-list (list (if downcased (downcase match) match))
14374 match)))
14376 (defun org-op-to-function (op &optional stringp)
14377 "Turn an operator into the appropriate function."
14378 (setq op
14379 (cond
14380 ((equal op "<" ) '(< string< org-time<))
14381 ((equal op ">" ) '(> org-string> org-time>))
14382 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14383 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14384 ((member op '("=" "==")) '(= string= org-time=))
14385 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14386 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14388 (defun org<> (a b) (not (= a b)))
14389 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14390 (defun org-string>= (a b) (not (string< a b)))
14391 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14392 (defun org-string<> (a b) (not (string= a b)))
14393 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14394 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14395 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14396 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14397 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14398 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14399 (defun org-2ft (s)
14400 "Convert S to a floating point time.
14401 If S is already a number, just return it. If it is a string, parse
14402 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14403 (cond
14404 ((numberp s) s)
14405 ((stringp s)
14406 (condition-case nil
14407 (float-time (apply 'encode-time (org-parse-time-string s)))
14408 (error 0.)))
14409 (t 0.)))
14411 (defun org-time-today ()
14412 "Time in seconds today at 0:00.
14413 Returns the float number of seconds since the beginning of the
14414 epoch to the beginning of today (00:00)."
14415 (float-time (apply 'encode-time
14416 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14418 (defun org-matcher-time (s)
14419 "Interpret a time comparison value."
14420 (save-match-data
14421 (cond
14422 ((string= s "<now>") (float-time))
14423 ((string= s "<today>") (org-time-today))
14424 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14425 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14426 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14427 (+ (org-time-today)
14428 (* (string-to-number (match-string 1 s))
14429 (cdr (assoc (match-string 2 s)
14430 '(("d" . 86400.0) ("w" . 604800.0)
14431 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14432 (t (org-2ft s)))))
14434 (defun org-match-any-p (re list)
14435 "Does re match any element of list?"
14436 (setq list (mapcar (lambda (x) (string-match re x)) list))
14437 (delq nil list))
14439 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14440 (defvar org-tags-overlay (make-overlay 1 1))
14441 (org-detach-overlay org-tags-overlay)
14443 (defun org-get-local-tags-at (&optional pos)
14444 "Get a list of tags defined in the current headline."
14445 (org-get-tags-at pos 'local))
14447 (defun org-get-local-tags ()
14448 "Get a list of tags defined in the current headline."
14449 (org-get-tags-at nil 'local))
14451 (defun org-get-tags-at (&optional pos local)
14452 "Get a list of all headline tags applicable at POS.
14453 POS defaults to point. If tags are inherited, the list contains
14454 the targets in the same sequence as the headlines appear, i.e.
14455 the tags of the current headline come last.
14456 When LOCAL is non-nil, only return tags from the current headline,
14457 ignore inherited ones."
14458 (interactive)
14459 (if (and org-trust-scanner-tags
14460 (or (not pos) (equal pos (point)))
14461 (not local))
14462 org-scanner-tags
14463 (let (tags ltags lastpos parent)
14464 (save-excursion
14465 (save-restriction
14466 (widen)
14467 (goto-char (or pos (point)))
14468 (save-match-data
14469 (catch 'done
14470 (condition-case nil
14471 (progn
14472 (org-back-to-heading t)
14473 (while (not (equal lastpos (point)))
14474 (setq lastpos (point))
14475 (when (looking-at
14476 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14477 (setq ltags (org-split-string
14478 (org-match-string-no-properties 1) ":"))
14479 (when parent
14480 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14481 (setq tags (append
14482 (if parent
14483 (org-remove-uninherited-tags ltags)
14484 ltags)
14485 tags)))
14486 (or org-use-tag-inheritance (throw 'done t))
14487 (if local (throw 'done t))
14488 (or (org-up-heading-safe) (error nil))
14489 (setq parent t)))
14490 (error nil)))))
14491 (if local
14492 tags
14493 (reverse (delete-dups
14494 (reverse (append
14495 (org-remove-uninherited-tags
14496 org-file-tags) tags)))))))))
14498 (defun org-add-prop-inherited (s)
14499 (add-text-properties 0 (length s) '(inherited t) s)
14502 (defun org-toggle-tag (tag &optional onoff)
14503 "Toggle the tag TAG for the current line.
14504 If ONOFF is `on' or `off', don't toggle but set to this state."
14505 (let (res current)
14506 (save-excursion
14507 (org-back-to-heading t)
14508 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14509 (point-at-eol) t)
14510 (progn
14511 (setq current (match-string 1))
14512 (replace-match ""))
14513 (setq current ""))
14514 (setq current (nreverse (org-split-string current ":")))
14515 (cond
14516 ((eq onoff 'on)
14517 (setq res t)
14518 (or (member tag current) (push tag current)))
14519 ((eq onoff 'off)
14520 (or (not (member tag current)) (setq current (delete tag current))))
14521 (t (if (member tag current)
14522 (setq current (delete tag current))
14523 (setq res t)
14524 (push tag current))))
14525 (end-of-line 1)
14526 (if current
14527 (progn
14528 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14529 (org-set-tags nil t))
14530 (delete-horizontal-space))
14531 (run-hooks 'org-after-tags-change-hook))
14532 res))
14534 (defun org-align-tags-here (to-col)
14535 ;; Assumes that this is a headline
14536 "Align tags on the current headline to TO-COL."
14537 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14538 (beginning-of-line 1)
14539 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14540 (< pos (match-beginning 2)))
14541 (progn
14542 (setq tags-l (- (match-end 2) (match-beginning 2)))
14543 (goto-char (match-beginning 1))
14544 (insert " ")
14545 (delete-region (point) (1+ (match-beginning 2)))
14546 (setq ncol (max (current-column)
14547 (1+ col)
14548 (if (> to-col 0)
14549 to-col
14550 (- (abs to-col) tags-l))))
14551 (setq p (point))
14552 (insert (make-string (- ncol (current-column)) ?\ ))
14553 (setq ncol (current-column))
14554 (when indent-tabs-mode (tabify p (point-at-eol)))
14555 (org-move-to-column (min ncol col)))
14556 (goto-char pos))))
14558 (defun org-set-tags-command (&optional arg just-align)
14559 "Call the set-tags command for the current entry."
14560 (interactive "P")
14561 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14562 (org-set-tags arg just-align)
14563 (save-excursion
14564 (unless (and (org-region-active-p)
14565 org-loop-over-headlines-in-active-region)
14566 (org-back-to-heading t))
14567 (org-set-tags arg just-align))))
14569 (defun org-set-tags-to (data)
14570 "Set the tags of the current entry to DATA, replacing the current tags.
14571 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14572 If DATA is nil or the empty string, any tags will be removed."
14573 (interactive "sTags: ")
14574 (setq data
14575 (cond
14576 ((eq data nil) "")
14577 ((equal data "") "")
14578 ((stringp data)
14579 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14580 ":"))
14581 ((listp data)
14582 (concat ":" (mapconcat 'identity data ":") ":"))))
14583 (when data
14584 (save-excursion
14585 (org-back-to-heading t)
14586 (when (looking-at org-complex-heading-regexp)
14587 (if (match-end 5)
14588 (progn
14589 (goto-char (match-beginning 5))
14590 (insert data)
14591 (delete-region (point) (point-at-eol))
14592 (org-set-tags nil 'align))
14593 (goto-char (point-at-eol))
14594 (insert " " data)
14595 (org-set-tags nil 'align)))
14596 (beginning-of-line 1)
14597 (if (looking-at ".*?\\([ \t]+\\)$")
14598 (delete-region (match-beginning 1) (match-end 1))))))
14600 (defun org-align-all-tags ()
14601 "Align the tags i all headings."
14602 (interactive)
14603 (save-excursion
14604 (or (ignore-errors (org-back-to-heading t))
14605 (outline-next-heading))
14606 (if (org-at-heading-p)
14607 (org-set-tags t)
14608 (message "No headings"))))
14610 (defvar org-indent-indentation-per-level)
14611 (defun org-set-tags (&optional arg just-align)
14612 "Set the tags for the current headline.
14613 With prefix ARG, realign all tags in headings in the current buffer.
14614 When JUST-ALIGN is non-nil, only align tags."
14615 (interactive "P")
14616 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14617 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14618 'region-start-level 'region))
14619 org-loop-over-headlines-in-active-region)
14620 (org-map-entries
14621 ;; We don't use ARG and JUST-ALIGN here because these args
14622 ;; are not useful when looping over headlines.
14623 `(org-set-tags)
14624 org-loop-over-headlines-in-active-region
14625 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14626 (let* ((re org-outline-regexp-bol)
14627 (current (unless arg (org-get-tags-string)))
14628 (col (current-column))
14629 (org-setting-tags t)
14630 table current-tags inherited-tags ; computed below when needed
14631 tags p0 c0 c1 rpl di tc level)
14632 (if arg
14633 (save-excursion
14634 (goto-char (point-min))
14635 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14636 (while (re-search-forward re nil t)
14637 (org-set-tags nil t)
14638 (end-of-line 1)))
14639 (message "All tags realigned to column %d" org-tags-column))
14640 (if just-align
14641 (setq tags current)
14642 ;; Get a new set of tags from the user
14643 (save-excursion
14644 (setq table (append org-tag-persistent-alist
14645 (or org-tag-alist (org-get-buffer-tags))
14646 (and
14647 org-complete-tags-always-offer-all-agenda-tags
14648 (org-global-tags-completion-table
14649 (org-agenda-files))))
14650 org-last-tags-completion-table table
14651 current-tags (org-split-string current ":")
14652 inherited-tags (nreverse
14653 (nthcdr (length current-tags)
14654 (nreverse (org-get-tags-at))))
14655 tags
14656 (if (or (eq t org-use-fast-tag-selection)
14657 (and org-use-fast-tag-selection
14658 (delq nil (mapcar 'cdr table))))
14659 (org-fast-tag-selection
14660 current-tags inherited-tags table
14661 (if org-fast-tag-selection-include-todo
14662 org-todo-key-alist))
14663 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14664 (org-trim
14665 (org-icompleting-read "Tags: "
14666 'org-tags-completion-function
14667 nil nil current 'org-tags-history))))))
14668 (while (string-match "[-+&]+" tags)
14669 ;; No boolean logic, just a list
14670 (setq tags (replace-match ":" t t tags))))
14672 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14674 (if org-tags-sort-function
14675 (setq tags (mapconcat 'identity
14676 (sort (org-split-string
14677 tags (org-re "[^[:alnum:]_@#%]+"))
14678 org-tags-sort-function) ":")))
14680 (if (string-match "\\`[\t ]*\\'" tags)
14681 (setq tags "")
14682 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14683 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14685 ;; Insert new tags at the correct column
14686 (beginning-of-line 1)
14687 (setq level (or (and (looking-at org-outline-regexp)
14688 (- (match-end 0) (point) 1))
14690 (cond
14691 ((and (equal current "") (equal tags "")))
14692 ((re-search-forward
14693 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14694 (point-at-eol) t)
14695 (if (equal tags "")
14696 (setq rpl "")
14697 (goto-char (match-beginning 0))
14698 (setq c0 (current-column)
14699 ;; compute offset for the case of org-indent-mode active
14700 di (if (org-bound-and-true-p org-indent-mode)
14701 (* (1- org-indent-indentation-per-level) (1- level))
14703 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14704 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14705 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14706 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14707 (replace-match rpl t t)
14708 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14709 tags)
14710 (t (error "Tags alignment failed")))
14711 (org-move-to-column col)
14712 (unless just-align
14713 (run-hooks 'org-after-tags-change-hook))))))
14715 (defun org-change-tag-in-region (beg end tag off)
14716 "Add or remove TAG for each entry in the region.
14717 This works in the agenda, and also in an org-mode buffer."
14718 (interactive
14719 (list (region-beginning) (region-end)
14720 (let ((org-last-tags-completion-table
14721 (if (derived-mode-p 'org-mode)
14722 (org-uniquify
14723 (delq nil (append (org-get-buffer-tags)
14724 (org-global-tags-completion-table))))
14725 (org-global-tags-completion-table))))
14726 (org-icompleting-read
14727 "Tag: " 'org-tags-completion-function nil nil nil
14728 'org-tags-history))
14729 (progn
14730 (message "[s]et or [r]emove? ")
14731 (equal (read-char-exclusive) ?r))))
14732 (if (fboundp 'deactivate-mark) (deactivate-mark))
14733 (let ((agendap (equal major-mode 'org-agenda-mode))
14734 l1 l2 m buf pos newhead (cnt 0))
14735 (goto-char end)
14736 (setq l2 (1- (org-current-line)))
14737 (goto-char beg)
14738 (setq l1 (org-current-line))
14739 (loop for l from l1 to l2 do
14740 (org-goto-line l)
14741 (setq m (get-text-property (point) 'org-hd-marker))
14742 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14743 (and agendap m))
14744 (setq buf (if agendap (marker-buffer m) (current-buffer))
14745 pos (if agendap m (point)))
14746 (with-current-buffer buf
14747 (save-excursion
14748 (save-restriction
14749 (goto-char pos)
14750 (setq cnt (1+ cnt))
14751 (org-toggle-tag tag (if off 'off 'on))
14752 (setq newhead (org-get-heading)))))
14753 (and agendap (org-agenda-change-all-lines newhead m))))
14754 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14756 (defun org-tags-completion-function (string predicate &optional flag)
14757 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14758 (confirm (lambda (x) (stringp (car x)))))
14759 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14760 (setq s1 (match-string 1 string)
14761 s2 (match-string 2 string))
14762 (setq s1 "" s2 string))
14763 (cond
14764 ((eq flag nil)
14765 ;; try completion
14766 (setq rtn (try-completion s2 ctable confirm))
14767 (if (stringp rtn)
14768 (setq rtn
14769 (concat s1 s2 (substring rtn (length s2))
14770 (if (and org-add-colon-after-tag-completion
14771 (assoc rtn ctable))
14772 ":" ""))))
14773 rtn)
14774 ((eq flag t)
14775 ;; all-completions
14776 (all-completions s2 ctable confirm))
14777 ((eq flag 'lambda)
14778 ;; exact match?
14779 (assoc s2 ctable)))))
14781 (defun org-fast-tag-insert (kwd tags face &optional end)
14782 "Insert KDW, and the TAGS, the latter with face FACE.
14783 Also insert END."
14784 (insert (format "%-12s" (concat kwd ":"))
14785 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14786 (or end "")))
14788 (defun org-fast-tag-show-exit (flag)
14789 (save-excursion
14790 (org-goto-line 3)
14791 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14792 (replace-match ""))
14793 (when flag
14794 (end-of-line 1)
14795 (org-move-to-column (- (window-width) 19) t)
14796 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14798 (defun org-set-current-tags-overlay (current prefix)
14799 "Add an overlay to CURRENT tag with PREFIX."
14800 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14801 (if (featurep 'xemacs)
14802 (org-overlay-display org-tags-overlay (concat prefix s)
14803 'secondary-selection)
14804 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14805 (org-overlay-display org-tags-overlay (concat prefix s)))))
14807 (defvar org-last-tag-selection-key nil)
14808 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14809 "Fast tag selection with single keys.
14810 CURRENT is the current list of tags in the headline, INHERITED is the
14811 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14812 possibly with grouping information. TODO-TABLE is a similar table with
14813 TODO keywords, should these have keys assigned to them.
14814 If the keys are nil, a-z are automatically assigned.
14815 Returns the new tags string, or nil to not change the current settings."
14816 (let* ((fulltable (append table todo-table))
14817 (maxlen (apply 'max (mapcar
14818 (lambda (x)
14819 (if (stringp (car x)) (string-width (car x)) 0))
14820 fulltable)))
14821 (buf (current-buffer))
14822 (expert (eq org-fast-tag-selection-single-key 'expert))
14823 (buffer-tags nil)
14824 (fwidth (+ maxlen 3 1 3))
14825 (ncol (/ (- (window-width) 4) fwidth))
14826 (i-face 'org-done)
14827 (c-face 'org-todo)
14828 tg cnt e c char c1 c2 ntable tbl rtn
14829 ov-start ov-end ov-prefix
14830 (exit-after-next org-fast-tag-selection-single-key)
14831 (done-keywords org-done-keywords)
14832 groups ingroup)
14833 (save-excursion
14834 (beginning-of-line 1)
14835 (if (looking-at
14836 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14837 (setq ov-start (match-beginning 1)
14838 ov-end (match-end 1)
14839 ov-prefix "")
14840 (setq ov-start (1- (point-at-eol))
14841 ov-end (1+ ov-start))
14842 (skip-chars-forward "^\n\r")
14843 (setq ov-prefix
14844 (concat
14845 (buffer-substring (1- (point)) (point))
14846 (if (> (current-column) org-tags-column)
14848 (make-string (- org-tags-column (current-column)) ?\ ))))))
14849 (move-overlay org-tags-overlay ov-start ov-end)
14850 (save-window-excursion
14851 (if expert
14852 (set-buffer (get-buffer-create " *Org tags*"))
14853 (delete-other-windows)
14854 (split-window-vertically)
14855 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14856 (erase-buffer)
14857 (org-set-local 'org-done-keywords done-keywords)
14858 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14859 (org-fast-tag-insert "Current" current c-face "\n\n")
14860 (org-fast-tag-show-exit exit-after-next)
14861 (org-set-current-tags-overlay current ov-prefix)
14862 (setq tbl fulltable char ?a cnt 0)
14863 (while (setq e (pop tbl))
14864 (cond
14865 ((equal (car e) :startgroup)
14866 (push '() groups) (setq ingroup t)
14867 (when (not (= cnt 0))
14868 (setq cnt 0)
14869 (insert "\n"))
14870 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14871 ((equal (car e) :endgroup)
14872 (setq ingroup nil cnt 0)
14873 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14874 ((equal e '(:newline))
14875 (when (not (= cnt 0))
14876 (setq cnt 0)
14877 (insert "\n")
14878 (setq e (car tbl))
14879 (while (equal (car tbl) '(:newline))
14880 (insert "\n")
14881 (setq tbl (cdr tbl)))))
14882 ((equal e '(:grouptags)) nil)
14884 (setq tg (copy-sequence (car e)) c2 nil)
14885 (if (cdr e)
14886 (setq c (cdr e))
14887 ;; automatically assign a character.
14888 (setq c1 (string-to-char
14889 (downcase (substring
14890 tg (if (= (string-to-char tg) ?@) 1 0)))))
14891 (if (or (rassoc c1 ntable) (rassoc c1 table))
14892 (while (or (rassoc char ntable) (rassoc char table))
14893 (setq char (1+ char)))
14894 (setq c2 c1))
14895 (setq c (or c2 char)))
14896 (if ingroup (push tg (car groups)))
14897 (setq tg (org-add-props tg nil 'face
14898 (cond
14899 ((not (assoc tg table))
14900 (org-get-todo-face tg))
14901 ((member tg current) c-face)
14902 ((member tg inherited) i-face))))
14903 (if (equal (caar tbl) :grouptags)
14904 (org-add-props tg nil 'face 'org-tag-group))
14905 (if (and (= cnt 0) (not ingroup)) (insert " "))
14906 (insert "[" c "] " tg (make-string
14907 (- fwidth 4 (length tg)) ?\ ))
14908 (push (cons tg c) ntable)
14909 (when (= (setq cnt (1+ cnt)) ncol)
14910 (insert "\n")
14911 (if ingroup (insert " "))
14912 (setq cnt 0)))))
14913 (setq ntable (nreverse ntable))
14914 (insert "\n")
14915 (goto-char (point-min))
14916 (if (not expert) (org-fit-window-to-buffer))
14917 (setq rtn
14918 (catch 'exit
14919 (while t
14920 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14921 (if (not groups) "no " "")
14922 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14923 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14924 (setq org-last-tag-selection-key c)
14925 (cond
14926 ((= c ?\r) (throw 'exit t))
14927 ((= c ?!)
14928 (setq groups (not groups))
14929 (goto-char (point-min))
14930 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14931 ((= c ?\C-c)
14932 (if (not expert)
14933 (org-fast-tag-show-exit
14934 (setq exit-after-next (not exit-after-next)))
14935 (setq expert nil)
14936 (delete-other-windows)
14937 (set-window-buffer (split-window-vertically) " *Org tags*")
14938 (org-switch-to-buffer-other-window " *Org tags*")
14939 (org-fit-window-to-buffer)))
14940 ((or (= c ?\C-g)
14941 (and (= c ?q) (not (rassoc c ntable))))
14942 (org-detach-overlay org-tags-overlay)
14943 (setq quit-flag t))
14944 ((= c ?\ )
14945 (setq current nil)
14946 (if exit-after-next (setq exit-after-next 'now)))
14947 ((= c ?\t)
14948 (condition-case nil
14949 (setq tg (org-icompleting-read
14950 "Tag: "
14951 (or buffer-tags
14952 (with-current-buffer buf
14953 (org-get-buffer-tags)))))
14954 (quit (setq tg "")))
14955 (when (string-match "\\S-" tg)
14956 (add-to-list 'buffer-tags (list tg))
14957 (if (member tg current)
14958 (setq current (delete tg current))
14959 (push tg current)))
14960 (if exit-after-next (setq exit-after-next 'now)))
14961 ((setq e (rassoc c todo-table) tg (car e))
14962 (with-current-buffer buf
14963 (save-excursion (org-todo tg)))
14964 (if exit-after-next (setq exit-after-next 'now)))
14965 ((setq e (rassoc c ntable) tg (car e))
14966 (if (member tg current)
14967 (setq current (delete tg current))
14968 (loop for g in groups do
14969 (if (member tg g)
14970 (mapc (lambda (x)
14971 (setq current (delete x current)))
14972 g)))
14973 (push tg current))
14974 (if exit-after-next (setq exit-after-next 'now))))
14976 ;; Create a sorted list
14977 (setq current
14978 (sort current
14979 (lambda (a b)
14980 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14981 (if (eq exit-after-next 'now) (throw 'exit t))
14982 (goto-char (point-min))
14983 (beginning-of-line 2)
14984 (delete-region (point) (point-at-eol))
14985 (org-fast-tag-insert "Current" current c-face)
14986 (org-set-current-tags-overlay current ov-prefix)
14987 (while (re-search-forward
14988 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14989 (setq tg (match-string 1))
14990 (add-text-properties
14991 (match-beginning 1) (match-end 1)
14992 (list 'face
14993 (cond
14994 ((member tg current) c-face)
14995 ((member tg inherited) i-face)
14996 (t (get-text-property (match-beginning 1) 'face))))))
14997 (goto-char (point-min)))))
14998 (org-detach-overlay org-tags-overlay)
14999 (if rtn
15000 (mapconcat 'identity current ":")
15001 nil))))
15003 (defun org-get-tags-string ()
15004 "Get the TAGS string in the current headline."
15005 (unless (org-at-heading-p t)
15006 (user-error "Not on a heading"))
15007 (save-excursion
15008 (beginning-of-line 1)
15009 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15010 (org-match-string-no-properties 1)
15011 "")))
15013 (defun org-get-tags ()
15014 "Get the list of tags specified in the current headline."
15015 (org-split-string (org-get-tags-string) ":"))
15017 (defun org-get-buffer-tags ()
15018 "Get a table of all tags used in the buffer, for completion."
15019 (let (tags)
15020 (save-excursion
15021 (goto-char (point-min))
15022 (while (re-search-forward
15023 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
15024 (when (equal (char-after (point-at-bol 0)) ?*)
15025 (mapc (lambda (x) (add-to-list 'tags x))
15026 (org-split-string (org-match-string-no-properties 1) ":")))))
15027 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
15028 (mapcar 'list tags)))
15030 ;;;; The mapping API
15032 (defun org-map-entries (func &optional match scope &rest skip)
15033 "Call FUNC at each headline selected by MATCH in SCOPE.
15035 FUNC is a function or a lisp form. The function will be called without
15036 arguments, with the cursor positioned at the beginning of the headline.
15037 The return values of all calls to the function will be collected and
15038 returned as a list.
15040 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15041 does not need to preserve point. After evaluation, the cursor will be
15042 moved to the end of the line (presumably of the headline of the
15043 processed entry) and search continues from there. Under some
15044 circumstances, this may not produce the wanted results. For example,
15045 if you have removed (e.g. archived) the current (sub)tree it could
15046 mean that the next entry will be skipped entirely. In such cases, you
15047 can specify the position from where search should continue by making
15048 FUNC set the variable `org-map-continue-from' to the desired buffer
15049 position.
15051 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15052 Only headlines that are matched by this query will be considered during
15053 the iteration. When MATCH is nil or t, all headlines will be
15054 visited by the iteration.
15056 SCOPE determines the scope of this command. It can be any of:
15058 nil The current buffer, respecting the restriction if any
15059 tree The subtree started with the entry at point
15060 region The entries within the active region, if any
15061 region-start-level
15062 The entries within the active region, but only those at
15063 the same level than the first one.
15064 file The current buffer, without restriction
15065 file-with-archives
15066 The current buffer, and any archives associated with it
15067 agenda All agenda files
15068 agenda-with-archives
15069 All agenda files with any archive files associated with them
15070 \(file1 file2 ...)
15071 If this is a list, all files in the list will be scanned
15073 The remaining args are treated as settings for the skipping facilities of
15074 the scanner. The following items can be given here:
15076 archive skip trees with the archive tag
15077 comment skip trees with the COMMENT keyword
15078 function or Emacs Lisp form:
15079 will be used as value for `org-agenda-skip-function', so
15080 whenever the function returns a position, FUNC will not be
15081 called for that entry and search will continue from the
15082 position returned
15084 If your function needs to retrieve the tags including inherited tags
15085 at the *current* entry, you can use the value of the variable
15086 `org-scanner-tags' which will be much faster than getting the value
15087 with `org-get-tags-at'. If your function gets properties with
15088 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15089 to t around the call to `org-entry-properties' to get the same speedup.
15090 Note that if your function moves around to retrieve tags and properties at
15091 a *different* entry, you cannot use these techniques."
15092 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15093 (not (org-region-active-p)))
15094 (let* ((org-agenda-archives-mode nil) ; just to make sure
15095 (org-agenda-skip-archived-trees (memq 'archive skip))
15096 (org-agenda-skip-comment-trees (memq 'comment skip))
15097 (org-agenda-skip-function
15098 (car (org-delete-all '(comment archive) skip)))
15099 (org-tags-match-list-sublevels t)
15100 (start-level (eq scope 'region-start-level))
15101 matcher file res
15102 org-todo-keywords-for-agenda
15103 org-done-keywords-for-agenda
15104 org-todo-keyword-alist-for-agenda
15105 org-tag-alist-for-agenda
15106 todo-only)
15108 (cond
15109 ((eq match t) (setq matcher t))
15110 ((eq match nil) (setq matcher t))
15111 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15113 (save-excursion
15114 (save-restriction
15115 (cond ((eq scope 'tree)
15116 (org-back-to-heading t)
15117 (org-narrow-to-subtree)
15118 (setq scope nil))
15119 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15120 (org-region-active-p))
15121 ;; If needed, set start-level to a string like "2"
15122 (when start-level
15123 (save-excursion
15124 (goto-char (region-beginning))
15125 (unless (org-at-heading-p) (outline-next-heading))
15126 (setq start-level (org-current-level))))
15127 (narrow-to-region (region-beginning)
15128 (save-excursion
15129 (goto-char (region-end))
15130 (unless (and (bolp) (org-at-heading-p))
15131 (outline-next-heading))
15132 (point)))
15133 (setq scope nil)))
15135 (if (not scope)
15136 (progn
15137 (org-agenda-prepare-buffers
15138 (list (buffer-file-name (current-buffer))))
15139 (setq res (org-scan-tags func matcher todo-only start-level)))
15140 ;; Get the right scope
15141 (cond
15142 ((and scope (listp scope) (symbolp (car scope)))
15143 (setq scope (eval scope)))
15144 ((eq scope 'agenda)
15145 (setq scope (org-agenda-files t)))
15146 ((eq scope 'agenda-with-archives)
15147 (setq scope (org-agenda-files t))
15148 (setq scope (org-add-archive-files scope)))
15149 ((eq scope 'file)
15150 (setq scope (list (buffer-file-name))))
15151 ((eq scope 'file-with-archives)
15152 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15153 (org-agenda-prepare-buffers scope)
15154 (while (setq file (pop scope))
15155 (with-current-buffer (org-find-base-buffer-visiting file)
15156 (save-excursion
15157 (save-restriction
15158 (widen)
15159 (goto-char (point-min))
15160 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15161 res)))
15163 ;;;; Properties
15165 ;;; Setting and retrieving properties
15167 (defconst org-special-properties
15168 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15169 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15170 "The special properties valid in Org-mode.
15172 These are properties that are not defined in the property drawer,
15173 but in some other way.")
15175 (defconst org-default-properties
15176 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15177 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15178 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15179 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15180 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15181 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15182 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15183 "Some properties that are used by Org-mode for various purposes.
15184 Being in this list makes sure that they are offered for completion.")
15186 (defun org-property-action ()
15187 "Do an action on properties."
15188 (interactive)
15189 (let (c)
15190 (org-at-property-p)
15191 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15192 (setq c (read-char-exclusive))
15193 (cond
15194 ((equal c ?s)
15195 (call-interactively 'org-set-property))
15196 ((equal c ?d)
15197 (call-interactively 'org-delete-property))
15198 ((equal c ?D)
15199 (call-interactively 'org-delete-property-globally))
15200 ((equal c ?c)
15201 (call-interactively 'org-compute-property-at-point))
15202 (t (user-error "No such property action %c" c)))))
15204 (defun org-inc-effort ()
15205 "Increment the value of the effort property in the current entry."
15206 (interactive)
15207 (org-set-effort nil t))
15209 (defvar org-clock-effort) ;; Defined in org-clock.el
15210 (defvar org-clock-current-task) ;; Defined in org-clock.el
15211 (defun org-set-effort (&optional value increment)
15212 "Set the effort property of the current entry.
15213 With numerical prefix arg, use the nth allowed value, 0 stands for the
15214 10th allowed value.
15216 When INCREMENT is non-nil, set the property to the next allowed value."
15217 (interactive "P")
15218 (if (equal value 0) (setq value 10))
15219 (let* ((completion-ignore-case t)
15220 (prop org-effort-property)
15221 (cur (org-entry-get nil prop))
15222 (allowed (org-property-get-allowed-values nil prop 'table))
15223 (existing (mapcar 'list (org-property-values prop)))
15224 (heading (nth 4 (org-heading-components)))
15226 (val (cond
15227 ((stringp value) value)
15228 ((and allowed (integerp value))
15229 (or (car (nth (1- value) allowed))
15230 (car (org-last allowed))))
15231 ((and allowed increment)
15232 (or (caadr (member (list cur) allowed))
15233 (user-error "Allowed effort values are not set")))
15234 (allowed
15235 (message "Select 1-9,0, [RET%s]: %s"
15236 (if cur (concat "=" cur) "")
15237 (mapconcat 'car allowed " "))
15238 (setq rpl (read-char-exclusive))
15239 (if (equal rpl ?\r)
15241 (setq rpl (- rpl ?0))
15242 (if (equal rpl 0) (setq rpl 10))
15243 (if (and (> rpl 0) (<= rpl (length allowed)))
15244 (car (nth (1- rpl) allowed))
15245 (org-completing-read "Effort: " allowed nil))))
15247 (let (org-completion-use-ido org-completion-use-iswitchb)
15248 (org-completing-read
15249 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15250 (concat "[" cur "]") "")
15251 ": ")
15252 existing nil nil "" nil cur))))))
15253 (unless (equal (org-entry-get nil prop) val)
15254 (org-entry-put nil prop val))
15255 (save-excursion
15256 (org-back-to-heading t)
15257 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15258 (when (string= heading org-clock-current-task)
15259 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15260 (org-clock-update-mode-line))
15261 (message "%s is now %s" prop val)))
15263 (defun org-at-property-p ()
15264 "Is cursor inside a property drawer?"
15265 (save-excursion
15266 (when (equal 'node-property (car (org-element-at-point)))
15267 (beginning-of-line 1)
15268 (looking-at org-property-re))))
15270 (defun org-get-property-block (&optional beg end force)
15271 "Return the (beg . end) range of the body of the property drawer.
15272 BEG and END are the beginning and end of the current subtree, or of
15273 the part before the first headline. If they are not given, they will
15274 be found. If the drawer does not exist and FORCE is non-nil, create
15275 the drawer."
15276 (catch 'exit
15277 (save-excursion
15278 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15279 (progn (org-back-to-heading t) (point))))
15280 (end (or end (and (not (outline-next-heading)) (point-max))
15281 (point))))
15282 (goto-char beg)
15283 (if (re-search-forward org-property-start-re end t)
15284 (setq beg (1+ (match-end 0)))
15285 (if force
15286 (save-excursion
15287 (org-insert-property-drawer)
15288 (setq end (progn (outline-next-heading) (point))))
15289 (throw 'exit nil))
15290 (goto-char beg)
15291 (if (re-search-forward org-property-start-re end t)
15292 (setq beg (1+ (match-end 0)))))
15293 (if (re-search-forward org-property-end-re end t)
15294 (setq end (match-beginning 0))
15295 (or force (throw 'exit nil))
15296 (goto-char beg)
15297 (setq end beg)
15298 (org-indent-line)
15299 (insert ":END:\n"))
15300 (cons beg end)))))
15302 (defun org-entry-properties (&optional pom which specific)
15303 "Get all properties of the entry at point-or-marker POM.
15304 This includes the TODO keyword, the tags, time strings for deadline,
15305 scheduled, and clocking, and any additional properties defined in the
15306 entry. The return value is an alist, keys may occur multiple times
15307 if the property key was used several times.
15308 POM may also be nil, in which case the current entry is used.
15309 If WHICH is nil or `all', get all properties. If WHICH is
15310 `special' or `standard', only get that subclass. If WHICH
15311 is a string only get exactly this property. SPECIFIC can be a string, the
15312 specific property we are interested in. Specifying it can speed
15313 things up because then unnecessary parsing is avoided."
15314 (setq which (or which 'all))
15315 (org-with-wide-buffer
15316 (org-with-point-at pom
15317 (let ((clockstr (substring org-clock-string 0 -1))
15318 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15319 (case-fold-search nil)
15320 beg end range props sum-props key key1 value string clocksum clocksumt)
15321 (when (and (derived-mode-p 'org-mode)
15322 (ignore-errors (org-back-to-heading t)))
15323 (setq beg (point))
15324 (setq sum-props (get-text-property (point) 'org-summaries))
15325 (setq clocksum (get-text-property (point) :org-clock-minutes)
15326 clocksumt (get-text-property (point) :org-clock-minutes-today))
15327 (outline-next-heading)
15328 (setq end (point))
15329 (when (memq which '(all special))
15330 ;; Get the special properties, like TODO and tags
15331 (goto-char beg)
15332 (when (and (or (not specific) (string= specific "TODO"))
15333 (looking-at org-todo-line-regexp) (match-end 2))
15334 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15335 (when (and (or (not specific) (string= specific "PRIORITY"))
15336 (looking-at org-priority-regexp))
15337 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15338 (when (or (not specific) (string= specific "FILE"))
15339 (push (cons "FILE" buffer-file-name) props))
15340 (when (and (or (not specific) (string= specific "TAGS"))
15341 (setq value (org-get-tags-string))
15342 (string-match "\\S-" value))
15343 (push (cons "TAGS" value) props))
15344 (when (and (or (not specific) (string= specific "ALLTAGS"))
15345 (setq value (org-get-tags-at)))
15346 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15347 ":"))
15348 props))
15349 (when (or (not specific) (string= specific "BLOCKED"))
15350 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15351 (when (or (not specific)
15352 (member specific
15353 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15354 "TIMESTAMP" "TIMESTAMP_IA")))
15355 (catch 'match
15356 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15357 (setq key (if (match-end 1)
15358 (substring (org-match-string-no-properties 1)
15359 0 -1))
15360 string (if (equal key clockstr)
15361 (org-trim
15362 (buffer-substring-no-properties
15363 (match-beginning 3) (goto-char
15364 (point-at-eol))))
15365 (substring (org-match-string-no-properties 3)
15366 1 -1)))
15367 ;; Get the correct property name from the key. This is
15368 ;; necessary if the user has configured time keywords.
15369 (setq key1 (concat key ":"))
15370 (cond
15371 ((not key)
15372 (setq key
15373 (if (= (char-after (match-beginning 3)) ?\[)
15374 "TIMESTAMP_IA" "TIMESTAMP")))
15375 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15376 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15377 ((equal key1 org-closed-string) (setq key "CLOSED"))
15378 ((equal key1 org-clock-string) (setq key "CLOCK")))
15379 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15380 (progn
15381 (push (cons key string) props)
15382 ;; no need to search further if match is found
15383 (throw 'match t))
15384 (when (or (equal key "CLOCK") (not (assoc key props)))
15385 (push (cons key string) props)))))))
15387 (when (memq which '(all standard))
15388 ;; Get the standard properties, like :PROP: ...
15389 (setq range (org-get-property-block beg end))
15390 (when range
15391 (goto-char (car range))
15392 (while (re-search-forward org-property-re
15393 (cdr range) t)
15394 (setq key (org-match-string-no-properties 2)
15395 value (org-trim (or (org-match-string-no-properties 3) "")))
15396 (unless (member key excluded)
15397 (push (cons key (or value "")) props)))))
15398 (if clocksum
15399 (push (cons "CLOCKSUM"
15400 (org-columns-number-to-string (/ (float clocksum) 60.)
15401 'add_times))
15402 props))
15403 (if clocksumt
15404 (push (cons "CLOCKSUM_T"
15405 (org-columns-number-to-string (/ (float clocksumt) 60.)
15406 'add_times))
15407 props))
15408 (unless (assoc "CATEGORY" props)
15409 (push (cons "CATEGORY" (org-get-category)) props))
15410 (append sum-props (nreverse props)))))))
15412 (defun org-entry-get (pom property &optional inherit literal-nil)
15413 "Get value of PROPERTY for entry or content at point-or-marker POM.
15414 If INHERIT is non-nil and the entry does not have the property,
15415 then also check higher levels of the hierarchy.
15416 If INHERIT is the symbol `selective', use inheritance only if the setting
15417 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15418 If the property is present but empty, the return value is the empty string.
15419 If the property is not present at all, nil is returned.
15421 Return the value as a string.
15423 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15424 do not interpret it as the list atom nil. This is used for inheritance
15425 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15426 (org-with-point-at pom
15427 (if (and inherit (if (eq inherit 'selective)
15428 (org-property-inherit-p property)
15430 (org-entry-get-with-inheritance property literal-nil)
15431 (if (member property org-special-properties)
15432 ;; We need a special property. Use `org-entry-properties'
15433 ;; to retrieve it, but specify the wanted property
15434 (cdr (assoc property (org-entry-properties nil 'special property)))
15435 (org-with-wide-buffer
15436 (let ((range (org-get-property-block)))
15437 (when (and range (not (eq (car range) (cdr range)))
15438 (save-excursion
15439 (goto-char (car range))
15440 (re-search-forward
15441 (concat (org-re-property property) "\\|"
15442 (org-re-property (concat property "+")))
15443 (cdr range) t)))
15444 (let* ((props
15445 (list (or (assoc property org-file-properties)
15446 (assoc property org-global-properties)
15447 (assoc property org-global-properties-fixed))))
15448 (ap (lambda (key)
15449 (when (re-search-forward
15450 (org-re-property key) (cdr range) t)
15451 (setq props
15452 (org-update-property-plist
15454 (if (match-end 3)
15455 (org-match-string-no-properties 3) "")
15456 props)))))
15457 val)
15458 (goto-char (car range))
15459 (funcall ap property)
15460 (goto-char (car range))
15461 (while (funcall ap (concat property "+")))
15462 (setq val (cdr (assoc property props)))
15463 (when val (if literal-nil val (org-not-nil val)))))))))))
15465 (defun org-property-or-variable-value (var &optional inherit)
15466 "Check if there is a property fixing the value of VAR.
15467 If yes, return this value. If not, return the current value of the variable."
15468 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15469 (if (and prop (stringp prop) (string-match "\\S-" prop))
15470 (read prop)
15471 (symbol-value var))))
15473 (defun org-entry-delete (pom property)
15474 "Delete the property PROPERTY from entry at point-or-marker POM."
15475 (unless (member property org-special-properties)
15476 (org-with-point-at pom
15477 (let ((range (org-get-property-block)))
15478 (if (and range
15479 (goto-char (car range))
15480 (re-search-forward
15481 (org-re-property property)
15482 (cdr range) t))
15483 (progn
15484 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15485 (org-remove-empty-drawer-at (car range))
15487 nil)))))
15489 ;; Multi-values properties are properties that contain multiple values
15490 ;; These values are assumed to be single words, separated by whitespace.
15491 (defun org-entry-add-to-multivalued-property (pom property value)
15492 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15493 (let* ((old (org-entry-get pom property))
15494 (values (and old (org-split-string old "[ \t]"))))
15495 (setq value (org-entry-protect-space value))
15496 (unless (member value values)
15497 (setq values (append values (list value)))
15498 (org-entry-put pom property
15499 (mapconcat 'identity values " ")))))
15501 (defun org-entry-remove-from-multivalued-property (pom property value)
15502 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15503 (let* ((old (org-entry-get pom property))
15504 (values (and old (org-split-string old "[ \t]"))))
15505 (setq value (org-entry-protect-space value))
15506 (when (member value values)
15507 (setq values (delete value values))
15508 (org-entry-put pom property
15509 (mapconcat 'identity values " ")))))
15511 (defun org-entry-member-in-multivalued-property (pom property value)
15512 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15513 (let* ((old (org-entry-get pom property))
15514 (values (and old (org-split-string old "[ \t]"))))
15515 (setq value (org-entry-protect-space value))
15516 (member value values)))
15518 (defun org-entry-get-multivalued-property (pom property)
15519 "Return a list of values in a multivalued property."
15520 (let* ((value (org-entry-get pom property))
15521 (values (and value (org-split-string value "[ \t]"))))
15522 (mapcar 'org-entry-restore-space values)))
15524 (defun org-entry-put-multivalued-property (pom property &rest values)
15525 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15526 VALUES should be a list of strings. Spaces will be protected."
15527 (org-entry-put pom property
15528 (mapconcat 'org-entry-protect-space values " "))
15529 (let* ((value (org-entry-get pom property))
15530 (values (and value (org-split-string value "[ \t]"))))
15531 (mapcar 'org-entry-restore-space values)))
15533 (defun org-entry-protect-space (s)
15534 "Protect spaces and newline in string S."
15535 (while (string-match " " s)
15536 (setq s (replace-match "%20" t t s)))
15537 (while (string-match "\n" s)
15538 (setq s (replace-match "%0A" t t s)))
15541 (defun org-entry-restore-space (s)
15542 "Restore spaces and newline in string S."
15543 (while (string-match "%20" s)
15544 (setq s (replace-match " " t t s)))
15545 (while (string-match "%0A" s)
15546 (setq s (replace-match "\n" t t s)))
15549 (defvar org-entry-property-inherited-from (make-marker)
15550 "Marker pointing to the entry from where a property was inherited.
15551 Each call to `org-entry-get-with-inheritance' will set this marker to the
15552 location of the entry where the inheritance search matched. If there was
15553 no match, the marker will point nowhere.
15554 Note that also `org-entry-get' calls this function, if the INHERIT flag
15555 is set.")
15557 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15558 "Get PROPERTY of entry or content at point, search higher levels if needed.
15559 The search will stop at the first ancestor which has the property defined.
15560 If the value found is \"nil\", return nil to show that the property
15561 should be considered as undefined (this is the meaning of nil here).
15562 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15563 (move-marker org-entry-property-inherited-from nil)
15564 (let (tmp)
15565 (save-excursion
15566 (save-restriction
15567 (widen)
15568 (catch 'ex
15569 (while t
15570 (when (setq tmp (org-entry-get nil property nil literal-nil))
15571 (or (ignore-errors (org-back-to-heading t))
15572 (goto-char (point-min)))
15573 (move-marker org-entry-property-inherited-from (point))
15574 (throw 'ex tmp))
15575 (or (ignore-errors (org-up-heading-safe))
15576 (throw 'ex nil))))))
15577 (setq tmp (or tmp
15578 (cdr (assoc property org-file-properties))
15579 (cdr (assoc property org-global-properties))
15580 (cdr (assoc property org-global-properties-fixed))))
15581 (if literal-nil tmp (org-not-nil tmp))))
15583 (defvar org-property-changed-functions nil
15584 "Hook called when the value of a property has changed.
15585 Each hook function should accept two arguments, the name of the property
15586 and the new value.")
15588 (defun org-entry-put (pom property value)
15589 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15590 If the value is `nil', it is converted to the empty string.
15591 If it is not a string, an error is raised."
15592 (cond ((null value) (setq value ""))
15593 ((not (stringp value))
15594 (error "Properties values should be strings.")))
15595 (org-with-point-at pom
15596 (org-back-to-heading t)
15597 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15598 range)
15599 (cond
15600 ((equal property "TODO")
15601 (when (and (string-match "\\S-" value)
15602 (not (member value org-todo-keywords-1)))
15603 (user-error "\"%s\" is not a valid TODO state" value))
15604 (if (or (not value)
15605 (not (string-match "\\S-" value)))
15606 (setq value 'none))
15607 (org-todo value)
15608 (org-set-tags nil 'align))
15609 ((equal property "PRIORITY")
15610 (org-priority (if (and value (string-match "\\S-" value))
15611 (string-to-char value) ?\ ))
15612 (org-set-tags nil 'align))
15613 ((equal property "CLOCKSUM")
15614 (if (not (re-search-forward
15615 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15616 (error "Cannot find a clock log")
15617 (goto-char (- (match-end 1) 2))
15618 (cond
15619 ((eq value 'earlier) (org-timestamp-down))
15620 ((eq value 'later) (org-timestamp-up)))
15621 (org-clock-sum-current-item)))
15622 ((equal property "SCHEDULED")
15623 (if (re-search-forward org-scheduled-time-regexp end t)
15624 (cond
15625 ((eq value 'earlier) (org-timestamp-change -1 'day))
15626 ((eq value 'later) (org-timestamp-change 1 'day))
15627 (t (call-interactively 'org-schedule)))
15628 (call-interactively 'org-schedule)))
15629 ((equal property "DEADLINE")
15630 (if (re-search-forward org-deadline-time-regexp end t)
15631 (cond
15632 ((eq value 'earlier) (org-timestamp-change -1 'day))
15633 ((eq value 'later) (org-timestamp-change 1 'day))
15634 (t (call-interactively 'org-deadline)))
15635 (call-interactively 'org-deadline)))
15636 ((member property org-special-properties)
15637 (error "The %s property can not yet be set with `org-entry-put'"
15638 property))
15639 (t ; a non-special property
15640 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15641 (setq range (org-get-property-block beg end 'force))
15642 (goto-char (car range))
15643 (if (re-search-forward
15644 (org-re-property property) (cdr range) t)
15645 (progn
15646 (delete-region (match-beginning 0) (match-end 0))
15647 (goto-char (match-beginning 0)))
15648 (goto-char (cdr range))
15649 (insert "\n")
15650 (backward-char 1)
15651 (org-indent-line))
15652 (insert ":" property ":")
15653 (and value (insert " " value))
15654 (org-indent-line)))))
15655 (run-hook-with-args 'org-property-changed-functions property value)))
15657 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15658 "Get all property keys in the current buffer.
15659 With INCLUDE-SPECIALS, also list the special properties that reflect things
15660 like tags and TODO state.
15661 With INCLUDE-DEFAULTS, also include properties that has special meaning
15662 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15663 and others.
15664 With INCLUDE-COLUMNS, also include property names given in COLUMN
15665 formats in the current buffer."
15666 (let (rtn range cfmt s p)
15667 (save-excursion
15668 (save-restriction
15669 (widen)
15670 (goto-char (point-min))
15671 (while (re-search-forward org-property-start-re nil t)
15672 (setq range (org-get-property-block))
15673 (goto-char (car range))
15674 (while (re-search-forward org-property-re
15675 (cdr range) t)
15676 (add-to-list 'rtn (org-match-string-no-properties 2)))
15677 (outline-next-heading))))
15679 (when include-specials
15680 (setq rtn (append org-special-properties rtn)))
15682 (when include-defaults
15683 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15684 (add-to-list 'rtn org-effort-property))
15686 (when include-columns
15687 (save-excursion
15688 (save-restriction
15689 (widen)
15690 (goto-char (point-min))
15691 (while (re-search-forward
15692 "^[ \t]*\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15693 nil t)
15694 (setq cfmt (match-string 2) s 0)
15695 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15696 cfmt s)
15697 (setq s (match-end 0)
15698 p (match-string 1 cfmt))
15699 (unless (or (equal p "ITEM")
15700 (member p org-special-properties))
15701 (add-to-list 'rtn (match-string 1 cfmt))))))))
15703 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15705 (defun org-property-values (key)
15706 "Return a list of all values of property KEY in the current buffer."
15707 (save-excursion
15708 (save-restriction
15709 (widen)
15710 (goto-char (point-min))
15711 (let ((re (org-re-property key))
15712 values)
15713 (while (re-search-forward re nil t)
15714 (add-to-list 'values (org-trim (match-string 3))))
15715 (delete "" values)))))
15717 (defun org-insert-property-drawer ()
15718 "Insert a property drawer into the current entry."
15719 (org-back-to-heading t)
15720 (looking-at org-outline-regexp)
15721 (let ((indent (if org-adapt-indentation
15722 (- (match-end 0) (match-beginning 0))
15724 (beg (point))
15725 (re (concat "^[ \t]*" org-keyword-time-regexp))
15726 end hiddenp)
15727 (outline-next-heading)
15728 (setq end (point))
15729 (goto-char beg)
15730 (while (re-search-forward re end t))
15731 (setq hiddenp (outline-invisible-p))
15732 (end-of-line 1)
15733 (and (equal (char-after) ?\n) (forward-char 1))
15734 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15735 (if (member (match-string 1) '("CLOCK:" ":END:"))
15736 ;; just skip this line
15737 (beginning-of-line 2)
15738 ;; Drawer start, find the end
15739 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15740 (beginning-of-line 1)))
15741 (org-skip-over-state-notes)
15742 (skip-chars-backward " \t\n\r")
15743 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15744 (forward-char 1))
15745 (goto-char (point-at-eol))
15746 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15747 (beginning-of-line 0)
15748 (org-indent-to-column indent)
15749 (beginning-of-line 2)
15750 (org-indent-to-column indent)
15751 (beginning-of-line 0)
15752 (if hiddenp
15753 (save-excursion
15754 (org-back-to-heading t)
15755 (hide-entry))
15756 (org-flag-drawer t))))
15758 (defun org-insert-drawer (&optional arg drawer)
15759 "Insert a drawer at point.
15761 Optional argument DRAWER, when non-nil, is a string representing
15762 drawer's name. Otherwise, the user is prompted for a name.
15764 If a region is active, insert the drawer around that region
15765 instead.
15767 Point is left between drawer's boundaries."
15768 (interactive "P")
15769 (let* ((drawer (if arg "PROPERTIES"
15770 (or drawer (read-from-minibuffer "Drawer: ")))))
15771 (cond
15772 ;; With C-u, fall back on `org-insert-property-drawer'
15773 (arg (org-insert-property-drawer))
15775 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15776 (user-error "Invalid drawer name"))
15777 ;; With an active region, insert a drawer at point.
15778 ((not (org-region-active-p))
15779 (progn
15780 (unless (bolp) (insert "\n"))
15781 (insert (format ":%s:\n\n:END:\n" drawer))
15782 (forward-line -2)))
15783 ;; Otherwise, insert the drawer at point
15785 (let ((rbeg (region-beginning))
15786 (rend (copy-marker (region-end))))
15787 (unwind-protect
15788 (progn
15789 (goto-char rbeg)
15790 (beginning-of-line)
15791 (when (save-excursion
15792 (re-search-forward org-outline-regexp-bol rend t))
15793 (user-error "Drawers cannot contain headlines"))
15794 ;; Position point at the beginning of the first
15795 ;; non-blank line in region. Insert drawer's opening
15796 ;; there, then indent it.
15797 (org-skip-whitespace)
15798 (beginning-of-line)
15799 (insert ":" drawer ":\n")
15800 (forward-line -1)
15801 (indent-for-tab-command)
15802 ;; Move point to the beginning of the first blank line
15803 ;; after the last non-blank line in region. Insert
15804 ;; drawer's closing, then indent it.
15805 (goto-char rend)
15806 (skip-chars-backward " \r\t\n")
15807 (insert "\n:END:")
15808 (deactivate-mark t)
15809 (indent-for-tab-command)
15810 (unless (eolp) (insert "\n")))
15811 ;; Clear marker, whatever the outcome of insertion is.
15812 (set-marker rend nil)))))))
15814 (defvar org-property-set-functions-alist nil
15815 "Property set function alist.
15816 Each entry should have the following format:
15818 (PROPERTY . READ-FUNCTION)
15820 The read function will be called with the same argument as
15821 `org-completing-read'.")
15823 (defun org-set-property-function (property)
15824 "Get the function that should be used to set PROPERTY.
15825 This is computed according to `org-property-set-functions-alist'."
15826 (or (cdr (assoc property org-property-set-functions-alist))
15827 'org-completing-read))
15829 (defun org-read-property-value (property)
15830 "Read PROPERTY value from user."
15831 (let* ((completion-ignore-case t)
15832 (allowed (org-property-get-allowed-values nil property 'table))
15833 (cur (org-entry-get nil property))
15834 (prompt (concat property " value"
15835 (if (and cur (string-match "\\S-" cur))
15836 (concat " [" cur "]") "") ": "))
15837 (set-function (org-set-property-function property))
15838 (val (if allowed
15839 (funcall set-function prompt allowed nil
15840 (not (get-text-property 0 'org-unrestricted
15841 (caar allowed))))
15842 (let (org-completion-use-ido org-completion-use-iswitchb)
15843 (funcall set-function prompt
15844 (mapcar 'list (org-property-values property))
15845 nil nil "" nil cur)))))
15846 (if (equal val "")
15848 val)))
15850 (defvar org-last-set-property nil)
15851 (defvar org-last-set-property-value nil)
15852 (defun org-read-property-name ()
15853 "Read a property name."
15854 (let* ((completion-ignore-case t)
15855 (keys (org-buffer-property-keys nil t t))
15856 (default-prop (or (save-excursion
15857 (save-match-data
15858 (beginning-of-line)
15859 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15860 (null (string= (match-string 1) "END"))
15861 (match-string 1))))
15862 org-last-set-property))
15863 (property (org-icompleting-read
15864 (concat "Property"
15865 (if default-prop (concat " [" default-prop "]") "")
15866 ": ")
15867 (mapcar 'list keys)
15868 nil nil nil nil
15869 default-prop)))
15870 (if (member property keys)
15871 property
15872 (or (cdr (assoc (downcase property)
15873 (mapcar (lambda (x) (cons (downcase x) x))
15874 keys)))
15875 property))))
15877 (defun org-set-property-and-value (use-last)
15878 "Allow to set [PROPERTY]: [value] direction from prompt.
15879 When use-default, don't even ask, just use the last
15880 \"[PROPERTY]: [value]\" string from the history."
15881 (interactive "P")
15882 (let* ((completion-ignore-case t)
15883 (pv (or (and use-last org-last-set-property-value)
15884 (org-completing-read
15885 "Enter a \"[Property]: [value]\" pair: "
15886 nil nil nil nil nil
15887 org-last-set-property-value)))
15888 prop val)
15889 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15890 (setq prop (match-string 1 pv)
15891 val (match-string 2 pv))
15892 (org-set-property prop val))))
15894 (defun org-set-property (property value)
15895 "In the current entry, set PROPERTY to VALUE.
15896 When called interactively, this will prompt for a property name, offering
15897 completion on existing and default properties. And then it will prompt
15898 for a value, offering completion either on allowed values (via an inherited
15899 xxx_ALL property) or on existing values in other instances of this property
15900 in the current file."
15901 (interactive (list nil nil))
15902 (let* ((property (or property (org-read-property-name)))
15903 (value (or value (org-read-property-value property)))
15904 (fn (cdr (assoc property org-properties-postprocess-alist))))
15905 (setq org-last-set-property property)
15906 (setq org-last-set-property-value (concat property ": " value))
15907 ;; Possibly postprocess the inserted value:
15908 (when fn (setq value (funcall fn value)))
15909 (unless (equal (org-entry-get nil property) value)
15910 (org-entry-put nil property value))))
15912 (defun org-delete-property (property)
15913 "In the current entry, delete PROPERTY."
15914 (interactive
15915 (let* ((completion-ignore-case t)
15916 (cat (org-entry-get (point) "CATEGORY"))
15917 (props0 (org-entry-properties nil 'standard))
15918 (props (if cat props0
15919 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15920 (prop (if (< 1 (length props))
15921 (org-icompleting-read "Property: " props nil t)
15922 (caar props))))
15923 (list prop)))
15924 (if (org-entry-delete nil property)
15925 (message "Property %s deleted" property)))
15927 (defun org-delete-property-globally (property)
15928 "Remove PROPERTY globally, from all entries."
15929 (interactive
15930 (let* ((completion-ignore-case t)
15931 (prop (org-icompleting-read
15932 "Globally remove property: "
15933 (mapcar 'list (org-buffer-property-keys)))))
15934 (list prop)))
15935 (save-excursion
15936 (save-restriction
15937 (widen)
15938 (goto-char (point-min))
15939 (let ((cnt 0))
15940 (while (re-search-forward
15941 (org-re-property property)
15942 nil t)
15943 (setq cnt (1+ cnt))
15944 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15945 (message "Property \"%s\" removed from %d entries" property cnt)))))
15947 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15949 (defun org-compute-property-at-point ()
15950 "Compute the property at point.
15951 This looks for an enclosing column format, extracts the operator and
15952 then applies it to the property in the column format's scope."
15953 (interactive)
15954 (unless (org-at-property-p)
15955 (user-error "Not at a property"))
15956 (let ((prop (org-match-string-no-properties 2)))
15957 (org-columns-get-format-and-top-level)
15958 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15959 (user-error "No operator defined for property %s" prop))
15960 (org-columns-compute prop)))
15962 (defvar org-property-allowed-value-functions nil
15963 "Hook for functions supplying allowed values for a specific property.
15964 The functions must take a single argument, the name of the property, and
15965 return a flat list of allowed values. If \":ETC\" is one of
15966 the values, this means that these values are intended as defaults for
15967 completion, but that other values should be allowed too.
15968 The functions must return nil if they are not responsible for this
15969 property.")
15971 (defun org-property-get-allowed-values (pom property &optional table)
15972 "Get allowed values for the property PROPERTY.
15973 When TABLE is non-nil, return an alist that can directly be used for
15974 completion."
15975 (let (vals)
15976 (cond
15977 ((equal property "TODO")
15978 (setq vals (org-with-point-at pom
15979 (append org-todo-keywords-1 '("")))))
15980 ((equal property "PRIORITY")
15981 (let ((n org-lowest-priority))
15982 (while (>= n org-highest-priority)
15983 (push (char-to-string n) vals)
15984 (setq n (1- n)))))
15985 ((member property org-special-properties))
15986 ((setq vals (run-hook-with-args-until-success
15987 'org-property-allowed-value-functions property)))
15989 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15990 (when (and vals (string-match "\\S-" vals))
15991 (setq vals (car (read-from-string (concat "(" vals ")"))))
15992 (setq vals (mapcar (lambda (x)
15993 (cond ((stringp x) x)
15994 ((numberp x) (number-to-string x))
15995 ((symbolp x) (symbol-name x))
15996 (t "???")))
15997 vals)))))
15998 (when (member ":ETC" vals)
15999 (setq vals (remove ":ETC" vals))
16000 (org-add-props (car vals) '(org-unrestricted t)))
16001 (if table (mapcar 'list vals) vals)))
16003 (defun org-property-previous-allowed-value (&optional previous)
16004 "Switch to the next allowed value for this property."
16005 (interactive)
16006 (org-property-next-allowed-value t))
16008 (defun org-property-next-allowed-value (&optional previous)
16009 "Switch to the next allowed value for this property."
16010 (interactive)
16011 (unless (org-at-property-p)
16012 (user-error "Not at a property"))
16013 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16014 (key (match-string 2))
16015 (value (match-string 3))
16016 (allowed (or (org-property-get-allowed-values (point) key)
16017 (and (member value '("[ ]" "[-]" "[X]"))
16018 '("[ ]" "[X]"))))
16019 (heading (save-match-data (nth 4 (org-heading-components))))
16020 nval)
16021 (unless allowed
16022 (user-error "Allowed values for this property have not been defined"))
16023 (if previous (setq allowed (reverse allowed)))
16024 (if (member value allowed)
16025 (setq nval (car (cdr (member value allowed)))))
16026 (setq nval (or nval (car allowed)))
16027 (if (equal nval value)
16028 (user-error "Only one allowed value for this property"))
16029 (org-at-property-p)
16030 (replace-match (concat " :" key ": " nval) t t)
16031 (org-indent-line)
16032 (beginning-of-line 1)
16033 (skip-chars-forward " \t")
16034 (when (equal prop org-effort-property)
16035 (save-excursion
16036 (org-back-to-heading t)
16037 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
16038 (when (string= org-clock-current-task heading)
16039 (setq org-clock-effort nval)
16040 (org-clock-update-mode-line)))
16041 (run-hook-with-args 'org-property-changed-functions key nval)))
16043 (defun org-find-olp (path &optional this-buffer)
16044 "Return a marker pointing to the entry at outline path OLP.
16045 If anything goes wrong, throw an error.
16046 You can wrap this call to catch the error like this:
16048 (condition-case msg
16049 (org-mobile-locate-entry (match-string 4))
16050 (error (nth 1 msg)))
16052 The return value will then be either a string with the error message,
16053 or a marker if everything is OK.
16055 If THIS-BUFFER is set, the outline path does not contain a file,
16056 only headings."
16057 (let* ((file (if this-buffer buffer-file-name (pop path)))
16058 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16059 (level 1)
16060 (lmin 1)
16061 (lmax 1)
16062 limit re end found pos heading cnt flevel)
16063 (unless buffer (error "File not found :%s" file))
16064 (with-current-buffer buffer
16065 (save-excursion
16066 (save-restriction
16067 (widen)
16068 (setq limit (point-max))
16069 (goto-char (point-min))
16070 (while (setq heading (pop path))
16071 (setq re (format org-complex-heading-regexp-format
16072 (regexp-quote heading)))
16073 (setq cnt 0 pos (point))
16074 (while (re-search-forward re end t)
16075 (setq level (- (match-end 1) (match-beginning 1)))
16076 (if (and (>= level lmin) (<= level lmax))
16077 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16078 (when (= cnt 0) (error "Heading not found on level %d: %s"
16079 lmax heading))
16080 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16081 lmax heading))
16082 (goto-char found)
16083 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16084 (setq end (save-excursion (org-end-of-subtree t t))))
16085 (when (org-at-heading-p)
16086 (point-marker)))))))
16088 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16089 "Find node HEADING in BUFFER.
16090 Return a marker to the heading if it was found, or nil if not.
16091 If POS-ONLY is set, return just the position instead of a marker.
16093 The heading text must match exact, but it may have a TODO keyword,
16094 a priority cookie and tags in the standard locations."
16095 (with-current-buffer (or buffer (current-buffer))
16096 (save-excursion
16097 (save-restriction
16098 (widen)
16099 (goto-char (point-min))
16100 (let (case-fold-search)
16101 (if (re-search-forward
16102 (format org-complex-heading-regexp-format
16103 (regexp-quote heading)) nil t)
16104 (if pos-only
16105 (match-beginning 0)
16106 (move-marker (make-marker) (match-beginning 0)))))))))
16108 (defun org-find-exact-heading-in-directory (heading &optional dir)
16109 "Find Org node headline HEADING in all .org files in directory DIR.
16110 When the target headline is found, return a marker to this location."
16111 (let ((files (directory-files (or dir default-directory)
16112 nil "\\`[^.#].*\\.org\\'"))
16113 file visiting m buffer)
16114 (catch 'found
16115 (while (setq file (pop files))
16116 (message "trying %s" file)
16117 (setq visiting (org-find-base-buffer-visiting file))
16118 (setq buffer (or visiting (find-file-noselect file)))
16119 (setq m (org-find-exact-headline-in-buffer
16120 heading buffer))
16121 (when (and (not m) (not visiting)) (kill-buffer buffer))
16122 (and m (throw 'found m))))))
16124 (defun org-find-entry-with-id (ident)
16125 "Locate the entry that contains the ID property with exact value IDENT.
16126 IDENT can be a string, a symbol or a number, this function will search for
16127 the string representation of it.
16128 Return the position where this entry starts, or nil if there is no such entry."
16129 (interactive "sID: ")
16130 (let ((id (cond
16131 ((stringp ident) ident)
16132 ((symbol-name ident) (symbol-name ident))
16133 ((numberp ident) (number-to-string ident))
16134 (t (error "IDENT %s must be a string, symbol or number" ident))))
16135 (case-fold-search nil))
16136 (save-excursion
16137 (save-restriction
16138 (widen)
16139 (goto-char (point-min))
16140 (when (re-search-forward
16141 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16142 nil t)
16143 (org-back-to-heading t)
16144 (point))))))
16146 ;;;; Timestamps
16148 (defvar org-last-changed-timestamp nil)
16149 (defvar org-last-inserted-timestamp nil
16150 "The last time stamp inserted with `org-insert-time-stamp'.")
16151 (defvar org-ts-what) ; dynamically scoped parameter
16153 (defun org-time-stamp (arg &optional inactive)
16154 "Prompt for a date/time and insert a time stamp.
16155 If the user specifies a time like HH:MM or if this command is
16156 called with at least one prefix argument, the time stamp contains
16157 the date and the time. Otherwise, only the date is be included.
16159 All parts of a date not specified by the user is filled in from
16160 the current date/time. So if you just press return without
16161 typing anything, the time stamp will represent the current
16162 date/time.
16164 If there is already a timestamp at the cursor, it will be
16165 modified.
16167 With two universal prefix arguments, insert an active timestamp
16168 with the current time without prompting the user.
16170 When called from lisp, the timestamp is inactive if INACTIVE is
16171 non-nil."
16172 (interactive "P")
16173 (let* ((ts nil)
16174 (default-time
16175 ;; Default time is either today, or, when entering a range,
16176 ;; the range start.
16177 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16178 (save-excursion
16179 (re-search-backward
16180 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16181 (- (point) 20) t)))
16182 (apply 'encode-time (org-parse-time-string (match-string 1)))
16183 (current-time)))
16184 (default-input (and ts (org-get-compact-tod ts)))
16185 (repeater (save-excursion
16186 (save-match-data
16187 (beginning-of-line)
16188 (when (re-search-forward
16189 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16190 (save-excursion (progn (end-of-line) (point))) t)
16191 (match-string 0)))))
16192 org-time-was-given org-end-time-was-given time)
16193 (cond
16194 ((and (org-at-timestamp-p t)
16195 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16196 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16197 (insert "--")
16198 (setq time (let ((this-command this-command))
16199 (org-read-date arg 'totime nil nil
16200 default-time default-input inactive)))
16201 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16202 ((org-at-timestamp-p t)
16203 (setq time (let ((this-command this-command))
16204 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16205 (when (org-at-timestamp-p t) ; just to get the match data
16206 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16207 (replace-match "")
16208 (setq org-last-changed-timestamp
16209 (org-insert-time-stamp
16210 time (or org-time-was-given arg)
16211 inactive nil nil (list org-end-time-was-given)))
16212 (when repeater (goto-char (1- (point))) (insert " " repeater)
16213 (setq org-last-changed-timestamp
16214 (concat (substring org-last-inserted-timestamp 0 -1)
16215 " " repeater ">"))))
16216 (message "Timestamp updated"))
16217 ((equal arg '(16))
16218 (org-insert-time-stamp (current-time) t inactive))
16220 (setq time (let ((this-command this-command))
16221 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16222 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16223 nil nil (list org-end-time-was-given))))))
16225 ;; FIXME: can we use this for something else, like computing time differences?
16226 (defun org-get-compact-tod (s)
16227 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16228 (let* ((t1 (match-string 1 s))
16229 (h1 (string-to-number (match-string 2 s)))
16230 (m1 (string-to-number (match-string 3 s)))
16231 (t2 (and (match-end 4) (match-string 5 s)))
16232 (h2 (and t2 (string-to-number (match-string 6 s))))
16233 (m2 (and t2 (string-to-number (match-string 7 s))))
16234 dh dm)
16235 (if (not t2)
16237 (setq dh (- h2 h1) dm (- m2 m1))
16238 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16239 (concat t1 "+" (number-to-string dh)
16240 (and (/= 0 dm) (format ":%02d" dm)))))))
16242 (defun org-time-stamp-inactive (&optional arg)
16243 "Insert an inactive time stamp.
16244 An inactive time stamp is enclosed in square brackets instead of angle
16245 brackets. It is inactive in the sense that it does not trigger agenda entries,
16246 does not link to the calendar and cannot be changed with the S-cursor keys.
16247 So these are more for recording a certain time/date."
16248 (interactive "P")
16249 (org-time-stamp arg 'inactive))
16251 (defvar org-date-ovl (make-overlay 1 1))
16252 (overlay-put org-date-ovl 'face 'org-date-selected)
16253 (org-detach-overlay org-date-ovl)
16255 (defvar org-ans1) ; dynamically scoped parameter
16256 (defvar org-ans2) ; dynamically scoped parameter
16258 (defvar org-plain-time-of-day-regexp) ; defined below
16260 (defvar org-overriding-default-time nil) ; dynamically scoped
16261 (defvar org-read-date-overlay nil)
16262 (defvar org-dcst nil) ; dynamically scoped
16263 (defvar org-read-date-history nil)
16264 (defvar org-read-date-final-answer nil)
16265 (defvar org-read-date-analyze-futurep nil)
16266 (defvar org-read-date-analyze-forced-year nil)
16267 (defvar org-read-date-inactive)
16269 (defvar org-read-date-minibuffer-local-map
16270 (let* ((org-replace-disputed-keys nil)
16271 (map (make-sparse-keymap)))
16272 (set-keymap-parent map minibuffer-local-map)
16273 (org-defkey map (kbd ".")
16274 (lambda () (interactive)
16275 ;; Are we at the beginning of the prompt?
16276 (if (looking-back "^[^:]+: ")
16277 (org-eval-in-calendar '(calendar-goto-today))
16278 (insert "."))))
16279 (org-defkey map (kbd "C-.")
16280 (lambda () (interactive)
16281 (org-eval-in-calendar '(calendar-goto-today))))
16282 (org-defkey map [(meta shift left)]
16283 (lambda () (interactive)
16284 (org-eval-in-calendar '(calendar-backward-month 1))))
16285 (org-defkey map [(meta shift right)]
16286 (lambda () (interactive)
16287 (org-eval-in-calendar '(calendar-forward-month 1))))
16288 (org-defkey map [(meta shift up)]
16289 (lambda () (interactive)
16290 (org-eval-in-calendar '(calendar-backward-year 1))))
16291 (org-defkey map [(meta shift down)]
16292 (lambda () (interactive)
16293 (org-eval-in-calendar '(calendar-forward-year 1))))
16294 (org-defkey map [?\e (shift left)]
16295 (lambda () (interactive)
16296 (org-eval-in-calendar '(calendar-backward-month 1))))
16297 (org-defkey map [?\e (shift right)]
16298 (lambda () (interactive)
16299 (org-eval-in-calendar '(calendar-forward-month 1))))
16300 (org-defkey map [?\e (shift up)]
16301 (lambda () (interactive)
16302 (org-eval-in-calendar '(calendar-backward-year 1))))
16303 (org-defkey map [?\e (shift down)]
16304 (lambda () (interactive)
16305 (org-eval-in-calendar '(calendar-forward-year 1))))
16306 (org-defkey map [(shift up)]
16307 (lambda () (interactive)
16308 (org-eval-in-calendar '(calendar-backward-week 1))))
16309 (org-defkey map [(shift down)]
16310 (lambda () (interactive)
16311 (org-eval-in-calendar '(calendar-forward-week 1))))
16312 (org-defkey map [(shift left)]
16313 (lambda () (interactive)
16314 (org-eval-in-calendar '(calendar-backward-day 1))))
16315 (org-defkey map [(shift right)]
16316 (lambda () (interactive)
16317 (org-eval-in-calendar '(calendar-forward-day 1))))
16318 (org-defkey map "!"
16319 (lambda () (interactive)
16320 (org-eval-in-calendar '(diary-view-entries))
16321 (message "")))
16322 (org-defkey map ">"
16323 (lambda () (interactive)
16324 (org-eval-in-calendar '(scroll-calendar-left 1))))
16325 (org-defkey map "<"
16326 (lambda () (interactive)
16327 (org-eval-in-calendar '(scroll-calendar-right 1))))
16328 (org-defkey map "\C-v"
16329 (lambda () (interactive)
16330 (org-eval-in-calendar
16331 '(calendar-scroll-left-three-months 1))))
16332 (org-defkey map "\M-v"
16333 (lambda () (interactive)
16334 (org-eval-in-calendar
16335 '(calendar-scroll-right-three-months 1))))
16336 map)
16337 "Keymap for minibuffer commands when using `org-read-date'.")
16339 (defvar org-def)
16340 (defvar org-defdecode)
16341 (defvar org-with-time)
16343 (defun org-read-date (&optional org-with-time to-time from-string prompt
16344 default-time default-input inactive)
16345 "Read a date, possibly a time, and make things smooth for the user.
16346 The prompt will suggest to enter an ISO date, but you can also enter anything
16347 which will at least partially be understood by `parse-time-string'.
16348 Unrecognized parts of the date will default to the current day, month, year,
16349 hour and minute. If this command is called to replace a timestamp at point,
16350 or to enter the second timestamp of a range, the default time is taken
16351 from the existing stamp. Furthermore, the command prefers the future,
16352 so if you are giving a date where the year is not given, and the day-month
16353 combination is already past in the current year, it will assume you
16354 mean next year. For details, see the manual. A few examples:
16356 3-2-5 --> 2003-02-05
16357 feb 15 --> currentyear-02-15
16358 2/15 --> currentyear-02-15
16359 sep 12 9 --> 2009-09-12
16360 12:45 --> today 12:45
16361 22 sept 0:34 --> currentyear-09-22 0:34
16362 12 --> currentyear-currentmonth-12
16363 Fri --> nearest Friday after today
16364 -Tue --> last Tuesday
16365 etc.
16367 Furthermore you can specify a relative date by giving, as the *first* thing
16368 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16369 change in days weeks, months, years.
16370 With a single plus or minus, the date is relative to today. With a double
16371 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16372 +4d --> four days from today
16373 +4 --> same as above
16374 +2w --> two weeks from today
16375 ++5 --> five days from default date
16377 The function understands only English month and weekday abbreviations.
16379 While prompting, a calendar is popped up - you can also select the
16380 date with the mouse (button 1). The calendar shows a period of three
16381 months. To scroll it to other months, use the keys `>' and `<'.
16382 If you don't like the calendar, turn it off with
16383 \(setq org-read-date-popup-calendar nil)
16385 With optional argument TO-TIME, the date will immediately be converted
16386 to an internal time.
16387 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16388 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16389 still enter a time, and this function will inform the calling routine
16390 about this change. The calling routine may then choose to change the
16391 format used to insert the time stamp into the buffer to include the time.
16392 With optional argument FROM-STRING, read from this string instead from
16393 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16394 the time/date that is used for everything that is not specified by the
16395 user."
16396 (require 'parse-time)
16397 (let* ((org-time-stamp-rounding-minutes
16398 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16399 (org-dcst org-display-custom-times)
16400 (ct (org-current-time))
16401 (org-def (or org-overriding-default-time default-time ct))
16402 (org-defdecode (decode-time org-def))
16403 (dummy (progn
16404 (when (< (nth 2 org-defdecode) org-extend-today-until)
16405 (setcar (nthcdr 2 org-defdecode) -1)
16406 (setcar (nthcdr 1 org-defdecode) 59)
16407 (setq org-def (apply 'encode-time org-defdecode)
16408 org-defdecode (decode-time org-def)))))
16409 (mouse-autoselect-window nil) ; Don't let the mouse jump
16410 (calendar-frame-setup nil)
16411 (calendar-setup nil)
16412 (calendar-move-hook nil)
16413 (calendar-view-diary-initially-flag nil)
16414 (calendar-view-holidays-initially-flag nil)
16415 (timestr (format-time-string
16416 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16417 (prompt (concat (if prompt (concat prompt " ") "")
16418 (format "Date+time [%s]: " timestr)))
16419 ans (org-ans0 "") org-ans1 org-ans2 final)
16421 (cond
16422 (from-string (setq ans from-string))
16423 (org-read-date-popup-calendar
16424 (save-excursion
16425 (save-window-excursion
16426 (calendar)
16427 (org-eval-in-calendar '(setq cursor-type nil) t)
16428 (unwind-protect
16429 (progn
16430 (calendar-forward-day (- (time-to-days org-def)
16431 (calendar-absolute-from-gregorian
16432 (calendar-current-date))))
16433 (org-eval-in-calendar nil t)
16434 (let* ((old-map (current-local-map))
16435 (map (copy-keymap calendar-mode-map))
16436 (minibuffer-local-map
16437 (copy-keymap org-read-date-minibuffer-local-map)))
16438 (org-defkey map (kbd "RET") 'org-calendar-select)
16439 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16440 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16441 (unwind-protect
16442 (progn
16443 (use-local-map map)
16444 (setq org-read-date-inactive inactive)
16445 (add-hook 'post-command-hook 'org-read-date-display)
16446 (setq org-ans0 (read-string prompt default-input
16447 'org-read-date-history nil))
16448 ;; org-ans0: from prompt
16449 ;; org-ans1: from mouse click
16450 ;; org-ans2: from calendar motion
16451 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16452 (remove-hook 'post-command-hook 'org-read-date-display)
16453 (use-local-map old-map)
16454 (when org-read-date-overlay
16455 (delete-overlay org-read-date-overlay)
16456 (setq org-read-date-overlay nil)))))
16457 (bury-buffer "*Calendar*")))))
16459 (t ; Naked prompt only
16460 (unwind-protect
16461 (setq ans (read-string prompt default-input
16462 'org-read-date-history timestr))
16463 (when org-read-date-overlay
16464 (delete-overlay org-read-date-overlay)
16465 (setq org-read-date-overlay nil)))))
16467 (setq final (org-read-date-analyze ans org-def org-defdecode))
16469 (when org-read-date-analyze-forced-year
16470 (message "Year was forced into %s"
16471 (if org-read-date-force-compatible-dates
16472 "compatible range (1970-2037)"
16473 "range representable on this machine"))
16474 (ding))
16476 ;; One round trip to get rid of 34th of August and stuff like that....
16477 (setq final (decode-time (apply 'encode-time final)))
16479 (setq org-read-date-final-answer ans)
16481 (if to-time
16482 (apply 'encode-time final)
16483 (if (and (boundp 'org-time-was-given) org-time-was-given)
16484 (format "%04d-%02d-%02d %02d:%02d"
16485 (nth 5 final) (nth 4 final) (nth 3 final)
16486 (nth 2 final) (nth 1 final))
16487 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16489 (defun org-read-date-display ()
16490 "Display the current date prompt interpretation in the minibuffer."
16491 (when org-read-date-display-live
16492 (when org-read-date-overlay
16493 (delete-overlay org-read-date-overlay))
16494 (when (minibufferp (current-buffer))
16495 (save-excursion
16496 (end-of-line 1)
16497 (while (not (equal (buffer-substring
16498 (max (point-min) (- (point) 4)) (point))
16499 " "))
16500 (insert " ")))
16501 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16502 " " (or org-ans1 org-ans2)))
16503 (org-end-time-was-given nil)
16504 (f (org-read-date-analyze ans org-def org-defdecode))
16505 (fmts (if org-dcst
16506 org-time-stamp-custom-formats
16507 org-time-stamp-formats))
16508 (fmt (if (or org-with-time
16509 (and (boundp 'org-time-was-given) org-time-was-given))
16510 (cdr fmts)
16511 (car fmts)))
16512 (txt (format-time-string fmt (apply 'encode-time f)))
16513 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16514 (txt (concat "=> " txt)))
16515 (when (and org-end-time-was-given
16516 (string-match org-plain-time-of-day-regexp txt))
16517 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16518 org-end-time-was-given
16519 (substring txt (match-end 0)))))
16520 (when org-read-date-analyze-futurep
16521 (setq txt (concat txt " (=>F)")))
16522 (setq org-read-date-overlay
16523 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16524 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16526 (defun org-read-date-analyze (ans org-def org-defdecode)
16527 "Analyze the combined answer of the date prompt."
16528 ;; FIXME: cleanup and comment
16529 (let ((nowdecode (decode-time (current-time)))
16530 delta deltan deltaw deltadef year month day
16531 hour minute second wday pm h2 m2 tl wday1
16532 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16533 (setq org-read-date-analyze-futurep nil
16534 org-read-date-analyze-forced-year nil)
16535 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16536 (setq ans "+0"))
16538 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16539 (setq ans (replace-match "" t t ans)
16540 deltan (car delta)
16541 deltaw (nth 1 delta)
16542 deltadef (nth 2 delta)))
16544 ;; Check if there is an iso week date in there. If yes, store the
16545 ;; info and postpone interpreting it until the rest of the parsing
16546 ;; is done.
16547 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16548 (setq iso-year (if (match-end 1)
16549 (org-small-year-to-year
16550 (string-to-number (match-string 1 ans))))
16551 iso-weekday (if (match-end 3)
16552 (string-to-number (match-string 3 ans)))
16553 iso-week (string-to-number (match-string 2 ans)))
16554 (setq ans (replace-match "" t t ans)))
16556 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16557 (when (string-match
16558 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16559 (setq year (if (match-end 2)
16560 (string-to-number (match-string 2 ans))
16561 (progn (setq kill-year t)
16562 (string-to-number (format-time-string "%Y"))))
16563 month (string-to-number (match-string 3 ans))
16564 day (string-to-number (match-string 4 ans)))
16565 (if (< year 100) (setq year (+ 2000 year)))
16566 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16567 t nil ans)))
16569 ;; Help matching dotted european dates
16570 (when (string-match
16571 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16572 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16573 (setq kill-year t)
16574 (string-to-number (format-time-string "%Y")))
16575 day (string-to-number (match-string 1 ans))
16576 month (string-to-number (match-string 2 ans))
16577 ans (replace-match (format "%04d-%02d-%02d" year month day)
16578 t nil ans)))
16580 ;; Help matching american dates, like 5/30 or 5/30/7
16581 (when (string-match
16582 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16583 (setq year (if (match-end 4)
16584 (string-to-number (match-string 4 ans))
16585 (progn (setq kill-year t)
16586 (string-to-number (format-time-string "%Y"))))
16587 month (string-to-number (match-string 1 ans))
16588 day (string-to-number (match-string 2 ans)))
16589 (if (< year 100) (setq year (+ 2000 year)))
16590 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16591 t nil ans)))
16592 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16593 ;; If there is a time with am/pm, and *no* time without it, we convert
16594 ;; so that matching will be successful.
16595 (loop for i from 1 to 2 do ; twice, for end time as well
16596 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16597 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16598 (setq hour (string-to-number (match-string 1 ans))
16599 minute (if (match-end 3)
16600 (string-to-number (match-string 3 ans))
16602 pm (equal ?p
16603 (string-to-char (downcase (match-string 4 ans)))))
16604 (if (and (= hour 12) (not pm))
16605 (setq hour 0)
16606 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16607 (setq ans (replace-match (format "%02d:%02d" hour minute)
16608 t t ans))))
16610 ;; Check if a time range is given as a duration
16611 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16612 (setq hour (string-to-number (match-string 1 ans))
16613 h2 (+ hour (string-to-number (match-string 3 ans)))
16614 minute (string-to-number (match-string 2 ans))
16615 m2 (+ minute (if (match-end 5) (string-to-number
16616 (match-string 5 ans))0)))
16617 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16618 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16619 t t ans)))
16621 ;; Check if there is a time range
16622 (when (boundp 'org-end-time-was-given)
16623 (setq org-time-was-given nil)
16624 (when (and (string-match org-plain-time-of-day-regexp ans)
16625 (match-end 8))
16626 (setq org-end-time-was-given (match-string 8 ans))
16627 (setq ans (concat (substring ans 0 (match-beginning 7))
16628 (substring ans (match-end 7))))))
16630 (setq tl (parse-time-string ans)
16631 day (or (nth 3 tl) (nth 3 org-defdecode))
16632 month (or (nth 4 tl)
16633 (if (and org-read-date-prefer-future
16634 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16635 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16636 (nth 4 org-defdecode)))
16637 year (or (and (not kill-year) (nth 5 tl))
16638 (if (and org-read-date-prefer-future
16639 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16640 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16641 (nth 5 org-defdecode)))
16642 hour (or (nth 2 tl) (nth 2 org-defdecode))
16643 minute (or (nth 1 tl) (nth 1 org-defdecode))
16644 second (or (nth 0 tl) 0)
16645 wday (nth 6 tl))
16647 (when (and (eq org-read-date-prefer-future 'time)
16648 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16649 (equal day (nth 3 nowdecode))
16650 (equal month (nth 4 nowdecode))
16651 (equal year (nth 5 nowdecode))
16652 (nth 2 tl)
16653 (or (< (nth 2 tl) (nth 2 nowdecode))
16654 (and (= (nth 2 tl) (nth 2 nowdecode))
16655 (nth 1 tl)
16656 (< (nth 1 tl) (nth 1 nowdecode)))))
16657 (setq day (1+ day)
16658 futurep t))
16660 ;; Special date definitions below
16661 (cond
16662 (iso-week
16663 ;; There was an iso week
16664 (require 'cal-iso)
16665 (setq futurep nil)
16666 (setq year (or iso-year year)
16667 day (or iso-weekday wday 1)
16668 wday nil ; to make sure that the trigger below does not match
16669 iso-date (calendar-gregorian-from-absolute
16670 (calendar-absolute-from-iso
16671 (list iso-week day year))))
16672 ; FIXME: Should we also push ISO weeks into the future?
16673 ; (when (and org-read-date-prefer-future
16674 ; (not iso-year)
16675 ; (< (calendar-absolute-from-gregorian iso-date)
16676 ; (time-to-days (current-time))))
16677 ; (setq year (1+ year)
16678 ; iso-date (calendar-gregorian-from-absolute
16679 ; (calendar-absolute-from-iso
16680 ; (list iso-week day year)))))
16681 (setq month (car iso-date)
16682 year (nth 2 iso-date)
16683 day (nth 1 iso-date)))
16684 (deltan
16685 (setq futurep nil)
16686 (unless deltadef
16687 (let ((now (decode-time (current-time))))
16688 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16689 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16690 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16691 ((equal deltaw "m") (setq month (+ month deltan)))
16692 ((equal deltaw "y") (setq year (+ year deltan)))))
16693 ((and wday (not (nth 3 tl)))
16694 ;; Weekday was given, but no day, so pick that day in the week
16695 ;; on or after the derived date.
16696 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16697 (unless (equal wday wday1)
16698 (setq day (+ day (% (- wday wday1 -7) 7))))))
16699 (if (and (boundp 'org-time-was-given)
16700 (nth 2 tl))
16701 (setq org-time-was-given t))
16702 (if (< year 100) (setq year (+ 2000 year)))
16703 ;; Check of the date is representable
16704 (if org-read-date-force-compatible-dates
16705 (progn
16706 (if (< year 1970)
16707 (setq year 1970 org-read-date-analyze-forced-year t))
16708 (if (> year 2037)
16709 (setq year 2037 org-read-date-analyze-forced-year t)))
16710 (condition-case nil
16711 (ignore (encode-time second minute hour day month year))
16712 (error
16713 (setq year (nth 5 org-defdecode))
16714 (setq org-read-date-analyze-forced-year t))))
16715 (setq org-read-date-analyze-futurep futurep)
16716 (list second minute hour day month year)))
16718 (defvar parse-time-weekdays)
16719 (defun org-read-date-get-relative (s today default)
16720 "Check string S for special relative date string.
16721 TODAY and DEFAULT are internal times, for today and for a default.
16722 Return shift list (N what def-flag)
16723 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16724 N is the number of WHATs to shift.
16725 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16726 the DEFAULT date rather than TODAY."
16727 (require 'parse-time)
16728 (when (and
16729 (string-match
16730 (concat
16731 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16732 "\\([0-9]+\\)?"
16733 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16734 "\\([ \t]\\|$\\)") s)
16735 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16736 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16737 (string-to-char (substring (match-string 1 s) -1))
16738 ?+))
16739 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16740 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16741 (what (if (match-end 3) (match-string 3 s) "d"))
16742 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16743 (date (if rel default today))
16744 (wday (nth 6 (decode-time date)))
16745 delta)
16746 (if wday1
16747 (progn
16748 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16749 (if (= delta 0) (setq delta 7))
16750 (if (= dir ?-)
16751 (progn
16752 (setq delta (- delta 7))
16753 (if (= delta 0) (setq delta -7))))
16754 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16755 (list delta "d" rel))
16756 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16758 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16759 "Turn a user-specified date into the internal representation.
16760 The internal representation needed by the calendar is (month day year).
16761 This is a wrapper to handle the brain-dead convention in calendar that
16762 user function argument order change dependent on argument order."
16763 (if (boundp 'calendar-date-style)
16764 (cond
16765 ((eq calendar-date-style 'american)
16766 (list arg1 arg2 arg3))
16767 ((eq calendar-date-style 'european)
16768 (list arg2 arg1 arg3))
16769 ((eq calendar-date-style 'iso)
16770 (list arg2 arg3 arg1)))
16771 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16772 (if (org-bound-and-true-p european-calendar-style)
16773 (list arg2 arg1 arg3)
16774 (list arg1 arg2 arg3)))))
16776 (defun org-eval-in-calendar (form &optional keepdate)
16777 "Eval FORM in the calendar window and return to current window.
16778 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16779 otherwise stick to the current value of `org-ans2'."
16780 (let ((sf (selected-frame))
16781 (sw (selected-window)))
16782 (select-window (get-buffer-window "*Calendar*" t))
16783 (eval form)
16784 (when (and (not keepdate) (calendar-cursor-to-date))
16785 (let* ((date (calendar-cursor-to-date))
16786 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16787 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16788 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16789 (select-window sw)
16790 (org-select-frame-set-input-focus sf)))
16792 (defun org-calendar-select ()
16793 "Return to `org-read-date' with the date currently selected.
16794 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16795 (interactive)
16796 (when (calendar-cursor-to-date)
16797 (let* ((date (calendar-cursor-to-date))
16798 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16799 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16800 (if (active-minibuffer-window) (exit-minibuffer))))
16802 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16803 "Insert a date stamp for the date given by the internal TIME.
16804 WITH-HM means use the stamp format that includes the time of the day.
16805 INACTIVE means use square brackets instead of angular ones, so that the
16806 stamp will not contribute to the agenda.
16807 PRE and POST are optional strings to be inserted before and after the
16808 stamp.
16809 The command returns the inserted time stamp."
16810 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16811 stamp)
16812 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16813 (insert-before-markers (or pre ""))
16814 (when (listp extra)
16815 (setq extra (car extra))
16816 (if (and (stringp extra)
16817 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16818 (setq extra (format "-%02d:%02d"
16819 (string-to-number (match-string 1 extra))
16820 (string-to-number (match-string 2 extra))))
16821 (setq extra nil)))
16822 (when extra
16823 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16824 (insert-before-markers (setq stamp (format-time-string fmt time)))
16825 (insert-before-markers (or post ""))
16826 (setq org-last-inserted-timestamp stamp)))
16828 (defun org-toggle-time-stamp-overlays ()
16829 "Toggle the use of custom time stamp formats."
16830 (interactive)
16831 (setq org-display-custom-times (not org-display-custom-times))
16832 (unless org-display-custom-times
16833 (let ((p (point-min)) (bmp (buffer-modified-p)))
16834 (while (setq p (next-single-property-change p 'display))
16835 (if (and (get-text-property p 'display)
16836 (eq (get-text-property p 'face) 'org-date))
16837 (remove-text-properties
16838 p (setq p (next-single-property-change p 'display))
16839 '(display t))))
16840 (set-buffer-modified-p bmp)))
16841 (if (featurep 'xemacs)
16842 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16843 (org-restart-font-lock)
16844 (setq org-table-may-need-update t)
16845 (if org-display-custom-times
16846 (message "Time stamps are overlaid with custom format")
16847 (message "Time stamp overlays removed")))
16849 (defun org-display-custom-time (beg end)
16850 "Overlay modified time stamp format over timestamp between BEG and END."
16851 (let* ((ts (buffer-substring beg end))
16852 t1 w1 with-hm tf time str w2 (off 0))
16853 (save-match-data
16854 (setq t1 (org-parse-time-string ts t))
16855 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16856 (setq off (- (match-end 0) (match-beginning 0)))))
16857 (setq end (- end off))
16858 (setq w1 (- end beg)
16859 with-hm (and (nth 1 t1) (nth 2 t1))
16860 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16861 time (org-fix-decoded-time t1)
16862 str (org-add-props
16863 (format-time-string
16864 (substring tf 1 -1) (apply 'encode-time time))
16865 nil 'mouse-face 'highlight)
16866 w2 (length str))
16867 (if (not (= w2 w1))
16868 (add-text-properties (1+ beg) (+ 2 beg)
16869 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16870 (if (featurep 'xemacs)
16871 (progn
16872 (put-text-property beg end 'invisible t)
16873 (put-text-property beg end 'end-glyph (make-glyph str)))
16874 (put-text-property beg end 'display str))))
16876 (defun org-translate-time (string)
16877 "Translate all timestamps in STRING to custom format.
16878 But do this only if the variable `org-display-custom-times' is set."
16879 (when org-display-custom-times
16880 (save-match-data
16881 (let* ((start 0)
16882 (re org-ts-regexp-both)
16883 t1 with-hm inactive tf time str beg end)
16884 (while (setq start (string-match re string start))
16885 (setq beg (match-beginning 0)
16886 end (match-end 0)
16887 t1 (save-match-data
16888 (org-parse-time-string (substring string beg end) t))
16889 with-hm (and (nth 1 t1) (nth 2 t1))
16890 inactive (equal (substring string beg (1+ beg)) "[")
16891 tf (funcall (if with-hm 'cdr 'car)
16892 org-time-stamp-custom-formats)
16893 time (org-fix-decoded-time t1)
16894 str (format-time-string
16895 (concat
16896 (if inactive "[" "<") (substring tf 1 -1)
16897 (if inactive "]" ">"))
16898 (apply 'encode-time time))
16899 string (replace-match str t t string)
16900 start (+ start (length str)))))))
16901 string)
16903 (defun org-fix-decoded-time (time)
16904 "Set 0 instead of nil for the first 6 elements of time.
16905 Don't touch the rest."
16906 (let ((n 0))
16907 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16909 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16911 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16912 "Difference between TIMESTAMP-STRING and now in days.
16913 If SECONDS is non-nil, return the difference in seconds."
16914 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16915 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16916 (funcall fdiff (current-time)))))
16918 (defun org-deadline-close (timestamp-string &optional ndays)
16919 "Is the time in TIMESTAMP-STRING close to the current date?"
16920 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16921 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16922 (not (org-entry-is-done-p))))
16924 (defun org-get-wdays (ts &optional delay zero-delay)
16925 "Get the deadline lead time appropriate for timestring TS.
16926 When DELAY is non-nil, get the delay time for scheduled items
16927 instead of the deadline lead time. When ZERO-DELAY is non-nil
16928 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16929 don't try to find the delay cookie in the scheduled timestamp."
16930 (let ((tv (if delay org-scheduled-delay-days
16931 org-deadline-warning-days)))
16932 (cond
16933 ((or (and delay (< tv 0))
16934 (and delay zero-delay (<= tv 0))
16935 (and (not delay) (<= tv 0)))
16936 ;; Enforce this value no matter what
16937 (- tv))
16938 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16939 ;; lead time is specified.
16940 (floor (* (string-to-number (match-string 1 ts))
16941 (cdr (assoc (match-string 2 ts)
16942 '(("d" . 1) ("w" . 7)
16943 ("m" . 30.4) ("y" . 365.25)
16944 ("h" . 0.041667)))))))
16945 ;; go for the default.
16946 (t tv))))
16948 (defun org-calendar-select-mouse (ev)
16949 "Return to `org-read-date' with the date currently selected.
16950 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16951 (interactive "e")
16952 (mouse-set-point ev)
16953 (when (calendar-cursor-to-date)
16954 (let* ((date (calendar-cursor-to-date))
16955 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16956 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16957 (if (active-minibuffer-window) (exit-minibuffer))))
16959 (defun org-check-deadlines (ndays)
16960 "Check if there are any deadlines due or past due.
16961 A deadline is considered due if it happens within `org-deadline-warning-days'
16962 days from today's date. If the deadline appears in an entry marked DONE,
16963 it is not shown. The prefix arg NDAYS can be used to test that many
16964 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16965 (interactive "P")
16966 (let* ((org-warn-days
16967 (cond
16968 ((equal ndays '(4)) 100000)
16969 (ndays (prefix-numeric-value ndays))
16970 (t (abs org-deadline-warning-days))))
16971 (case-fold-search nil)
16972 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16973 (callback
16974 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16976 (message "%d deadlines past-due or due within %d days"
16977 (org-occur regexp nil callback)
16978 org-warn-days)))
16980 (defsubst org-re-timestamp (type)
16981 "Return a regexp for timestamp TYPE.
16982 Allowed values for TYPE are:
16984 all: all timestamps
16985 active: only active timestamps (<...>)
16986 inactive: only inactive timestamps ([...])
16987 scheduled: only scheduled timestamps
16988 deadline: only deadline timestamps
16989 closed: only closed time-stamps
16991 When TYPE is nil, fall back on returning a regexp that matches
16992 both scheduled and deadline timestamps."
16993 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16994 ((eq type 'active) org-ts-regexp)
16995 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16996 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16997 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16998 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16999 ((eq type 'scheduled-or-deadline)
17000 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
17002 (defun org-check-before-date (date)
17003 "Check if there are deadlines or scheduled entries before DATE."
17004 (interactive (list (org-read-date)))
17005 (let ((case-fold-search nil)
17006 (regexp (org-re-timestamp org-ts-type))
17007 (callback
17008 (lambda () (time-less-p
17009 (org-time-string-to-time (match-string 1))
17010 (org-time-string-to-time date)))))
17011 (message "%d entries before %s"
17012 (org-occur regexp nil callback) date)))
17014 (defun org-check-after-date (date)
17015 "Check if there are deadlines or scheduled entries after DATE."
17016 (interactive (list (org-read-date)))
17017 (let ((case-fold-search nil)
17018 (regexp (org-re-timestamp org-ts-type))
17019 (callback
17020 (lambda () (not
17021 (time-less-p
17022 (org-time-string-to-time (match-string 1))
17023 (org-time-string-to-time date))))))
17024 (message "%d entries after %s"
17025 (org-occur regexp nil callback) date)))
17027 (defun org-check-dates-range (start-date end-date)
17028 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17029 (interactive (list (org-read-date nil nil nil "Range starts")
17030 (org-read-date nil nil nil "Range end")))
17031 (let ((case-fold-search nil)
17032 (regexp (org-re-timestamp org-ts-type))
17033 (callback
17034 (lambda ()
17035 (let ((match (match-string 1)))
17036 (and
17037 (not (time-less-p
17038 (org-time-string-to-time match)
17039 (org-time-string-to-time start-date)))
17040 (time-less-p
17041 (org-time-string-to-time match)
17042 (org-time-string-to-time end-date)))))))
17043 (message "%d entries between %s and %s"
17044 (org-occur regexp nil callback) start-date end-date)))
17046 (defun org-evaluate-time-range (&optional to-buffer)
17047 "Evaluate a time range by computing the difference between start and end.
17048 Normally the result is just printed in the echo area, but with prefix arg
17049 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17050 If the time range is actually in a table, the result is inserted into the
17051 next column.
17052 For time difference computation, a year is assumed to be exactly 365
17053 days in order to avoid rounding problems."
17054 (interactive "P")
17056 (org-clock-update-time-maybe)
17057 (save-excursion
17058 (unless (org-at-date-range-p t)
17059 (goto-char (point-at-bol))
17060 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17061 (if (not (org-at-date-range-p t))
17062 (user-error "Not at a time-stamp range, and none found in current line")))
17063 (let* ((ts1 (match-string 1))
17064 (ts2 (match-string 2))
17065 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17066 (match-end (match-end 0))
17067 (time1 (org-time-string-to-time ts1))
17068 (time2 (org-time-string-to-time ts2))
17069 (t1 (org-float-time time1))
17070 (t2 (org-float-time time2))
17071 (diff (abs (- t2 t1)))
17072 (negative (< (- t2 t1) 0))
17073 ;; (ys (floor (* 365 24 60 60)))
17074 (ds (* 24 60 60))
17075 (hs (* 60 60))
17076 (fy "%dy %dd %02d:%02d")
17077 (fy1 "%dy %dd")
17078 (fd "%dd %02d:%02d")
17079 (fd1 "%dd")
17080 (fh "%02d:%02d")
17081 y d h m align)
17082 (if havetime
17083 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17085 d (floor (/ diff ds)) diff (mod diff ds)
17086 h (floor (/ diff hs)) diff (mod diff hs)
17087 m (floor (/ diff 60)))
17088 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17090 d (floor (+ (/ diff ds) 0.5))
17091 h 0 m 0))
17092 (if (not to-buffer)
17093 (message "%s" (org-make-tdiff-string y d h m))
17094 (if (org-at-table-p)
17095 (progn
17096 (goto-char match-end)
17097 (setq align t)
17098 (and (looking-at " *|") (goto-char (match-end 0))))
17099 (goto-char match-end))
17100 (if (looking-at
17101 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17102 (replace-match ""))
17103 (if negative (insert " -"))
17104 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17105 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17106 (insert " " (format fh h m))))
17107 (if align (org-table-align))
17108 (message "Time difference inserted")))))
17110 (defun org-make-tdiff-string (y d h m)
17111 (let ((fmt "")
17112 (l nil))
17113 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17114 l (push y l)))
17115 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17116 l (push d l)))
17117 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17118 l (push h l)))
17119 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17120 l (push m l)))
17121 (apply 'format fmt (nreverse l))))
17123 (defun org-time-string-to-time (s &optional buffer pos)
17124 "Convert a timestamp string into internal time."
17125 (condition-case errdata
17126 (apply 'encode-time (org-parse-time-string s))
17127 (error (error "Bad timestamp `%s'%s\nError was: %s"
17128 s (if (not (and buffer pos))
17130 (format " at %d in buffer `%s'" pos buffer))
17131 (cdr errdata)))))
17133 (defun org-time-string-to-seconds (s)
17134 "Convert a timestamp string to a number of seconds."
17135 (org-float-time (org-time-string-to-time s)))
17137 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17138 "Convert a time stamp to an absolute day number.
17139 If there is a specifier for a cyclic time stamp, get the closest
17140 date to DAYNR.
17141 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17142 The variable `date' is bound by the calendar when this is called."
17143 (cond
17144 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17145 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17146 daynr
17147 (+ daynr 1000)))
17148 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17149 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17150 (time-to-days (current-time))) (match-string 0 s)
17151 prefer show-all))
17152 (t (time-to-days
17153 (condition-case errdata
17154 (apply 'encode-time (org-parse-time-string s))
17155 (error (error "Bad timestamp `%s'%s\nError was: %s"
17156 s (if (not (and buffer pos))
17158 (format " at %d in buffer `%s'" pos buffer))
17159 (cdr errdata))))))))
17161 (defun org-days-to-iso-week (days)
17162 "Return the iso week number."
17163 (require 'cal-iso)
17164 (car (calendar-iso-from-absolute days)))
17166 (defun org-small-year-to-year (year)
17167 "Convert 2-digit years into 4-digit years.
17168 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17169 The year 2000 cannot be abbreviated. Any year larger than 99
17170 is returned unchanged."
17171 (if (< year 38)
17172 (setq year (+ 2000 year))
17173 (if (< year 100)
17174 (setq year (+ 1900 year))))
17175 year)
17177 (defun org-time-from-absolute (d)
17178 "Return the time corresponding to date D.
17179 D may be an absolute day number, or a calendar-type list (month day year)."
17180 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17181 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17183 (defun org-calendar-holiday ()
17184 "List of holidays, for Diary display in Org-mode."
17185 (require 'holidays)
17186 (let ((hl (funcall
17187 (if (fboundp 'calendar-check-holidays)
17188 'calendar-check-holidays 'check-calendar-holidays) date)))
17189 (if hl (mapconcat 'identity hl "; "))))
17191 (defun org-diary-sexp-entry (sexp entry date)
17192 "Process a SEXP diary ENTRY for DATE."
17193 (require 'diary-lib)
17194 (let ((result (if calendar-debug-sexp
17195 (let ((stack-trace-on-error t))
17196 (eval (car (read-from-string sexp))))
17197 (condition-case nil
17198 (eval (car (read-from-string sexp)))
17199 (error
17200 (beep)
17201 (message "Bad sexp at line %d in %s: %s"
17202 (org-current-line)
17203 (buffer-file-name) sexp)
17204 (sleep-for 2))))))
17205 (cond ((stringp result) (split-string result "; "))
17206 ((and (consp result)
17207 (not (consp (cdr result)))
17208 (stringp (cdr result))) (cdr result))
17209 ((and (consp result)
17210 (stringp (car result))) result)
17211 (result entry))))
17213 (defun org-diary-to-ical-string (frombuf)
17214 "Get iCalendar entries from diary entries in buffer FROMBUF.
17215 This uses the icalendar.el library."
17216 (let* ((tmpdir (if (featurep 'xemacs)
17217 (temp-directory)
17218 temporary-file-directory))
17219 (tmpfile (make-temp-name
17220 (expand-file-name "orgics" tmpdir)))
17221 buf rtn b e)
17222 (with-current-buffer frombuf
17223 (icalendar-export-region (point-min) (point-max) tmpfile)
17224 (setq buf (find-buffer-visiting tmpfile))
17225 (set-buffer buf)
17226 (goto-char (point-min))
17227 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17228 (setq b (match-beginning 0)))
17229 (goto-char (point-max))
17230 (if (re-search-backward "^END:VEVENT" nil t)
17231 (setq e (match-end 0)))
17232 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17233 (kill-buffer buf)
17234 (delete-file tmpfile)
17235 rtn))
17237 (defun org-closest-date (start current change prefer show-all)
17238 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17239 When PREFER is `past', return a date that is either CURRENT or past.
17240 When PREFER is `future', return a date that is either CURRENT or future.
17241 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17242 ;; Make the proper lists from the dates
17243 (catch 'exit
17244 (let ((a1 '(("h" . hour)
17245 ("d" . day)
17246 ("w" . week)
17247 ("m" . month)
17248 ("y" . year)))
17249 (shour (nth 2 (org-parse-time-string start)))
17250 dn dw sday cday n1 n2 n0
17251 d m y y1 y2 date1 date2 nmonths nm ny m2)
17253 (setq start (org-date-to-gregorian start)
17254 current (org-date-to-gregorian
17255 (if show-all
17256 current
17257 (time-to-days (current-time))))
17258 sday (calendar-absolute-from-gregorian start)
17259 cday (calendar-absolute-from-gregorian current))
17261 (if (<= cday sday) (throw 'exit sday))
17263 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17264 (setq dn (string-to-number (match-string 1 change))
17265 dw (cdr (assoc (match-string 2 change) a1)))
17266 (user-error "Invalid change specifier: %s" change))
17267 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17268 (cond
17269 ((eq dw 'hour)
17270 (let ((missing-hours
17271 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17272 dn)))
17273 (setq n1 (if (zerop missing-hours) cday
17274 (- cday (1+ (floor (/ missing-hours 24)))))
17275 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17276 ((eq dw 'day)
17277 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17278 n2 (+ n1 dn)))
17279 ((eq dw 'year)
17280 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17281 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17282 (setq date1 (list m d y1)
17283 n1 (calendar-absolute-from-gregorian date1)
17284 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17285 n2 (calendar-absolute-from-gregorian date2)))
17286 ((eq dw 'month)
17287 ;; approx number of month between the two dates
17288 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17289 ;; How often does dn fit in there?
17290 (setq d (nth 1 start) m (car start) y (nth 2 start)
17291 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17292 m (+ m nm)
17293 ny (floor (/ m 12))
17294 y (+ y ny)
17295 m (- m (* ny 12)))
17296 (while (> m 12) (setq m (- m 12) y (1+ y)))
17297 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17298 (setq m2 (+ m dn) y2 y)
17299 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17300 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17301 (while (<= n2 cday)
17302 (setq n1 n2 m m2 y y2)
17303 (setq m2 (+ m dn) y2 y)
17304 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17305 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17306 ;; Make sure n1 is the earlier date
17307 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17308 (if show-all
17309 (cond
17310 ((eq prefer 'past) (if (= cday n2) n2 n1))
17311 ((eq prefer 'future) (if (= cday n1) n1 n2))
17312 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17313 (cond
17314 ((eq prefer 'past) (if (= cday n2) n2 n1))
17315 ((eq prefer 'future) (if (= cday n1) n1 n2))
17316 (t (if (= cday n1) n1 n2)))))))
17318 (defun org-date-to-gregorian (date)
17319 "Turn any specification of DATE into a Gregorian date for the calendar."
17320 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17321 ((and (listp date) (= (length date) 3)) date)
17322 ((stringp date)
17323 (setq date (org-parse-time-string date))
17324 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17325 ((listp date)
17326 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17328 (defun org-parse-time-string (s &optional nodefault)
17329 "Parse the standard Org-mode time string.
17330 This should be a lot faster than the normal `parse-time-string'.
17331 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17332 hour and minute fields will be nil if not given."
17333 (cond ((string-match org-ts-regexp0 s)
17334 (list 0
17335 (if (or (match-beginning 8) (not nodefault))
17336 (string-to-number (or (match-string 8 s) "0")))
17337 (if (or (match-beginning 7) (not nodefault))
17338 (string-to-number (or (match-string 7 s) "0")))
17339 (string-to-number (match-string 4 s))
17340 (string-to-number (match-string 3 s))
17341 (string-to-number (match-string 2 s))
17342 nil nil nil))
17343 ((string-match "^<[^>]+>$" s)
17344 (decode-time (seconds-to-time (org-matcher-time s))))
17345 (t (error "Not a standard Org-mode time string: %s" s))))
17347 (defun org-timestamp-up (&optional arg)
17348 "Increase the date item at the cursor by one.
17349 If the cursor is on the year, change the year. If it is on the month,
17350 the day or the time, change that.
17351 With prefix ARG, change by that many units."
17352 (interactive "p")
17353 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17355 (defun org-timestamp-down (&optional arg)
17356 "Decrease the date item at the cursor by one.
17357 If the cursor is on the year, change the year. If it is on the month,
17358 the day or the time, change that.
17359 With prefix ARG, change by that many units."
17360 (interactive "p")
17361 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17363 (defun org-timestamp-up-day (&optional arg)
17364 "Increase the date in the time stamp by one day.
17365 With prefix ARG, change that many days."
17366 (interactive "p")
17367 (if (and (not (org-at-timestamp-p t))
17368 (org-at-heading-p))
17369 (org-todo 'up)
17370 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17372 (defun org-timestamp-down-day (&optional arg)
17373 "Decrease the date in the time stamp by one day.
17374 With prefix ARG, change that many days."
17375 (interactive "p")
17376 (if (and (not (org-at-timestamp-p t))
17377 (org-at-heading-p))
17378 (org-todo 'down)
17379 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17381 (defun org-at-timestamp-p (&optional inactive-ok)
17382 "Determine if the cursor is in or at a timestamp."
17383 (interactive)
17384 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17385 (pos (point))
17386 (ans (or (looking-at tsr)
17387 (save-excursion
17388 (skip-chars-backward "^[<\n\r\t")
17389 (if (> (point) (point-min)) (backward-char 1))
17390 (and (looking-at tsr)
17391 (> (- (match-end 0) pos) -1))))))
17392 (and ans
17393 (boundp 'org-ts-what)
17394 (setq org-ts-what
17395 (cond
17396 ((= pos (match-beginning 0)) 'bracket)
17397 ;; Point is considered to be "on the bracket" whether
17398 ;; it's really on it or right after it.
17399 ((= pos (1- (match-end 0))) 'bracket)
17400 ((= pos (match-end 0)) 'after)
17401 ((org-pos-in-match-range pos 2) 'year)
17402 ((org-pos-in-match-range pos 3) 'month)
17403 ((org-pos-in-match-range pos 7) 'hour)
17404 ((org-pos-in-match-range pos 8) 'minute)
17405 ((or (org-pos-in-match-range pos 4)
17406 (org-pos-in-match-range pos 5)) 'day)
17407 ((and (> pos (or (match-end 8) (match-end 5)))
17408 (< pos (match-end 0)))
17409 (- pos (or (match-end 8) (match-end 5))))
17410 (t 'day))))
17411 ans))
17413 (defun org-toggle-timestamp-type ()
17414 "Toggle the type (<active> or [inactive]) of a time stamp."
17415 (interactive)
17416 (when (org-at-timestamp-p t)
17417 (let ((beg (match-beginning 0)) (end (match-end 0))
17418 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17419 (save-excursion
17420 (goto-char beg)
17421 (while (re-search-forward "[][<>]" end t)
17422 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17423 t t)))
17424 (message "Timestamp is now %sactive"
17425 (if (equal (char-after beg) ?<) "" "in")))))
17427 (defun org-at-clock-log-p nil
17428 "Is the cursor on the clock log line?"
17429 (save-excursion
17430 (move-beginning-of-line 1)
17431 (looking-at "^[ \t]*CLOCK:")))
17433 (defvar org-clock-history) ; defined in org-clock.el
17434 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17435 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17436 "Change the date in the time stamp at point.
17437 The date will be changed by N times WHAT. WHAT can be `day', `month',
17438 `year', `minute', `second'. If WHAT is not given, the cursor position
17439 in the timestamp determines what will be changed.
17440 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17441 (let ((origin (point)) origin-cat
17442 with-hm inactive
17443 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17444 org-ts-what
17445 extra rem
17446 ts time time0 fixnext clrgx)
17447 (if (not (org-at-timestamp-p t))
17448 (user-error "Not at a timestamp"))
17449 (if (and (not what) (eq org-ts-what 'bracket))
17450 (org-toggle-timestamp-type)
17451 ;; Point isn't on brackets. Remember the part of the time-stamp
17452 ;; the point was in. Indeed, size of time-stamps may change,
17453 ;; but point must be kept in the same category nonetheless.
17454 (setq origin-cat org-ts-what)
17455 (if (and (not what) (not (eq org-ts-what 'day))
17456 org-display-custom-times
17457 (get-text-property (point) 'display)
17458 (not (get-text-property (1- (point)) 'display)))
17459 (setq org-ts-what 'day))
17460 (setq org-ts-what (or what org-ts-what)
17461 inactive (= (char-after (match-beginning 0)) ?\[)
17462 ts (match-string 0))
17463 (replace-match "")
17464 (when (string-match
17465 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17467 (setq extra (match-string 1 ts))
17468 (if suppress-tmp-delay
17469 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17470 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17471 (setq with-hm t))
17472 (setq time0 (org-parse-time-string ts))
17473 (when (and updown
17474 (eq org-ts-what 'minute)
17475 (not current-prefix-arg))
17476 ;; This looks like s-up and s-down. Change by one rounding step.
17477 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17478 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17479 (setcar (cdr time0) (+ (nth 1 time0)
17480 (if (> n 0) (- rem) (- dm rem))))))
17481 (setq time
17482 (encode-time (or (car time0) 0)
17483 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17484 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17485 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17486 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17487 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17488 (nthcdr 6 time0)))
17489 (when (and (member org-ts-what '(hour minute))
17490 extra
17491 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17492 (setq extra (org-modify-ts-extra
17493 extra
17494 (if (eq org-ts-what 'hour) 2 5)
17495 n dm)))
17496 (when (integerp org-ts-what)
17497 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17498 (if (eq what 'calendar)
17499 (let ((cal-date (org-get-date-from-calendar)))
17500 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17501 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17502 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17503 (setcar time0 (or (car time0) 0))
17504 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17505 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17506 (setq time (apply 'encode-time time0))))
17507 ;; Insert the new time-stamp, and ensure point stays in the same
17508 ;; category as before (i.e. not after the last position in that
17509 ;; category).
17510 (let ((pos (point)))
17511 ;; Stay before inserted string. `save-excursion' is of no use.
17512 (setq org-last-changed-timestamp
17513 (org-insert-time-stamp time with-hm inactive nil nil extra))
17514 (goto-char pos))
17515 (save-match-data
17516 (looking-at org-ts-regexp3)
17517 (goto-char (cond
17518 ;; `day' category ends before `hour' if any, or at
17519 ;; the end of the day name.
17520 ((eq origin-cat 'day)
17521 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17522 ((eq origin-cat 'hour) (min (match-end 7) origin))
17523 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17524 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17525 ;; `year' and `month' have both fixed size: point
17526 ;; couldn't have moved into another part.
17527 (t origin))))
17528 ;; Update clock if on a CLOCK line.
17529 (org-clock-update-time-maybe)
17530 ;; Maybe adjust the closest clock in `org-clock-history'
17531 (when org-clock-adjust-closest
17532 (if (not (and (org-at-clock-log-p)
17533 (< 1 (length (delq nil (mapcar 'marker-position
17534 org-clock-history))))))
17535 (message "No clock to adjust")
17536 (cond ((save-excursion ; fix previous clock?
17537 (re-search-backward org-ts-regexp0 nil t)
17538 (org-looking-back (concat org-clock-string " \\[")))
17539 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17540 ((save-excursion ; fix next clock?
17541 (re-search-backward org-ts-regexp0 nil t)
17542 (looking-at (concat org-ts-regexp0 "\\] =>")))
17543 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17544 (save-window-excursion
17545 ;; Find closest clock to point, adjust the previous/next one in history
17546 (let* ((p (save-excursion (org-back-to-heading t)))
17547 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17548 (clfixnth
17549 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17550 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17551 (if (not clfixpos)
17552 (message "No clock to adjust")
17553 (save-excursion
17554 (org-goto-marker-or-bmk clfixpos)
17555 (org-show-subtree)
17556 (when (re-search-forward clrgx nil t)
17557 (goto-char (match-beginning 1))
17558 (let (org-clock-adjust-closest)
17559 (org-timestamp-change n org-ts-what updown))
17560 (message "Clock adjusted in %s for heading: %s"
17561 (file-name-nondirectory (buffer-file-name))
17562 (org-get-heading t t)))))))))
17563 ;; Try to recenter the calendar window, if any.
17564 (if (and org-calendar-follow-timestamp-change
17565 (get-buffer-window "*Calendar*" t)
17566 (memq org-ts-what '(day month year)))
17567 (org-recenter-calendar (time-to-days time))))))
17569 (defun org-modify-ts-extra (s pos n dm)
17570 "Change the different parts of the lead-time and repeat fields in timestamp."
17571 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17572 ng h m new rem)
17573 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17574 (cond
17575 ((or (org-pos-in-match-range pos 2)
17576 (org-pos-in-match-range pos 3))
17577 (setq m (string-to-number (match-string 3 s))
17578 h (string-to-number (match-string 2 s)))
17579 (if (org-pos-in-match-range pos 2)
17580 (setq h (+ h n))
17581 (setq n (* dm (org-no-warnings (signum n))))
17582 (when (not (= 0 (setq rem (% m dm))))
17583 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17584 (setq m (+ m n)))
17585 (if (< m 0) (setq m (+ m 60) h (1- h)))
17586 (if (> m 59) (setq m (- m 60) h (1+ h)))
17587 (setq h (min 24 (max 0 h)))
17588 (setq ng 1 new (format "-%02d:%02d" h m)))
17589 ((org-pos-in-match-range pos 6)
17590 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17591 ((org-pos-in-match-range pos 5)
17592 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17594 ((org-pos-in-match-range pos 9)
17595 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17596 ((org-pos-in-match-range pos 8)
17597 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17599 (when ng
17600 (setq s (concat
17601 (substring s 0 (match-beginning ng))
17603 (substring s (match-end ng))))))
17606 (defun org-recenter-calendar (date)
17607 "If the calendar is visible, recenter it to DATE."
17608 (let ((cwin (get-buffer-window "*Calendar*" t)))
17609 (when cwin
17610 (let ((calendar-move-hook nil))
17611 (with-selected-window cwin
17612 (calendar-goto-date (if (listp date) date
17613 (calendar-gregorian-from-absolute date))))))))
17615 (defun org-goto-calendar (&optional arg)
17616 "Go to the Emacs calendar at the current date.
17617 If there is a time stamp in the current line, go to that date.
17618 A prefix ARG can be used to force the current date."
17619 (interactive "P")
17620 (let ((tsr org-ts-regexp) diff
17621 (calendar-move-hook nil)
17622 (calendar-view-holidays-initially-flag nil)
17623 (calendar-view-diary-initially-flag nil))
17624 (if (or (org-at-timestamp-p)
17625 (save-excursion
17626 (beginning-of-line 1)
17627 (looking-at (concat ".*" tsr))))
17628 (let ((d1 (time-to-days (current-time)))
17629 (d2 (time-to-days
17630 (org-time-string-to-time (match-string 1)))))
17631 (setq diff (- d2 d1))))
17632 (calendar)
17633 (calendar-goto-today)
17634 (if (and diff (not arg)) (calendar-forward-day diff))))
17636 (defun org-get-date-from-calendar ()
17637 "Return a list (month day year) of date at point in calendar."
17638 (with-current-buffer "*Calendar*"
17639 (save-match-data
17640 (calendar-cursor-to-date))))
17642 (defun org-date-from-calendar ()
17643 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17644 If there is already a time stamp at the cursor position, update it."
17645 (interactive)
17646 (if (org-at-timestamp-p t)
17647 (org-timestamp-change 0 'calendar)
17648 (let ((cal-date (org-get-date-from-calendar)))
17649 (org-insert-time-stamp
17650 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17652 (defcustom org-effort-durations
17653 `(("h" . 60)
17654 ("d" . ,(* 60 8))
17655 ("w" . ,(* 60 8 5))
17656 ("m" . ,(* 60 8 5 4))
17657 ("y" . ,(* 60 8 5 40)))
17658 "Conversion factor to minutes for an effort modifier.
17660 Each entry has the form (MODIFIER . MINUTES).
17662 In an effort string, a number followed by MODIFIER is multiplied
17663 by the specified number of MINUTES to obtain an effort in
17664 minutes.
17666 For example, if the value of this variable is ((\"hours\" . 60)), then an
17667 effort string \"2hours\" is equivalent to 120 minutes."
17668 :group 'org-agenda
17669 :version "24.1"
17670 :type '(alist :key-type (string :tag "Modifier")
17671 :value-type (number :tag "Minutes")))
17673 (defun org-minutes-to-clocksum-string (m)
17674 "Format number of minutes as a clocksum string.
17675 The format is determined by `org-time-clocksum-format',
17676 `org-time-clocksum-use-fractional' and
17677 `org-time-clocksum-fractional-format' and
17678 `org-time-clocksum-use-effort-durations'."
17679 (let ((clocksum "")
17680 (m (round m)) ; Don't allow fractions of minutes
17681 h d w mo y fmt n)
17682 (setq h (if org-time-clocksum-use-effort-durations
17683 (cdr (assoc "h" org-effort-durations)) 60)
17684 d (if org-time-clocksum-use-effort-durations
17685 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17686 w (if org-time-clocksum-use-effort-durations
17687 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17688 mo (if org-time-clocksum-use-effort-durations
17689 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17690 y (if org-time-clocksum-use-effort-durations
17691 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17692 ;; fractional format
17693 (if org-time-clocksum-use-fractional
17694 (cond
17695 ;; single format string
17696 ((stringp org-time-clocksum-fractional-format)
17697 (format org-time-clocksum-fractional-format (/ m (float h))))
17698 ;; choice of fractional formats for different time units
17699 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17700 (> (/ (truncate m) (* y d h)) 0))
17701 (format fmt (/ m (* y d (float h)))))
17702 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17703 (> (/ (truncate m) (* mo d h)) 0))
17704 (format fmt (/ m (* mo d (float h)))))
17705 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17706 (> (/ (truncate m) (* w d h)) 0))
17707 (format fmt (/ m (* w d (float h)))))
17708 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17709 (> (/ (truncate m) (* d h)) 0))
17710 (format fmt (/ m (* d (float h)))))
17711 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17712 (> (/ (truncate m) h) 0))
17713 (format fmt (/ m (float h))))
17714 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17715 (format fmt m))
17716 ;; fall back to smallest time unit with a format
17717 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17718 (format fmt (/ m (float h))))
17719 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17720 (format fmt (/ m (* d (float h)))))
17721 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17722 (format fmt (/ m (* w d (float h)))))
17723 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17724 (format fmt (/ m (* mo d (float h)))))
17725 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17726 (format fmt (/ m (* y d (float h))))))
17727 ;; standard (non-fractional) format, with single format string
17728 (if (stringp org-time-clocksum-format)
17729 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17730 ;; separate formats components
17731 (and (setq fmt (plist-get org-time-clocksum-format :years))
17732 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17733 (plist-get org-time-clocksum-format :require-years))
17734 (setq clocksum (concat clocksum (format fmt n))
17735 m (- m (* n y d h))))
17736 (and (setq fmt (plist-get org-time-clocksum-format :months))
17737 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17738 (plist-get org-time-clocksum-format :require-months))
17739 (setq clocksum (concat clocksum (format fmt n))
17740 m (- m (* n mo d h))))
17741 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17742 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17743 (plist-get org-time-clocksum-format :require-weeks))
17744 (setq clocksum (concat clocksum (format fmt n))
17745 m (- m (* n w d h))))
17746 (and (setq fmt (plist-get org-time-clocksum-format :days))
17747 (or (> (setq n (/ (truncate m) (* d h))) 0)
17748 (plist-get org-time-clocksum-format :require-days))
17749 (setq clocksum (concat clocksum (format fmt n))
17750 m (- m (* n d h))))
17751 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17752 (or (> (setq n (/ (truncate m) h)) 0)
17753 (plist-get org-time-clocksum-format :require-hours))
17754 (setq clocksum (concat clocksum (format fmt n))
17755 m (- m (* n h))))
17756 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17757 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17758 (setq clocksum (concat clocksum (format fmt m))))
17759 ;; return formatted time duration
17760 clocksum))))
17762 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17763 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17764 "Org mode version 8.0")
17766 (defun org-hours-to-clocksum-string (n)
17767 (org-minutes-to-clocksum-string (* n 60)))
17769 (defun org-hh:mm-string-to-minutes (s)
17770 "Convert a string H:MM to a number of minutes.
17771 If the string is just a number, interpret it as minutes.
17772 In fact, the first hh:mm or number in the string will be taken,
17773 there can be extra stuff in the string.
17774 If no number is found, the return value is 0."
17775 (cond
17776 ((integerp s) s)
17777 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17778 (+ (* (string-to-number (match-string 1 s)) 60)
17779 (string-to-number (match-string 2 s))))
17780 ((string-match "\\([0-9]+\\)" s)
17781 (string-to-number (match-string 1 s)))
17782 (t 0)))
17784 (defcustom org-image-actual-width t
17785 "Should we use the actual width of images when inlining them?
17787 When set to `t', always use the image width.
17789 When set to a number, use imagemagick (when available) to set
17790 the image's width to this value.
17792 When set to a number in a list, try to get the width from any
17793 #+ATTR.* keyword if it matches a width specification like
17795 #+ATTR_HTML: :width 300px
17797 and fall back on that number if none is found.
17799 When set to nil, try to get the width from an #+ATTR.* keyword
17800 and fall back on the original width if none is found.
17802 This requires Emacs >= 24.1, build with imagemagick support."
17803 :group 'org-appearance
17804 :version "24.4"
17805 :package-version '(Org . "8.0")
17806 :type '(choice
17807 (const :tag "Use the image width" t)
17808 (integer :tag "Use a number of pixels")
17809 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17810 (const :tag "Use #+ATTR* or don't resize" nil)))
17812 (defcustom org-agenda-inhibit-startup nil
17813 "Inhibit startup when preparing agenda buffers.
17814 When this variable is `t' (the default), the initialization of
17815 the Org agenda buffers is inhibited: e.g. the visibility state
17816 is not set, the tables are not re-aligned, etc."
17817 :type 'boolean
17818 :version "24.3"
17819 :group 'org-agenda)
17821 (defcustom org-agenda-ignore-drawer-properties nil
17822 "Avoid updating text properties when building the agenda.
17823 Properties are used to prepare buffers for effort estimates, appointments,
17824 and subtree-local categories.
17825 If you don't use these in the agenda, you can add them to this list and
17826 agenda building will be a bit faster.
17827 The value is a list, with zero or more of the symbols `effort', `appt',
17828 or `category'."
17829 :type '(set :greedy t
17830 (const effort)
17831 (const appt)
17832 (const category))
17833 :version "24.3"
17834 :group 'org-agenda)
17836 (defun org-duration-string-to-minutes (s &optional output-to-string)
17837 "Convert a duration string S to minutes.
17839 A bare number is interpreted as minutes, modifiers can be set by
17840 customizing `org-effort-durations' (which see).
17842 Entries containing a colon are interpreted as H:MM by
17843 `org-hh:mm-string-to-minutes'."
17844 (let ((result 0)
17845 (re (concat "\\([0-9.]+\\) *\\("
17846 (regexp-opt (mapcar 'car org-effort-durations))
17847 "\\)")))
17848 (while (string-match re s)
17849 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17850 (string-to-number (match-string 1 s))))
17851 (setq s (replace-match "" nil t s)))
17852 (setq result (floor result))
17853 (incf result (org-hh:mm-string-to-minutes s))
17854 (if output-to-string (number-to-string result) result)))
17856 ;;;; Files
17858 (defun org-save-all-org-buffers ()
17859 "Save all Org-mode buffers without user confirmation."
17860 (interactive)
17861 (message "Saving all Org-mode buffers...")
17862 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17863 (when (featurep 'org-id) (org-id-locations-save))
17864 (message "Saving all Org-mode buffers... done"))
17866 (defun org-revert-all-org-buffers ()
17867 "Revert all Org-mode buffers.
17868 Prompt for confirmation when there are unsaved changes.
17869 Be sure you know what you are doing before letting this function
17870 overwrite your changes.
17872 This function is useful in a setup where one tracks org files
17873 with a version control system, to revert on one machine after pulling
17874 changes from another. I believe the procedure must be like this:
17876 1. M-x org-save-all-org-buffers
17877 2. Pull changes from the other machine, resolve conflicts
17878 3. M-x org-revert-all-org-buffers"
17879 (interactive)
17880 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17881 (user-error "Abort"))
17882 (save-excursion
17883 (save-window-excursion
17884 (mapc
17885 (lambda (b)
17886 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17887 (with-current-buffer b buffer-file-name))
17888 (org-pop-to-buffer-same-window b)
17889 (revert-buffer t 'no-confirm)))
17890 (buffer-list))
17891 (when (and (featurep 'org-id) org-id-track-globally)
17892 (org-id-locations-load)))))
17894 ;;;; Agenda files
17896 ;;;###autoload
17897 (defun org-switchb (&optional arg)
17898 "Switch between Org buffers.
17899 With one prefix argument, restrict available buffers to files.
17900 With two prefix arguments, restrict available buffers to agenda files.
17902 Defaults to `iswitchb' for buffer name completion.
17903 Set `org-completion-use-ido' to make it use ido instead."
17904 (interactive "P")
17905 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17906 ((equal arg '(16)) (org-buffer-list 'agenda))
17907 (t (org-buffer-list))))
17908 (org-completion-use-iswitchb org-completion-use-iswitchb)
17909 (org-completion-use-ido org-completion-use-ido))
17910 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17911 (setq org-completion-use-iswitchb t))
17912 (org-pop-to-buffer-same-window
17913 (org-icompleting-read "Org buffer: "
17914 (mapcar 'list (mapcar 'buffer-name blist))
17915 nil t))))
17917 ;;; Define some older names previously used for this functionality
17918 ;;;###autoload
17919 (defalias 'org-ido-switchb 'org-switchb)
17920 ;;;###autoload
17921 (defalias 'org-iswitchb 'org-switchb)
17923 (defun org-buffer-list (&optional predicate exclude-tmp)
17924 "Return a list of Org buffers.
17925 PREDICATE can be `export', `files' or `agenda'.
17927 export restrict the list to Export buffers.
17928 files restrict the list to buffers visiting Org files.
17929 agenda restrict the list to buffers visiting agenda files.
17931 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17932 (let* ((bfn nil)
17933 (agenda-files (and (eq predicate 'agenda)
17934 (mapcar 'file-truename (org-agenda-files t))))
17935 (filter
17936 (cond
17937 ((eq predicate 'files)
17938 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17939 ((eq predicate 'export)
17940 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17941 ((eq predicate 'agenda)
17942 (lambda (b)
17943 (with-current-buffer b
17944 (and (derived-mode-p 'org-mode)
17945 (setq bfn (buffer-file-name b))
17946 (member (file-truename bfn) agenda-files)))))
17947 (t (lambda (b) (with-current-buffer b
17948 (or (derived-mode-p 'org-mode)
17949 (string-match "\*Org .*Export"
17950 (buffer-name b)))))))))
17951 (delq nil
17952 (mapcar
17953 (lambda(b)
17954 (if (and (funcall filter b)
17955 (or (not exclude-tmp)
17956 (not (string-match "tmp" (buffer-name b)))))
17958 nil))
17959 (buffer-list)))))
17961 (defun org-agenda-files (&optional unrestricted archives)
17962 "Get the list of agenda files.
17963 Optional UNRESTRICTED means return the full list even if a restriction
17964 is currently in place.
17965 When ARCHIVES is t, include all archive files that are really being
17966 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17967 `org-agenda-archives-mode' is t."
17968 (let ((files
17969 (cond
17970 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17971 ((stringp org-agenda-files) (org-read-agenda-file-list))
17972 ((listp org-agenda-files) org-agenda-files)
17973 (t (error "Invalid value of `org-agenda-files'")))))
17974 (setq files (apply 'append
17975 (mapcar (lambda (f)
17976 (if (file-directory-p f)
17977 (directory-files
17978 f t org-agenda-file-regexp)
17979 (list f)))
17980 files)))
17981 (when org-agenda-skip-unavailable-files
17982 (setq files (delq nil
17983 (mapcar (function
17984 (lambda (file)
17985 (and (file-readable-p file) file)))
17986 files))))
17987 (when (or (eq archives t)
17988 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17989 (setq files (org-add-archive-files files)))
17990 files))
17992 (defun org-agenda-file-p (&optional file)
17993 "Return non-nil, if FILE is an agenda file.
17994 If FILE is omitted, use the file associated with the current
17995 buffer."
17996 (member (or file (buffer-file-name))
17997 (org-agenda-files t)))
17999 (defun org-edit-agenda-file-list ()
18000 "Edit the list of agenda files.
18001 Depending on setup, this either uses customize to edit the variable
18002 `org-agenda-files', or it visits the file that is holding the list. In the
18003 latter case, the buffer is set up in a way that saving it automatically kills
18004 the buffer and restores the previous window configuration."
18005 (interactive)
18006 (if (stringp org-agenda-files)
18007 (let ((cw (current-window-configuration)))
18008 (find-file org-agenda-files)
18009 (org-set-local 'org-window-configuration cw)
18010 (org-add-hook 'after-save-hook
18011 (lambda ()
18012 (set-window-configuration
18013 (prog1 org-window-configuration
18014 (kill-buffer (current-buffer))))
18015 (org-install-agenda-files-menu)
18016 (message "New agenda file list installed"))
18017 nil 'local)
18018 (message "%s" (substitute-command-keys
18019 "Edit list and finish with \\[save-buffer]")))
18020 (customize-variable 'org-agenda-files)))
18022 (defun org-store-new-agenda-file-list (list)
18023 "Set new value for the agenda file list and save it correctly."
18024 (if (stringp org-agenda-files)
18025 (let ((fe (org-read-agenda-file-list t)) b u)
18026 (while (setq b (find-buffer-visiting org-agenda-files))
18027 (kill-buffer b))
18028 (with-temp-file org-agenda-files
18029 (insert
18030 (mapconcat
18031 (lambda (f) ;; Keep un-expanded entries.
18032 (if (setq u (assoc f fe))
18033 (cdr u)
18035 list "\n")
18036 "\n")))
18037 (let ((org-mode-hook nil) (org-inhibit-startup t)
18038 (org-insert-mode-line-in-empty-file nil))
18039 (setq org-agenda-files list)
18040 (customize-save-variable 'org-agenda-files org-agenda-files))))
18042 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18043 "Read the list of agenda files from a file.
18044 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18045 filenames, used by `org-store-new-agenda-file-list' to write back
18046 un-expanded file names."
18047 (when (file-directory-p org-agenda-files)
18048 (error "`org-agenda-files' cannot be a single directory"))
18049 (when (stringp org-agenda-files)
18050 (with-temp-buffer
18051 (insert-file-contents org-agenda-files)
18052 (mapcar
18053 (lambda (f)
18054 (let ((e (expand-file-name (substitute-in-file-name f)
18055 org-directory)))
18056 (if pair-with-expansion
18057 (cons e f)
18058 e)))
18059 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18061 ;;;###autoload
18062 (defun org-cycle-agenda-files ()
18063 "Cycle through the files in `org-agenda-files'.
18064 If the current buffer visits an agenda file, find the next one in the list.
18065 If the current buffer does not, find the first agenda file."
18066 (interactive)
18067 (let* ((fs (org-agenda-files t))
18068 (files (append fs (list (car fs))))
18069 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18070 file)
18071 (unless files (user-error "No agenda files"))
18072 (catch 'exit
18073 (while (setq file (pop files))
18074 (if (equal (file-truename file) tcf)
18075 (when (car files)
18076 (find-file (car files))
18077 (throw 'exit t))))
18078 (find-file (car fs)))
18079 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18081 (defun org-agenda-file-to-front (&optional to-end)
18082 "Move/add the current file to the top of the agenda file list.
18083 If the file is not present in the list, it is added to the front. If it is
18084 present, it is moved there. With optional argument TO-END, add/move to the
18085 end of the list."
18086 (interactive "P")
18087 (let ((org-agenda-skip-unavailable-files nil)
18088 (file-alist (mapcar (lambda (x)
18089 (cons (file-truename x) x))
18090 (org-agenda-files t)))
18091 (ctf (file-truename
18092 (or buffer-file-name
18093 (user-error "Please save the current buffer to a file"))))
18094 x had)
18095 (setq x (assoc ctf file-alist) had x)
18097 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18098 (if to-end
18099 (setq file-alist (append (delq x file-alist) (list x)))
18100 (setq file-alist (cons x (delq x file-alist))))
18101 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18102 (org-install-agenda-files-menu)
18103 (message "File %s to %s of agenda file list"
18104 (if had "moved" "added") (if to-end "end" "front"))))
18106 (defun org-remove-file (&optional file)
18107 "Remove current file from the list of files in variable `org-agenda-files'.
18108 These are the files which are being checked for agenda entries.
18109 Optional argument FILE means use this file instead of the current."
18110 (interactive)
18111 (let* ((org-agenda-skip-unavailable-files nil)
18112 (file (or file buffer-file-name
18113 (user-error "Current buffer does not visit a file")))
18114 (true-file (file-truename file))
18115 (afile (abbreviate-file-name file))
18116 (files (delq nil (mapcar
18117 (lambda (x)
18118 (if (equal true-file
18119 (file-truename x))
18120 nil x))
18121 (org-agenda-files t)))))
18122 (if (not (= (length files) (length (org-agenda-files t))))
18123 (progn
18124 (org-store-new-agenda-file-list files)
18125 (org-install-agenda-files-menu)
18126 (message "Removed file: %s" afile))
18127 (message "File was not in list: %s (not removed)" afile))))
18129 (defun org-file-menu-entry (file)
18130 (vector file (list 'find-file file) t))
18132 (defun org-check-agenda-file (file)
18133 "Make sure FILE exists. If not, ask user what to do."
18134 (when (not (file-exists-p file))
18135 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18136 (abbreviate-file-name file))
18137 (let ((r (downcase (read-char-exclusive))))
18138 (cond
18139 ((equal r ?r)
18140 (org-remove-file file)
18141 (throw 'nextfile t))
18142 (t (error "Abort"))))))
18144 (defun org-get-agenda-file-buffer (file)
18145 "Get a buffer visiting FILE. If the buffer needs to be created, add
18146 it to the list of buffers which might be released later."
18147 (let ((buf (org-find-base-buffer-visiting file)))
18148 (if buf
18149 buf ; just return it
18150 ;; Make a new buffer and remember it
18151 (setq buf (find-file-noselect file))
18152 (if buf (push buf org-agenda-new-buffers))
18153 buf)))
18155 (defun org-release-buffers (blist)
18156 "Release all buffers in list, asking the user for confirmation when needed.
18157 When a buffer is unmodified, it is just killed. When modified, it is saved
18158 \(if the user agrees) and then killed."
18159 (let (buf file)
18160 (while (setq buf (pop blist))
18161 (setq file (buffer-file-name buf))
18162 (when (and (buffer-modified-p buf)
18163 file
18164 (y-or-n-p (format "Save file %s? " file)))
18165 (with-current-buffer buf (save-buffer)))
18166 (kill-buffer buf))))
18168 (defun org-agenda-prepare-buffers (files)
18169 "Create buffers for all agenda files, protect archived trees and comments."
18170 (interactive)
18171 (let ((pa '(:org-archived t))
18172 (pc '(:org-comment t))
18173 (pall '(:org-archived t :org-comment t))
18174 (inhibit-read-only t)
18175 (org-inhibit-startup org-agenda-inhibit-startup)
18176 (rea (concat ":" org-archive-tag ":"))
18177 file re pos)
18178 (setq org-tag-alist-for-agenda nil
18179 org-tag-groups-alist-for-agenda nil)
18180 (save-excursion
18181 (save-restriction
18182 (while (setq file (pop files))
18183 (catch 'nextfile
18184 (if (bufferp file)
18185 (set-buffer file)
18186 (org-check-agenda-file file)
18187 (set-buffer (org-get-agenda-file-buffer file)))
18188 (widen)
18189 (org-set-regexps-and-options-for-tags)
18190 (setq pos (point))
18191 (goto-char (point-min))
18192 (let ((case-fold-search t))
18193 (when (search-forward "#+setupfile" nil t)
18194 ;; Don't set all regexps and options systematically as
18195 ;; this is only run for setting agenda tags from setup
18196 ;; file
18197 (org-set-regexps-and-options)))
18198 (or (memq 'category org-agenda-ignore-drawer-properties)
18199 (org-refresh-category-properties))
18200 (or (memq 'effort org-agenda-ignore-drawer-properties)
18201 (org-refresh-properties org-effort-property 'org-effort))
18202 (or (memq 'appt org-agenda-ignore-drawer-properties)
18203 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18204 (setq org-todo-keywords-for-agenda
18205 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18206 (setq org-done-keywords-for-agenda
18207 (append org-done-keywords-for-agenda org-done-keywords))
18208 (setq org-todo-keyword-alist-for-agenda
18209 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18210 (setq org-tag-alist-for-agenda
18211 (org-uniquify
18212 (append org-tag-alist-for-agenda
18213 org-tag-alist
18214 org-tag-persistent-alist)))
18215 (if org-group-tags
18216 (setq org-tag-groups-alist-for-agenda
18217 (org-uniquify-alist
18218 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18219 (org-with-silent-modifications
18220 (save-excursion
18221 (remove-text-properties (point-min) (point-max) pall)
18222 (when org-agenda-skip-archived-trees
18223 (goto-char (point-min))
18224 (while (re-search-forward rea nil t)
18225 (if (org-at-heading-p t)
18226 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18227 (goto-char (point-min))
18228 (setq re (format org-heading-keyword-regexp-format
18229 org-comment-string))
18230 (while (re-search-forward re nil t)
18231 (add-text-properties
18232 (match-beginning 0) (org-end-of-subtree t) pc))))
18233 (goto-char pos)))))
18234 (setq org-todo-keywords-for-agenda
18235 (org-uniquify org-todo-keywords-for-agenda))
18236 (setq org-todo-keyword-alist-for-agenda
18237 (org-uniquify org-todo-keyword-alist-for-agenda))))
18240 ;;;; CDLaTeX minor mode
18242 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18243 "Keymap for the minor `org-cdlatex-mode'.")
18245 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18246 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18247 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18248 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18249 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18251 (defvar org-cdlatex-texmathp-advice-is-done nil
18252 "Flag remembering if we have applied the advice to texmathp already.")
18254 (define-minor-mode org-cdlatex-mode
18255 "Toggle the minor `org-cdlatex-mode'.
18256 This mode supports entering LaTeX environment and math in LaTeX fragments
18257 in Org-mode.
18258 \\{org-cdlatex-mode-map}"
18259 nil " OCDL" nil
18260 (when org-cdlatex-mode
18261 (require 'cdlatex)
18262 (run-hooks 'cdlatex-mode-hook)
18263 (cdlatex-compute-tables))
18264 (unless org-cdlatex-texmathp-advice-is-done
18265 (setq org-cdlatex-texmathp-advice-is-done t)
18266 (defadvice texmathp (around org-math-always-on activate)
18267 "Always return t in org-mode buffers.
18268 This is because we want to insert math symbols without dollars even outside
18269 the LaTeX math segments. If Orgmode thinks that point is actually inside
18270 an embedded LaTeX fragment, let texmathp do its job.
18271 \\[org-cdlatex-mode-map]"
18272 (interactive)
18273 (let (p)
18274 (cond
18275 ((not (derived-mode-p 'org-mode)) ad-do-it)
18276 ((eq this-command 'cdlatex-math-symbol)
18277 (setq ad-return-value t
18278 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18280 (let ((p (org-inside-LaTeX-fragment-p)))
18281 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18282 (setq ad-return-value t
18283 texmathp-why '("Org-mode embedded math" . 0))
18284 (if p ad-do-it)))))))))
18286 (defun turn-on-org-cdlatex ()
18287 "Unconditionally turn on `org-cdlatex-mode'."
18288 (org-cdlatex-mode 1))
18290 (defun org-try-cdlatex-tab ()
18291 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18292 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18293 - inside a LaTeX fragment, or
18294 - after the first word in a line, where an abbreviation expansion could
18295 insert a LaTeX environment."
18296 (when org-cdlatex-mode
18297 (cond
18298 ;; Before any word on the line: No expansion possible.
18299 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18300 ;; Just after first word on the line: Expand it. Make sure it
18301 ;; cannot happen on headlines, though.
18302 ((save-excursion
18303 (skip-chars-backward "a-zA-Z0-9*")
18304 (skip-chars-backward " \t")
18305 (and (bolp) (not (org-at-heading-p))))
18306 (cdlatex-tab) t)
18307 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18309 (defun org-cdlatex-underscore-caret (&optional arg)
18310 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18311 Revert to the normal definition outside of these fragments."
18312 (interactive "P")
18313 (if (org-inside-LaTeX-fragment-p)
18314 (call-interactively 'cdlatex-sub-superscript)
18315 (let (org-cdlatex-mode)
18316 (call-interactively (key-binding (vector last-input-event))))))
18318 (defun org-cdlatex-math-modify (&optional arg)
18319 "Execute `cdlatex-math-modify' in LaTeX fragments.
18320 Revert to the normal definition outside of these fragments."
18321 (interactive "P")
18322 (if (org-inside-LaTeX-fragment-p)
18323 (call-interactively 'cdlatex-math-modify)
18324 (let (org-cdlatex-mode)
18325 (call-interactively (key-binding (vector last-input-event))))))
18329 ;;;; LaTeX fragments
18331 (defun org-inside-LaTeX-fragment-p ()
18332 "Test if point is inside a LaTeX fragment.
18333 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18334 sequence appearing also before point.
18335 Even though the matchers for math are configurable, this function assumes
18336 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18337 delimiters are skipped when they have been removed by customization.
18338 The return value is nil, or a cons cell with the delimiter and the
18339 position of this delimiter.
18341 This function does a reasonably good job, but can locally be fooled by
18342 for example currency specifications. For example it will assume being in
18343 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18344 fragments that are properly closed, but during editing, we have to live
18345 with the uncertainty caused by missing closing delimiters. This function
18346 looks only before point, not after."
18347 (catch 'exit
18348 (let ((pos (point))
18349 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18350 (lim (progn
18351 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18352 (point)))
18353 dd-on str (start 0) m re)
18354 (goto-char pos)
18355 (when dodollar
18356 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18357 re (nth 1 (assoc "$" org-latex-regexps)))
18358 (while (string-match re str start)
18359 (cond
18360 ((= (match-end 0) (length str))
18361 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18362 ((= (match-end 0) (- (length str) 5))
18363 (throw 'exit nil))
18364 (t (setq start (match-end 0))))))
18365 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18366 (goto-char pos)
18367 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18368 (and (match-beginning 2) (throw 'exit nil))
18369 ;; count $$
18370 (while (re-search-backward "\\$\\$" lim t)
18371 (setq dd-on (not dd-on)))
18372 (goto-char pos)
18373 (if dd-on (cons "$$" m))))))
18375 (defun org-inside-latex-macro-p ()
18376 "Is point inside a LaTeX macro or its arguments?"
18377 (save-match-data
18378 (org-in-regexp
18379 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18381 (defvar org-latex-fragment-image-overlays nil
18382 "List of overlays carrying the images of latex fragments.")
18383 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18385 (defun org-remove-latex-fragment-image-overlays ()
18386 "Remove all overlays with LaTeX fragment images in current buffer."
18387 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18388 (setq org-latex-fragment-image-overlays nil))
18390 (defun org-preview-latex-fragment (&optional subtree)
18391 "Preview the LaTeX fragment at point, or all locally or globally.
18392 If the cursor is in a LaTeX fragment, create the image and overlay
18393 it over the source code. If there is no fragment at point, display
18394 all fragments in the current text, from one headline to the next. With
18395 prefix SUBTREE, display all fragments in the current subtree. With a
18396 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18397 the cursor is before the first headline,
18398 display all fragments in the buffer.
18399 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18400 (interactive "P")
18401 (unless buffer-file-name
18402 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18403 (when (display-graphic-p)
18404 (org-remove-latex-fragment-image-overlays)
18405 (save-excursion
18406 (save-restriction
18407 (let (beg end at msg)
18408 (cond
18409 ((or (equal subtree '(16))
18410 (not (save-excursion
18411 (re-search-backward org-outline-regexp-bol nil t))))
18412 (setq beg (point-min) end (point-max)
18413 msg "Creating images for buffer...%s"))
18414 ((equal subtree '(4))
18415 (org-back-to-heading)
18416 (setq beg (point) end (org-end-of-subtree t)
18417 msg "Creating images for subtree...%s"))
18419 (if (setq at (org-inside-LaTeX-fragment-p))
18420 (goto-char (max (point-min) (- (cdr at) 2)))
18421 (org-back-to-heading))
18422 (setq beg (point) end (progn (outline-next-heading) (point))
18423 msg (if at "Creating image...%s"
18424 "Creating images for entry...%s"))))
18425 (message msg "")
18426 (narrow-to-region beg end)
18427 (goto-char beg)
18428 (org-format-latex
18429 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18430 (file-name-nondirectory
18431 buffer-file-name)))
18432 default-directory 'overlays msg at 'forbuffer
18433 org-latex-create-formula-image-program)
18434 (message msg "done. Use `C-c C-c' to remove images."))))))
18436 (defun org-format-latex (prefix &optional dir overlays msg at
18437 forbuffer processing-type)
18438 "Replace LaTeX fragments with links to an image, and produce images.
18439 Some of the options can be changed using the variable
18440 `org-format-latex-options'."
18441 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18442 (let* ((prefixnodir (file-name-nondirectory prefix))
18443 (absprefix (expand-file-name prefix dir))
18444 (todir (file-name-directory absprefix))
18445 (opt org-format-latex-options)
18446 (optnew org-format-latex-options)
18447 (matchers (plist-get opt :matchers))
18448 (re-list org-latex-regexps)
18449 (cnt 0) txt hash link beg end re e checkdir
18450 string
18451 m n block-type block linkfile movefile ov)
18452 ;; Check the different regular expressions
18453 (while (setq e (pop re-list))
18454 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18455 block (if block-type "\n\n" ""))
18456 (when (member m matchers)
18457 (goto-char (point-min))
18458 (while (re-search-forward re nil t)
18459 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18460 (or (not overlays)
18461 (not (eq (get-char-property (match-beginning n)
18462 'org-overlay-type)
18463 'org-latex-overlay))))
18464 (cond
18465 ((eq processing-type 'verbatim))
18466 ((eq processing-type 'mathjax)
18467 ;; Prepare for MathJax processing.
18468 (setq string (match-string n))
18469 (when (member m '("$" "$1"))
18470 (save-excursion
18471 (delete-region (match-beginning n) (match-end n))
18472 (goto-char (match-beginning n))
18473 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18474 ((or (eq processing-type 'dvipng)
18475 (eq processing-type 'imagemagick))
18476 ;; Process to an image.
18477 (setq txt (match-string n)
18478 beg (match-beginning n) end (match-end n)
18479 cnt (1+ cnt))
18480 (let ((face (face-at-point))
18481 (fg (plist-get opt :foreground))
18482 (bg (plist-get opt :background))
18483 ;; Ensure full list is printed.
18484 print-length print-level)
18485 (when forbuffer
18486 ;; Get the colors from the face at point.
18487 (goto-char beg)
18488 (when (eq fg 'auto)
18489 (setq fg (face-attribute face :foreground nil 'default)))
18490 (when (eq bg 'auto)
18491 (setq bg (face-attribute face :background nil 'default)))
18492 (setq optnew (copy-sequence opt))
18493 (plist-put optnew :foreground fg)
18494 (plist-put optnew :background bg))
18495 (setq hash (sha1 (prin1-to-string
18496 (list org-format-latex-header
18497 org-latex-default-packages-alist
18498 org-latex-packages-alist
18499 org-format-latex-options
18500 forbuffer txt fg bg)))
18501 linkfile (format "%s_%s.png" prefix hash)
18502 movefile (format "%s_%s.png" absprefix hash)))
18503 (setq link (concat block "[[file:" linkfile "]]" block))
18504 (if msg (message msg cnt))
18505 (goto-char beg)
18506 (unless checkdir ; Ensure the directory exists.
18507 (setq checkdir t)
18508 (or (file-directory-p todir) (make-directory todir t)))
18509 (unless (file-exists-p movefile)
18510 (org-create-formula-image
18511 txt movefile optnew forbuffer processing-type))
18512 (if overlays
18513 (progn
18514 (mapc (lambda (o)
18515 (if (eq (overlay-get o 'org-overlay-type)
18516 'org-latex-overlay)
18517 (delete-overlay o)))
18518 (overlays-in beg end))
18519 (setq ov (make-overlay beg end))
18520 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18521 (if (featurep 'xemacs)
18522 (progn
18523 (overlay-put ov 'invisible t)
18524 (overlay-put
18525 ov 'end-glyph
18526 (make-glyph (vector 'png :file movefile))))
18527 (overlay-put
18528 ov 'display
18529 (list 'image :type 'png :file movefile :ascent 'center)))
18530 (push ov org-latex-fragment-image-overlays)
18531 (goto-char end))
18532 (delete-region beg end)
18533 (insert (org-add-props link
18534 (list 'org-latex-src
18535 (replace-regexp-in-string
18536 "\"" "" txt)
18537 'org-latex-src-embed-type
18538 (if block-type 'paragraph 'character))))))
18539 ((eq processing-type 'mathml)
18540 ;; Process to MathML
18541 (unless (save-match-data (org-format-latex-mathml-available-p))
18542 (user-error "LaTeX to MathML converter not configured"))
18543 (setq txt (match-string n)
18544 beg (match-beginning n) end (match-end n)
18545 cnt (1+ cnt))
18546 (if msg (message msg cnt))
18547 (goto-char beg)
18548 (delete-region beg end)
18549 (insert (org-format-latex-as-mathml
18550 txt block-type prefix dir)))
18552 (error "Unknown conversion type %s for LaTeX fragments"
18553 processing-type)))))))))
18555 (defun org-create-math-formula (latex-frag &optional mathml-file)
18556 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18557 Use `org-latex-to-mathml-convert-command'. If the conversion is
18558 sucessful, return the portion between \"<math...> </math>\"
18559 elements otherwise return nil. When MATHML-FILE is specified,
18560 write the results in to that file. When invoked as an
18561 interactive command, prompt for LATEX-FRAG, with initial value
18562 set to the current active region and echo the results for user
18563 inspection."
18564 (interactive (list (let ((frag (when (org-region-active-p)
18565 (buffer-substring-no-properties
18566 (region-beginning) (region-end)))))
18567 (read-string "LaTeX Fragment: " frag nil frag))))
18568 (unless latex-frag (error "Invalid LaTeX fragment"))
18569 (let* ((tmp-in-file (file-relative-name
18570 (make-temp-name (expand-file-name "ltxmathml-in"))))
18571 (ignore (write-region latex-frag nil tmp-in-file))
18572 (tmp-out-file (file-relative-name
18573 (make-temp-name (expand-file-name "ltxmathml-out"))))
18574 (cmd (format-spec
18575 org-latex-to-mathml-convert-command
18576 `((?j . ,(shell-quote-argument
18577 (expand-file-name org-latex-to-mathml-jar-file)))
18578 (?I . ,(shell-quote-argument tmp-in-file))
18579 (?o . ,(shell-quote-argument tmp-out-file)))))
18580 mathml shell-command-output)
18581 (when (org-called-interactively-p 'any)
18582 (unless (org-format-latex-mathml-available-p)
18583 (user-error "LaTeX to MathML converter not configured")))
18584 (message "Running %s" cmd)
18585 (setq shell-command-output (shell-command-to-string cmd))
18586 (setq mathml
18587 (when (file-readable-p tmp-out-file)
18588 (with-current-buffer (find-file-noselect tmp-out-file t)
18589 (goto-char (point-min))
18590 (when (re-search-forward
18591 (concat
18592 (regexp-quote
18593 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18594 "\\(.\\|\n\\)*"
18595 (regexp-quote "</math>")) nil t)
18596 (prog1 (match-string 0) (kill-buffer))))))
18597 (cond
18598 (mathml
18599 (setq mathml
18600 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18601 (when mathml-file
18602 (write-region mathml nil mathml-file))
18603 (when (org-called-interactively-p 'any)
18604 (message mathml)))
18605 ((message "LaTeX to MathML conversion failed")
18606 (message shell-command-output)))
18607 (delete-file tmp-in-file)
18608 (when (file-exists-p tmp-out-file)
18609 (delete-file tmp-out-file))
18610 mathml))
18612 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18613 prefix &optional dir)
18614 "Use `org-create-math-formula' but check local cache first."
18615 (let* ((absprefix (expand-file-name prefix dir))
18616 (print-length nil) (print-level nil)
18617 (formula-id (concat
18618 "formula-"
18619 (sha1
18620 (prin1-to-string
18621 (list latex-frag
18622 org-latex-to-mathml-convert-command)))))
18623 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18624 (formula-cache-dir (file-name-directory formula-cache)))
18626 (unless (file-directory-p formula-cache-dir)
18627 (make-directory formula-cache-dir t))
18629 (unless (file-exists-p formula-cache)
18630 (org-create-math-formula latex-frag formula-cache))
18632 (if (file-exists-p formula-cache)
18633 ;; Successful conversion. Return the link to MathML file.
18634 (org-add-props
18635 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18636 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18637 'org-latex-src-embed-type (if latex-frag-type
18638 'paragraph 'character)))
18639 ;; Failed conversion. Return the LaTeX fragment verbatim
18640 latex-frag)))
18642 (defun org-create-formula-image (string tofile options buffer &optional type)
18643 "Create an image from LaTeX source using dvipng or convert.
18644 This function calls either `org-create-formula-image-with-dvipng'
18645 or `org-create-formula-image-with-imagemagick' depending on the
18646 value of `org-latex-create-formula-image-program' or on the value
18647 of the optional TYPE variable.
18649 Note: ultimately these two function should be combined as they
18650 share a good deal of logic."
18651 (org-check-external-command
18652 "latex" "needed to convert LaTeX fragments to images")
18653 (funcall
18654 (case (or type org-latex-create-formula-image-program)
18655 ('dvipng
18656 (org-check-external-command
18657 "dvipng" "needed to convert LaTeX fragments to images")
18658 #'org-create-formula-image-with-dvipng)
18659 ('imagemagick
18660 (org-check-external-command
18661 "convert" "you need to install imagemagick")
18662 #'org-create-formula-image-with-imagemagick)
18663 (t (error
18664 "Invalid value of `org-latex-create-formula-image-program'")))
18665 string tofile options buffer))
18667 (declare-function org-export-get-backend "ox" (name))
18668 (declare-function org-export--get-global-options "ox" (&optional backend))
18669 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18670 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18671 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18672 (defun org-create-formula--latex-header ()
18673 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18674 (let ((info (org-combine-plists (org-export--get-global-options
18675 (org-export-get-backend 'latex))
18676 (org-export--get-inbuffer-options
18677 (org-export-get-backend 'latex)))))
18678 (org-latex-guess-babel-language
18679 (org-latex-guess-inputenc
18680 (org-splice-latex-header
18681 org-format-latex-header
18682 org-latex-default-packages-alist
18683 org-latex-packages-alist t
18684 (plist-get info :latex-header)))
18685 info)))
18687 ;; This function borrows from Ganesh Swami's latex2png.el
18688 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18689 "This calls dvipng."
18690 (require 'ox-latex)
18691 (let* ((tmpdir (if (featurep 'xemacs)
18692 (temp-directory)
18693 temporary-file-directory))
18694 (texfilebase (make-temp-name
18695 (expand-file-name "orgtex" tmpdir)))
18696 (texfile (concat texfilebase ".tex"))
18697 (dvifile (concat texfilebase ".dvi"))
18698 (pngfile (concat texfilebase ".png"))
18699 (fnh (if (featurep 'xemacs)
18700 (font-height (face-font 'default))
18701 (face-attribute 'default :height nil)))
18702 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18703 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18704 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18705 "Black"))
18706 (bg (or (plist-get options (if buffer :background :html-background))
18707 "Transparent")))
18708 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18709 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18710 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18711 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18712 (let ((latex-header (org-create-formula--latex-header)))
18713 (with-temp-file texfile
18714 (insert latex-header)
18715 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18716 (let ((dir default-directory))
18717 (condition-case nil
18718 (progn
18719 (cd tmpdir)
18720 (call-process "latex" nil nil nil texfile))
18721 (error nil))
18722 (cd dir))
18723 (if (not (file-exists-p dvifile))
18724 (progn (message "Failed to create dvi file from %s" texfile) nil)
18725 (condition-case nil
18726 (if (featurep 'xemacs)
18727 (call-process "dvipng" nil nil nil
18728 "-fg" fg "-bg" bg
18729 "-T" "tight"
18730 "-o" pngfile
18731 dvifile)
18732 (call-process "dvipng" nil nil nil
18733 "-fg" fg "-bg" bg
18734 "-D" dpi
18735 ;;"-x" scale "-y" scale
18736 "-T" "tight"
18737 "-o" pngfile
18738 dvifile))
18739 (error nil))
18740 (if (not (file-exists-p pngfile))
18741 (if org-format-latex-signal-error
18742 (error "Failed to create png file from %s" texfile)
18743 (message "Failed to create png file from %s" texfile)
18744 nil)
18745 ;; Use the requested file name and clean up
18746 (copy-file pngfile tofile 'replace)
18747 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18748 (if (file-exists-p (concat texfilebase e))
18749 (delete-file (concat texfilebase e))))
18750 pngfile))))
18752 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18753 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18754 "This calls convert, which is included into imagemagick."
18755 (require 'ox-latex)
18756 (let* ((tmpdir (if (featurep 'xemacs)
18757 (temp-directory)
18758 temporary-file-directory))
18759 (texfilebase (make-temp-name
18760 (expand-file-name "orgtex" tmpdir)))
18761 (texfile (concat texfilebase ".tex"))
18762 (pdffile (concat texfilebase ".pdf"))
18763 (pngfile (concat texfilebase ".png"))
18764 (fnh (if (featurep 'xemacs)
18765 (font-height (face-font 'default))
18766 (face-attribute 'default :height nil)))
18767 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18768 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18769 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18770 "black"))
18771 (bg (or (plist-get options (if buffer :background :html-background))
18772 "white")))
18773 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18774 (setq fg (org-latex-color-format fg)))
18775 (if (eq bg 'default) (setq bg (org-latex-color :background))
18776 (setq bg (org-latex-color-format
18777 (if (string= bg "Transparent") "white" bg))))
18778 (let ((latex-header (org-create-formula--latex-header)))
18779 (with-temp-file texfile
18780 (insert latex-header)
18781 (insert "\n\\begin{document}\n"
18782 "\\definecolor{fg}{rgb}{" fg "}\n"
18783 "\\definecolor{bg}{rgb}{" bg "}\n"
18784 "\n\\pagecolor{bg}\n"
18785 "\n{\\color{fg}\n"
18786 string
18787 "\n}\n"
18788 "\n\\end{document}\n")))
18789 (org-latex-compile texfile t)
18790 (if (not (file-exists-p pdffile))
18791 (progn (message "Failed to create pdf file from %s" texfile) nil)
18792 (condition-case nil
18793 (if (featurep 'xemacs)
18794 (call-process "convert" nil nil nil
18795 "-density" "96"
18796 "-trim"
18797 "-antialias"
18798 pdffile
18799 "-quality" "100"
18800 ;; "-sharpen" "0x1.0"
18801 pngfile)
18802 (call-process "convert" nil nil nil
18803 "-density" dpi
18804 "-trim"
18805 "-antialias"
18806 pdffile
18807 "-quality" "100"
18808 ;; "-sharpen" "0x1.0"
18809 pngfile))
18810 (error nil))
18811 (if (not (file-exists-p pngfile))
18812 (if org-format-latex-signal-error
18813 (error "Failed to create png file from %s" texfile)
18814 (message "Failed to create png file from %s" texfile)
18815 nil)
18816 ;; Use the requested file name and clean up
18817 (copy-file pngfile tofile 'replace)
18818 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18819 (if (file-exists-p (concat texfilebase e))
18820 (delete-file (concat texfilebase e))))
18821 pngfile))))
18823 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18824 "Fill a LaTeX header template TPL.
18825 In the template, the following place holders will be recognized:
18827 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18828 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18829 [PACKAGES] \\usepackage statements for PKG
18830 [NO-PACKAGES] do not include PKG
18831 [EXTRA] the string EXTRA
18832 [NO-EXTRA] do not include EXTRA
18834 For backward compatibility, if both the positive and the negative place
18835 holder is missing, the positive one (without the \"NO-\") will be
18836 assumed to be present at the end of the template.
18837 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18838 EXTRA is a string.
18839 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18840 (let (rpl (end ""))
18841 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18842 (setq rpl (if (or (match-end 1) (not def-pkg))
18843 "" (org-latex-packages-to-string def-pkg snippets-p t))
18844 tpl (replace-match rpl t t tpl))
18845 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18847 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18848 (setq rpl (if (or (match-end 1) (not pkg))
18849 "" (org-latex-packages-to-string pkg snippets-p t))
18850 tpl (replace-match rpl t t tpl))
18851 (if pkg (setq end
18852 (concat end "\n"
18853 (org-latex-packages-to-string pkg snippets-p)))))
18855 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18856 (setq rpl (if (or (match-end 1) (not extra))
18857 "" (concat extra "\n"))
18858 tpl (replace-match rpl t t tpl))
18859 (if (and extra (string-match "\\S-" extra))
18860 (setq end (concat end "\n" extra))))
18862 (if (string-match "\\S-" end)
18863 (concat tpl "\n" end)
18864 tpl)))
18866 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18867 "Turn an alist of packages into a string with the \\usepackage macros."
18868 (setq pkg (mapconcat (lambda(p)
18869 (cond
18870 ((stringp p) p)
18871 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18872 (format "%% Package %s omitted" (cadr p)))
18873 ((equal "" (car p))
18874 (format "\\usepackage{%s}" (cadr p)))
18876 (format "\\usepackage[%s]{%s}"
18877 (car p) (cadr p)))))
18879 "\n"))
18880 (if newline (concat pkg "\n") pkg))
18882 (defun org-dvipng-color (attr)
18883 "Return a RGB color specification for dvipng."
18884 (apply 'format "rgb %s %s %s"
18885 (mapcar 'org-normalize-color
18886 (if (featurep 'xemacs)
18887 (color-rgb-components
18888 (face-property 'default
18889 (cond ((eq attr :foreground) 'foreground)
18890 ((eq attr :background) 'background))))
18891 (color-values (face-attribute 'default attr nil))))))
18893 (defun org-dvipng-color-format (color-name)
18894 "Convert COLOR-NAME to a RGB color value for dvipng."
18895 (apply 'format "rgb %s %s %s"
18896 (mapcar 'org-normalize-color
18897 (color-values color-name))))
18899 (defun org-latex-color (attr)
18900 "Return a RGB color for the LaTeX color package."
18901 (apply 'format "%s,%s,%s"
18902 (mapcar 'org-normalize-color
18903 (if (featurep 'xemacs)
18904 (color-rgb-components
18905 (face-property 'default
18906 (cond ((eq attr :foreground) 'foreground)
18907 ((eq attr :background) 'background))))
18908 (color-values (face-attribute 'default attr nil))))))
18910 (defun org-latex-color-format (color-name)
18911 "Convert COLOR-NAME to a RGB color value."
18912 (apply 'format "%s,%s,%s"
18913 (mapcar 'org-normalize-color
18914 (color-values color-name))))
18916 (defun org-normalize-color (value)
18917 "Return string to be used as color value for an RGB component."
18918 (format "%g" (/ value 65535.0)))
18922 ;; Image display
18924 (defvar org-inline-image-overlays nil)
18925 (make-variable-buffer-local 'org-inline-image-overlays)
18927 (defun org-toggle-inline-images (&optional include-linked)
18928 "Toggle the display of inline images.
18929 INCLUDE-LINKED is passed to `org-display-inline-images'."
18930 (interactive "P")
18931 (if org-inline-image-overlays
18932 (progn
18933 (org-remove-inline-images)
18934 (message "Inline image display turned off"))
18935 (org-display-inline-images include-linked)
18936 (if (and (org-called-interactively-p)
18937 org-inline-image-overlays)
18938 (message "%d images displayed inline"
18939 (length org-inline-image-overlays))
18940 (message "No images to display inline"))))
18942 (defun org-redisplay-inline-images ()
18943 "Refresh the display of inline images."
18944 (interactive)
18945 (if (not org-inline-image-overlays)
18946 (org-toggle-inline-images)
18947 (org-toggle-inline-images)
18948 (org-toggle-inline-images)))
18950 (defun org-display-inline-images (&optional include-linked refresh beg end)
18951 "Display inline images.
18953 An inline image is a link which follows either of these
18954 conventions:
18956 1. Its path is a file with an extension matching return value
18957 from `image-file-name-regexp' and it has no contents.
18959 2. Its description consists in a single link of the previous
18960 type.
18962 When optional argument INCLUDE-LINKED is non-nil, also links with
18963 a text description part will be inlined. This can be nice for
18964 a quick look at those images, but it does not reflect what
18965 exported files will look like.
18967 When optional argument REFRESH is non-nil, refresh existing
18968 images between BEG and END. This will create new image displays
18969 only if necessary. BEG and END default to the buffer
18970 boundaries."
18971 (interactive "P")
18972 (when (display-graphic-p)
18973 (unless refresh
18974 (org-remove-inline-images)
18975 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18976 (org-with-wide-buffer
18977 (goto-char (or beg (point-min)))
18978 (let ((case-fold-search t)
18979 (file-extension-re (org-image-file-name-regexp)))
18980 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
18981 (let ((link (save-match-data (org-element-context))))
18982 ;; Check if we're at an inline image.
18983 (when (and (equal (org-element-property :type link) "file")
18984 (or include-linked
18985 (not (org-element-property :contents-begin link)))
18986 (let ((parent (org-element-property :parent link)))
18987 (or (not (eq (org-element-type parent) 'link))
18988 (not (cdr (org-element-contents parent)))))
18989 (org-string-match-p file-extension-re
18990 (org-element-property :path link)))
18991 (let ((file (expand-file-name (org-element-property :path link))))
18992 (when (file-exists-p file)
18993 (let ((width
18994 ;; Apply `org-image-actual-width' specifications.
18995 (cond
18996 ((not (image-type-available-p 'imagemagick)) nil)
18997 ((eq org-image-actual-width t) nil)
18998 ((listp org-image-actual-width)
19000 ;; First try to find a width among
19001 ;; attributes associated to the paragraph
19002 ;; containing link.
19003 (let ((paragraph
19004 (let ((e link))
19005 (while (and (setq e (org-element-property
19006 :parent e))
19007 (not (eq (org-element-type e)
19008 'paragraph))))
19009 e)))
19010 (when paragraph
19011 (save-excursion
19012 (goto-char (org-element-property :begin paragraph))
19013 (when (save-match-data
19014 (re-search-forward
19015 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19016 (org-element-property
19017 :post-affiliated paragraph)
19019 (string-to-number (match-string 1))))))
19020 ;; Otherwise, fall-back to provided number.
19021 (car org-image-actual-width)))
19022 ((numberp org-image-actual-width)
19023 org-image-actual-width)))
19024 (old (get-char-property-and-overlay
19025 (org-element-property :begin link)
19026 'org-image-overlay)))
19027 (if (and (car-safe old) refresh)
19028 (image-refresh (overlay-get (cdr old) 'display))
19029 (let ((image (save-match-data
19030 (create-image file
19031 (and width 'imagemagick)
19033 :width width))))
19034 (when image
19035 (let* ((link
19036 ;; If inline image is the description
19037 ;; of another link, be sure to
19038 ;; consider the latter as the one to
19039 ;; apply the overlay on.
19040 (let ((parent
19041 (org-element-property :parent link)))
19042 (if (eq (org-element-type parent) 'link)
19043 parent
19044 link)))
19045 (ov (make-overlay
19046 (org-element-property :begin link)
19047 (progn
19048 (goto-char
19049 (org-element-property :end link))
19050 (skip-chars-backward " \t")
19051 (point)))))
19052 (overlay-put ov 'display image)
19053 (overlay-put ov 'face 'default)
19054 (overlay-put ov 'org-image-overlay t)
19055 (overlay-put
19056 ov 'modification-hooks
19057 (list 'org-display-inline-remove-overlay))
19058 (push ov org-inline-image-overlays)))))))))))))))
19060 (define-obsolete-function-alias
19061 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19063 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19064 "Remove inline-display overlay if a corresponding region is modified."
19065 (let ((inhibit-modification-hooks t))
19066 (when (and ov after)
19067 (delete ov org-inline-image-overlays)
19068 (delete-overlay ov))))
19070 (defun org-remove-inline-images ()
19071 "Remove inline display of images."
19072 (interactive)
19073 (mapc 'delete-overlay org-inline-image-overlays)
19074 (setq org-inline-image-overlays nil))
19076 ;;;; Key bindings
19078 ;; Outline functions from `outline-mode-prefix-map'
19079 ;; that can be remapped in Org:
19080 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19081 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19082 (define-key org-mode-map [remap outline-forward-same-level]
19083 'org-forward-heading-same-level)
19084 (define-key org-mode-map [remap outline-backward-same-level]
19085 'org-backward-heading-same-level)
19086 (define-key org-mode-map [remap show-branches]
19087 'org-kill-note-or-show-branches)
19088 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19089 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19090 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19092 ;; Outline functions from `outline-mode-prefix-map' that can not
19093 ;; be remapped in Org:
19095 ;; - the column "key binding" shows whether the Outline function is still
19096 ;; available in Org mode on the same key that it has been bound to in
19097 ;; Outline mode:
19098 ;; - "overridden": key used for a different functionality in Org mode
19099 ;; - else: key still bound to the same Outline function in Org mode
19101 ;; | Outline function | key binding | Org replacement |
19102 ;; |------------------------------------+-------------+-----------------------|
19103 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19104 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19105 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19106 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19107 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19108 ;; | `show-entry' | overridden | no replacement |
19109 ;; | `show-children' | `C-c C-i' | visibility cycling |
19110 ;; | `show-branches' | `C-c C-k' | still same function |
19111 ;; | `show-subtree' | overridden | visibility cycling |
19112 ;; | `show-all' | overridden | no replacement |
19113 ;; | `hide-subtree' | overridden | visibility cycling |
19114 ;; | `hide-body' | overridden | no replacement |
19115 ;; | `hide-entry' | overridden | visibility cycling |
19116 ;; | `hide-leaves' | overridden | no replacement |
19117 ;; | `hide-sublevels' | overridden | no replacement |
19118 ;; | `hide-other' | overridden | no replacement |
19120 ;; Make `C-c C-x' a prefix key
19121 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19123 ;; TAB key with modifiers
19124 (org-defkey org-mode-map "\C-i" 'org-cycle)
19125 (org-defkey org-mode-map [(tab)] 'org-cycle)
19126 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19127 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19128 ;; The following line is necessary under Suse GNU/Linux
19129 (unless (featurep 'xemacs)
19130 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19131 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19132 (define-key org-mode-map [backtab] 'org-shifttab)
19134 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19135 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19136 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19138 ;; Cursor keys with modifiers
19139 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19140 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19141 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19142 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19144 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19145 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19146 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19147 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19149 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19150 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19151 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19152 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19154 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19155 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19156 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19157 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19159 ;; Babel keys
19160 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19161 (mapc (lambda (pair)
19162 (define-key org-babel-map (car pair) (cdr pair)))
19163 org-babel-key-bindings)
19165 ;;; Extra keys for tty access.
19166 ;; We only set them when really needed because otherwise the
19167 ;; menus don't show the simple keys
19169 (when (or org-use-extra-keys
19170 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19171 (not window-system))
19172 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19173 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19174 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19175 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19176 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19177 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19178 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19179 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19180 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19181 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19182 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19183 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19184 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19185 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19186 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19187 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19188 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19189 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19190 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19191 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19192 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19193 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19194 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19195 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19196 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19197 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19198 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19199 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19201 ;; All the other keys
19203 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19204 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19205 (if (boundp 'narrow-map)
19206 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19207 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19208 (if (boundp 'narrow-map)
19209 (org-defkey narrow-map "b" 'org-narrow-to-block)
19210 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19211 (if (boundp 'narrow-map)
19212 (org-defkey narrow-map "e" 'org-narrow-to-element)
19213 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19214 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19215 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19216 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19217 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19218 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19219 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19220 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19221 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19222 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19223 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19224 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19225 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19226 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19227 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19228 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19229 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19230 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19231 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19232 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19233 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19234 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19235 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19236 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19237 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19238 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19239 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19240 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19241 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19242 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19243 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19244 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19245 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19246 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19247 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19248 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19249 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19250 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19251 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19252 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19253 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19254 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19255 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19256 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19257 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19258 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19259 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19260 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19261 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19262 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19263 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19264 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19265 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19266 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19267 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19268 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19269 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19270 (org-defkey org-mode-map "\C-c^" 'org-sort)
19271 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19272 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19273 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19274 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19275 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19276 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19277 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19278 (org-defkey org-mode-map "\C-m" 'org-return)
19279 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19280 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19281 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19282 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19283 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19284 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19285 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19286 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19287 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19288 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19289 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19290 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19291 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19292 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19293 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19294 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19295 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19296 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19297 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19298 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19299 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19300 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19301 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19303 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19304 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19305 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19307 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19308 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19309 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19310 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19311 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19312 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19313 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19314 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19315 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19316 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19317 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19318 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19319 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19320 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19321 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19322 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19323 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19324 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19325 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19326 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19327 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19328 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19329 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19331 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19332 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19333 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19334 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19335 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19337 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19339 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19341 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19342 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19344 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19347 (when (featurep 'xemacs)
19348 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19351 (defconst org-speed-commands-default
19353 ("Outline Navigation")
19354 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19355 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19356 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19357 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19358 ("F" . org-next-block)
19359 ("B" . org-previous-block)
19360 ("u" . (org-speed-move-safe 'outline-up-heading))
19361 ("j" . org-goto)
19362 ("g" . (org-refile t))
19363 ("Outline Visibility")
19364 ("c" . org-cycle)
19365 ("C" . org-shifttab)
19366 (" " . org-display-outline-path)
19367 ("s" . org-narrow-to-subtree)
19368 ("=" . org-columns)
19369 ("Outline Structure Editing")
19370 ("U" . org-shiftmetaup)
19371 ("D" . org-shiftmetadown)
19372 ("r" . org-metaright)
19373 ("l" . org-metaleft)
19374 ("R" . org-shiftmetaright)
19375 ("L" . org-shiftmetaleft)
19376 ("i" . (progn (forward-char 1) (call-interactively
19377 'org-insert-heading-respect-content)))
19378 ("^" . org-sort)
19379 ("w" . org-refile)
19380 ("a" . org-archive-subtree-default-with-confirmation)
19381 ("@" . org-mark-subtree)
19382 ("#" . org-toggle-comment)
19383 ("Clock Commands")
19384 ("I" . org-clock-in)
19385 ("O" . org-clock-out)
19386 ("Meta Data Editing")
19387 ("t" . org-todo)
19388 ("," . (org-priority))
19389 ("0" . (org-priority ?\ ))
19390 ("1" . (org-priority ?A))
19391 ("2" . (org-priority ?B))
19392 ("3" . (org-priority ?C))
19393 (":" . org-set-tags-command)
19394 ("e" . org-set-effort)
19395 ("E" . org-inc-effort)
19396 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19397 (org-entry-put (point) "APPT_WARNTIME" m)))
19398 ("Agenda Views etc")
19399 ("v" . org-agenda)
19400 ("/" . org-sparse-tree)
19401 ("Misc")
19402 ("o" . org-open-at-point)
19403 ("?" . org-speed-command-help)
19404 ("<" . (org-agenda-set-restriction-lock 'subtree))
19405 (">" . (org-agenda-remove-restriction-lock))
19407 "The default speed commands.")
19409 (defun org-print-speed-command (e)
19410 (if (> (length (car e)) 1)
19411 (progn
19412 (princ "\n")
19413 (princ (car e))
19414 (princ "\n")
19415 (princ (make-string (length (car e)) ?-))
19416 (princ "\n"))
19417 (princ (car e))
19418 (princ " ")
19419 (if (symbolp (cdr e))
19420 (princ (symbol-name (cdr e)))
19421 (prin1 (cdr e)))
19422 (princ "\n")))
19424 (defun org-speed-command-help ()
19425 "Show the available speed commands."
19426 (interactive)
19427 (if (not org-use-speed-commands)
19428 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19429 (with-output-to-temp-buffer "*Help*"
19430 (princ "User-defined Speed commands\n===========================\n")
19431 (mapc 'org-print-speed-command org-speed-commands-user)
19432 (princ "\n")
19433 (princ "Built-in Speed commands\n=======================\n")
19434 (mapc 'org-print-speed-command org-speed-commands-default))
19435 (with-current-buffer "*Help*"
19436 (setq truncate-lines t))))
19438 (defun org-speed-move-safe (cmd)
19439 "Execute CMD, but make sure that the cursor always ends up in a headline.
19440 If not, return to the original position and throw an error."
19441 (interactive)
19442 (let ((pos (point)))
19443 (call-interactively cmd)
19444 (unless (and (bolp) (org-at-heading-p))
19445 (goto-char pos)
19446 (error "Boundary reached while executing %s" cmd))))
19448 (defvar org-self-insert-command-undo-counter 0)
19450 (defvar org-table-auto-blank-field) ; defined in org-table.el
19451 (defvar org-speed-command nil)
19453 (define-obsolete-function-alias
19454 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19456 (defun org-speed-command-activate (keys)
19457 "Hook for activating single-letter speed commands.
19458 `org-speed-commands-default' specifies a minimal command set.
19459 Use `org-speed-commands-user' for further customization."
19460 (when (or (and (bolp) (looking-at org-outline-regexp))
19461 (and (functionp org-use-speed-commands)
19462 (funcall org-use-speed-commands)))
19463 (cdr (assoc keys (append org-speed-commands-user
19464 org-speed-commands-default)))))
19466 (define-obsolete-function-alias
19467 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19469 (defun org-babel-speed-command-activate (keys)
19470 "Hook for activating single-letter code block commands."
19471 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19472 (cdr (assoc keys org-babel-key-bindings))))
19474 (defcustom org-speed-command-hook
19475 '(org-speed-command-default-hook org-babel-speed-command-hook)
19476 "Hook for activating speed commands at strategic locations.
19477 Hook functions are called in sequence until a valid handler is
19478 found.
19480 Each hook takes a single argument, a user-pressed command key
19481 which is also a `self-insert-command' from the global map.
19483 Within the hook, examine the cursor position and the command key
19484 and return nil or a valid handler as appropriate. Handler could
19485 be one of an interactive command, a function, or a form.
19487 Set `org-use-speed-commands' to non-nil value to enable this
19488 hook. The default setting is `org-speed-command-activate'."
19489 :group 'org-structure
19490 :version "24.1"
19491 :type 'hook)
19493 (defun org-self-insert-command (N)
19494 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19495 If the cursor is in a table looking at whitespace, the whitespace is
19496 overwritten, and the table is not marked as requiring realignment."
19497 (interactive "p")
19498 (org-check-before-invisible-edit 'insert)
19499 (cond
19500 ((and org-use-speed-commands
19501 (setq org-speed-command
19502 (run-hook-with-args-until-success
19503 'org-speed-command-hook (this-command-keys))))
19504 (cond
19505 ((commandp org-speed-command)
19506 (setq this-command org-speed-command)
19507 (call-interactively org-speed-command))
19508 ((functionp org-speed-command)
19509 (funcall org-speed-command))
19510 ((and org-speed-command (listp org-speed-command))
19511 (eval org-speed-command))
19512 (t (let (org-use-speed-commands)
19513 (call-interactively 'org-self-insert-command)))))
19514 ((and
19515 (org-table-p)
19516 (progn
19517 ;; check if we blank the field, and if that triggers align
19518 (and (featurep 'org-table) org-table-auto-blank-field
19519 (member last-command
19520 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19521 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19522 ;; got extra space, this field does not determine column width
19523 (let (org-table-may-need-update) (org-table-blank-field))
19524 ;; no extra space, this field may determine column width
19525 (org-table-blank-field)))
19527 (eq N 1)
19528 (looking-at "[^|\n]* |"))
19529 (let (org-table-may-need-update)
19530 (goto-char (1- (match-end 0)))
19531 (backward-delete-char 1)
19532 (goto-char (match-beginning 0))
19533 (self-insert-command N)))
19535 (setq org-table-may-need-update t)
19536 (self-insert-command N)
19537 (org-fix-tags-on-the-fly)
19538 (if org-self-insert-cluster-for-undo
19539 (if (not (eq last-command 'org-self-insert-command))
19540 (setq org-self-insert-command-undo-counter 1)
19541 (if (>= org-self-insert-command-undo-counter 20)
19542 (setq org-self-insert-command-undo-counter 1)
19543 (and (> org-self-insert-command-undo-counter 0)
19544 buffer-undo-list (listp buffer-undo-list)
19545 (not (cadr buffer-undo-list)) ; remove nil entry
19546 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19547 (setq org-self-insert-command-undo-counter
19548 (1+ org-self-insert-command-undo-counter))))))))
19550 (defun org-check-before-invisible-edit (kind)
19551 "Check is editing if kind KIND would be dangerous with invisible text around.
19552 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19553 ;; First, try to get out of here as quickly as possible, to reduce overhead
19554 (if (and org-catch-invisible-edits
19555 (or (not (boundp 'visible-mode)) (not visible-mode))
19556 (or (get-char-property (point) 'invisible)
19557 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19558 ;; OK, we need to take a closer look
19559 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19560 (invisible-before-point (if (bobp) nil (get-char-property
19561 (1- (point)) 'invisible)))
19562 (border-and-ok-direction
19564 ;; Check if we are acting predictably before invisible text
19565 (and invisible-at-point (not invisible-before-point)
19566 (memq kind '(insert delete-backward)))
19567 ;; Check if we are acting predictably after invisible text
19568 ;; This works not well, and I have turned it off. It seems
19569 ;; better to always show and stop after invisible text.
19570 ;; (and (not invisible-at-point) invisible-before-point
19571 ;; (memq kind '(insert delete)))
19573 (when (or (memq invisible-at-point '(outline org-hide-block t))
19574 (memq invisible-before-point '(outline org-hide-block t)))
19575 (if (eq org-catch-invisible-edits 'error)
19576 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19577 (if (and org-custom-properties-overlays
19578 (y-or-n-p "Display invisible properties in this buffer? "))
19579 (org-toggle-custom-properties-visibility)
19580 ;; Make the area visible
19581 (save-excursion
19582 (if invisible-before-point
19583 (goto-char (previous-single-char-property-change
19584 (point) 'invisible)))
19585 (org-cycle))
19586 (cond
19587 ((eq org-catch-invisible-edits 'show)
19588 ;; That's it, we do the edit after showing
19589 (message
19590 "Unfolding invisible region around point before editing")
19591 (sit-for 1))
19592 ((and (eq org-catch-invisible-edits 'smart)
19593 border-and-ok-direction)
19594 (message "Unfolding invisible region around point before editing"))
19596 ;; Don't do the edit, make the user repeat it in full visibility
19597 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19599 (defun org-fix-tags-on-the-fly ()
19600 (when (and (equal (char-after (point-at-bol)) ?*)
19601 (org-at-heading-p))
19602 (org-align-tags-here org-tags-column)))
19604 (defun org-delete-backward-char (N)
19605 "Like `delete-backward-char', insert whitespace at field end in tables.
19606 When deleting backwards, in tables this function will insert whitespace in
19607 front of the next \"|\" separator, to keep the table aligned. The table will
19608 still be marked for re-alignment if the field did fill the entire column,
19609 because, in this case the deletion might narrow the column."
19610 (interactive "p")
19611 (save-match-data
19612 (org-check-before-invisible-edit 'delete-backward)
19613 (if (and (org-table-p)
19614 (eq N 1)
19615 (string-match "|" (buffer-substring (point-at-bol) (point)))
19616 (looking-at ".*?|"))
19617 (let ((pos (point))
19618 (noalign (looking-at "[^|\n\r]* |"))
19619 (c org-table-may-need-update))
19620 (backward-delete-char N)
19621 (if (not overwrite-mode)
19622 (progn
19623 (skip-chars-forward "^|")
19624 (insert " ")
19625 (goto-char (1- pos))))
19626 ;; noalign: if there were two spaces at the end, this field
19627 ;; does not determine the width of the column.
19628 (if noalign (setq org-table-may-need-update c)))
19629 (backward-delete-char N)
19630 (org-fix-tags-on-the-fly))))
19632 (defun org-delete-char (N)
19633 "Like `delete-char', but insert whitespace at field end in tables.
19634 When deleting characters, in tables this function will insert whitespace in
19635 front of the next \"|\" separator, to keep the table aligned. The table will
19636 still be marked for re-alignment if the field did fill the entire column,
19637 because, in this case the deletion might narrow the column."
19638 (interactive "p")
19639 (save-match-data
19640 (org-check-before-invisible-edit 'delete)
19641 (if (and (org-table-p)
19642 (not (bolp))
19643 (not (= (char-after) ?|))
19644 (eq N 1))
19645 (if (looking-at ".*?|")
19646 (let ((pos (point))
19647 (noalign (looking-at "[^|\n\r]* |"))
19648 (c org-table-may-need-update))
19649 (replace-match
19650 (concat (substring (match-string 0) 1 -1) " |") nil t)
19651 (goto-char pos)
19652 ;; noalign: if there were two spaces at the end, this field
19653 ;; does not determine the width of the column.
19654 (if noalign (setq org-table-may-need-update c)))
19655 (delete-char N))
19656 (delete-char N)
19657 (org-fix-tags-on-the-fly))))
19659 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19660 (put 'org-self-insert-command 'delete-selection
19661 (lambda ()
19662 (not (run-hook-with-args-until-success
19663 'self-insert-uses-region-functions))))
19664 (put 'orgtbl-self-insert-command 'delete-selection
19665 (lambda ()
19666 (not (run-hook-with-args-until-success
19667 'self-insert-uses-region-functions))))
19668 (put 'org-delete-char 'delete-selection 'supersede)
19669 (put 'org-delete-backward-char 'delete-selection 'supersede)
19670 (put 'org-yank 'delete-selection 'yank)
19672 ;; Make `flyspell-mode' delay after some commands
19673 (put 'org-self-insert-command 'flyspell-delayed t)
19674 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19675 (put 'org-delete-char 'flyspell-delayed t)
19676 (put 'org-delete-backward-char 'flyspell-delayed t)
19678 ;; Make pabbrev-mode expand after org-mode commands
19679 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19680 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19682 (defun org-remap (map &rest commands)
19683 "In MAP, remap the functions given in COMMANDS.
19684 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19685 (let (new old)
19686 (while commands
19687 (setq old (pop commands) new (pop commands))
19688 (if (fboundp 'command-remapping)
19689 (org-defkey map (vector 'remap old) new)
19690 (substitute-key-definition old new map global-map)))))
19692 (defun org-transpose-words ()
19693 "Transpose words for Org.
19694 This uses the `org-mode-transpose-word-syntax-table' syntax
19695 table, which interprets characters in `org-emphasis-alist' as
19696 word constituents."
19697 (interactive)
19698 (with-syntax-table org-mode-transpose-word-syntax-table
19699 (call-interactively 'transpose-words)))
19700 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19702 (when (eq org-enable-table-editor 'optimized)
19703 ;; If the user wants maximum table support, we need to hijack
19704 ;; some standard editing functions
19705 (org-remap org-mode-map
19706 'self-insert-command 'org-self-insert-command
19707 'delete-char 'org-delete-char
19708 'delete-backward-char 'org-delete-backward-char)
19709 (org-defkey org-mode-map "|" 'org-force-self-insert))
19711 (defvar org-ctrl-c-ctrl-c-hook nil
19712 "Hook for functions attaching themselves to `C-c C-c'.
19714 This can be used to add additional functionality to the C-c C-c
19715 key which executes context-dependent commands. This hook is run
19716 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19717 run after the last test.
19719 Each function will be called with no arguments. The function
19720 must check if the context is appropriate for it to act. If yes,
19721 it should do its thing and then return a non-nil value. If the
19722 context is wrong, just do nothing and return nil.")
19724 (defvar org-ctrl-c-ctrl-c-final-hook nil
19725 "Hook for functions attaching themselves to `C-c C-c'.
19727 This can be used to add additional functionality to the C-c C-c
19728 key which executes context-dependent commands. This hook is run
19729 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19730 before the first test.
19732 Each function will be called with no arguments. The function
19733 must check if the context is appropriate for it to act. If yes,
19734 it should do its thing and then return a non-nil value. If the
19735 context is wrong, just do nothing and return nil.")
19737 (defvar org-tab-first-hook nil
19738 "Hook for functions to attach themselves to TAB.
19739 See `org-ctrl-c-ctrl-c-hook' for more information.
19740 This hook runs as the first action when TAB is pressed, even before
19741 `org-cycle' messes around with the `outline-regexp' to cater for
19742 inline tasks and plain list item folding.
19743 If any function in this hook returns t, any other actions that
19744 would have been caused by TAB (such as table field motion or visibility
19745 cycling) will not occur.")
19747 (defvar org-tab-after-check-for-table-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 it has been established that the cursor is not in a
19751 table, but before checking if the cursor is in a headline or if global cycling
19752 should be done.
19753 If any function in this hook returns t, not other actions like visibility
19754 cycling will be done.")
19756 (defvar org-tab-after-check-for-cycling-hook nil
19757 "Hook for functions to attach themselves to TAB.
19758 See `org-ctrl-c-ctrl-c-hook' for more information.
19759 This hook runs after it has been established that not table field motion and
19760 not visibility should be done because of current context. This is probably
19761 the place where a package like yasnippets can hook in.")
19763 (defvar org-tab-before-tab-emulation-hook nil
19764 "Hook for functions to attach themselves to TAB.
19765 See `org-ctrl-c-ctrl-c-hook' for more information.
19766 This hook runs after every other options for TAB have been exhausted, but
19767 before indentation and \t insertion takes place.")
19769 (defvar org-metaleft-hook nil
19770 "Hook for functions attaching themselves to `M-left'.
19771 See `org-ctrl-c-ctrl-c-hook' for more information.")
19772 (defvar org-metaright-hook nil
19773 "Hook for functions attaching themselves to `M-right'.
19774 See `org-ctrl-c-ctrl-c-hook' for more information.")
19775 (defvar org-metaup-hook nil
19776 "Hook for functions attaching themselves to `M-up'.
19777 See `org-ctrl-c-ctrl-c-hook' for more information.")
19778 (defvar org-metadown-hook nil
19779 "Hook for functions attaching themselves to `M-down'.
19780 See `org-ctrl-c-ctrl-c-hook' for more information.")
19781 (defvar org-shiftmetaleft-hook nil
19782 "Hook for functions attaching themselves to `M-S-left'.
19783 See `org-ctrl-c-ctrl-c-hook' for more information.")
19784 (defvar org-shiftmetaright-hook nil
19785 "Hook for functions attaching themselves to `M-S-right'.
19786 See `org-ctrl-c-ctrl-c-hook' for more information.")
19787 (defvar org-shiftmetaup-hook nil
19788 "Hook for functions attaching themselves to `M-S-up'.
19789 See `org-ctrl-c-ctrl-c-hook' for more information.")
19790 (defvar org-shiftmetadown-hook nil
19791 "Hook for functions attaching themselves to `M-S-down'.
19792 See `org-ctrl-c-ctrl-c-hook' for more information.")
19793 (defvar org-metareturn-hook nil
19794 "Hook for functions attaching themselves to `M-RET'.
19795 See `org-ctrl-c-ctrl-c-hook' for more information.")
19796 (defvar org-shiftup-hook nil
19797 "Hook for functions attaching themselves to `S-up'.
19798 See `org-ctrl-c-ctrl-c-hook' for more information.")
19799 (defvar org-shiftup-final-hook nil
19800 "Hook for functions attaching themselves to `S-up'.
19801 This one runs after all other options except shift-select have been excluded.
19802 See `org-ctrl-c-ctrl-c-hook' for more information.")
19803 (defvar org-shiftdown-hook nil
19804 "Hook for functions attaching themselves to `S-down'.
19805 See `org-ctrl-c-ctrl-c-hook' for more information.")
19806 (defvar org-shiftdown-final-hook nil
19807 "Hook for functions attaching themselves to `S-down'.
19808 This one runs after all other options except shift-select have been excluded.
19809 See `org-ctrl-c-ctrl-c-hook' for more information.")
19810 (defvar org-shiftleft-hook nil
19811 "Hook for functions attaching themselves to `S-left'.
19812 See `org-ctrl-c-ctrl-c-hook' for more information.")
19813 (defvar org-shiftleft-final-hook nil
19814 "Hook for functions attaching themselves to `S-left'.
19815 This one runs after all other options except shift-select have been excluded.
19816 See `org-ctrl-c-ctrl-c-hook' for more information.")
19817 (defvar org-shiftright-hook nil
19818 "Hook for functions attaching themselves to `S-right'.
19819 See `org-ctrl-c-ctrl-c-hook' for more information.")
19820 (defvar org-shiftright-final-hook nil
19821 "Hook for functions attaching themselves to `S-right'.
19822 This one runs after all other options except shift-select have been excluded.
19823 See `org-ctrl-c-ctrl-c-hook' for more information.")
19825 (defun org-modifier-cursor-error ()
19826 "Throw an error, a modified cursor command was applied in wrong context."
19827 (user-error "This command is active in special context like tables, headlines or items"))
19829 (defun org-shiftselect-error ()
19830 "Throw an error because Shift-Cursor command was applied in wrong context."
19831 (if (and (boundp 'shift-select-mode) shift-select-mode)
19832 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19833 (user-error "This command works only in special context like headlines or timestamps")))
19835 (defun org-call-for-shift-select (cmd)
19836 (let ((this-command-keys-shift-translated t))
19837 (call-interactively cmd)))
19839 (defun org-shifttab (&optional arg)
19840 "Global visibility cycling or move to previous table field.
19841 Call `org-table-previous-field' within a table.
19842 When ARG is nil, cycle globally through visibility states.
19843 When ARG is a numeric prefix, show contents of this level."
19844 (interactive "P")
19845 (cond
19846 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19847 ((integerp arg)
19848 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19849 (message "Content view to level: %d" arg)
19850 (org-content (prefix-numeric-value arg2))
19851 (org-cycle-show-empty-lines t)
19852 (setq org-cycle-global-status 'overview)))
19853 (t (call-interactively 'org-global-cycle))))
19855 (defun org-shiftmetaleft ()
19856 "Promote subtree or delete table column.
19857 Calls `org-promote-subtree', `org-outdent-item-tree', or
19858 `org-table-delete-column', depending on context. See the
19859 individual commands for more information."
19860 (interactive)
19861 (cond
19862 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19863 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19864 ((org-at-heading-p) (call-interactively 'org-promote-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-outdent-item-tree))
19869 (t (org-modifier-cursor-error))))
19871 (defun org-shiftmetaright ()
19872 "Demote subtree or insert table column.
19873 Calls `org-demote-subtree', `org-indent-item-tree', or
19874 `org-table-insert-column', depending on context. See the
19875 individual commands for more information."
19876 (interactive)
19877 (cond
19878 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19879 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19880 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19881 ((if (not (org-region-active-p)) (org-at-item-p)
19882 (save-excursion (goto-char (region-beginning))
19883 (org-at-item-p)))
19884 (call-interactively 'org-indent-item-tree))
19885 (t (org-modifier-cursor-error))))
19887 (defun org-shiftmetaup (&optional arg)
19888 "Move subtree up or kill table row.
19889 Calls `org-move-subtree-up' or `org-table-kill-row' or
19890 `org-move-item-up' or `org-timestamp-up', depending on context.
19891 See the individual commands for more information."
19892 (interactive "P")
19893 (cond
19894 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19895 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19896 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19897 ((org-at-item-p) (call-interactively 'org-move-item-up))
19898 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19899 (call-interactively 'org-timestamp-up)))
19900 (t (call-interactively 'org-drag-line-backward))))
19902 (defun org-shiftmetadown (&optional arg)
19903 "Move subtree down or insert table row.
19904 Calls `org-move-subtree-down' or `org-table-insert-row' or
19905 `org-move-item-down' or `org-timestamp-up', depending on context.
19906 See the individual commands for more information."
19907 (interactive "P")
19908 (cond
19909 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19910 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19911 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19912 ((org-at-item-p) (call-interactively 'org-move-item-down))
19913 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19914 (call-interactively 'org-timestamp-down)))
19915 (t (call-interactively 'org-drag-line-forward))))
19917 (defsubst org-hidden-tree-error ()
19918 (user-error
19919 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19921 (defun org-metaleft (&optional arg)
19922 "Promote heading or move table column to left.
19923 Calls `org-do-promote' or `org-table-move-column', depending on context.
19924 With no specific context, calls the Emacs default `backward-word'.
19925 See the individual commands for more information."
19926 (interactive "P")
19927 (cond
19928 ((run-hook-with-args-until-success 'org-metaleft-hook))
19929 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19930 ((org-with-limited-levels
19931 (or (org-at-heading-p)
19932 (and (org-region-active-p)
19933 (save-excursion
19934 (goto-char (region-beginning))
19935 (org-at-heading-p)))))
19936 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19937 (call-interactively 'org-do-promote))
19938 ;; At an inline task.
19939 ((org-at-heading-p)
19940 (call-interactively 'org-inlinetask-promote))
19941 ((or (org-at-item-p)
19942 (and (org-region-active-p)
19943 (save-excursion
19944 (goto-char (region-beginning))
19945 (org-at-item-p))))
19946 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19947 (call-interactively 'org-outdent-item))
19948 (t (call-interactively 'backward-word))))
19950 (defun org-metaright (&optional arg)
19951 "Demote a subtree, a list item or move table column to right.
19952 In front of a drawer or a block keyword, indent it correctly.
19953 With no specific context, calls the Emacs default `forward-word'.
19954 See the individual commands for more information."
19955 (interactive "P")
19956 (cond
19957 ((run-hook-with-args-until-success 'org-metaright-hook))
19958 ((org-at-table-p) (call-interactively 'org-table-move-column))
19959 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19960 ((org-at-block-p) (call-interactively 'org-indent-block))
19961 ((org-with-limited-levels
19962 (or (org-at-heading-p)
19963 (and (org-region-active-p)
19964 (save-excursion
19965 (goto-char (region-beginning))
19966 (org-at-heading-p)))))
19967 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19968 (call-interactively 'org-do-demote))
19969 ;; At an inline task.
19970 ((org-at-heading-p)
19971 (call-interactively 'org-inlinetask-demote))
19972 ((or (org-at-item-p)
19973 (and (org-region-active-p)
19974 (save-excursion
19975 (goto-char (region-beginning))
19976 (org-at-item-p))))
19977 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19978 (call-interactively 'org-indent-item))
19979 (t (call-interactively 'forward-word))))
19981 (defun org-check-for-hidden (what)
19982 "Check if there are hidden headlines/items in the current visual line.
19983 WHAT can be either `headlines' or `items'. If the current line is
19984 an outline or item heading and it has a folded subtree below it,
19985 this function returns t, nil otherwise."
19986 (let ((re (cond
19987 ((eq what 'headlines) org-outline-regexp-bol)
19988 ((eq what 'items) (org-item-beginning-re))
19989 (t (error "This should not happen"))))
19990 beg end)
19991 (save-excursion
19992 (catch 'exit
19993 (unless (org-region-active-p)
19994 (setq beg (point-at-bol))
19995 (beginning-of-line 2)
19996 (while (and (not (eobp)) ;; this is like `next-line'
19997 (get-char-property (1- (point)) 'invisible))
19998 (beginning-of-line 2))
19999 (setq end (point))
20000 (goto-char beg)
20001 (goto-char (point-at-eol))
20002 (setq end (max end (point)))
20003 (while (re-search-forward re end t)
20004 (if (get-char-property (match-beginning 0) 'invisible)
20005 (throw 'exit t))))
20006 nil))))
20008 (defun org-metaup (&optional arg)
20009 "Move subtree up or move table row up.
20010 Calls `org-move-subtree-up' or `org-table-move-row' or
20011 `org-move-item-up', depending on context. See the individual commands
20012 for more information."
20013 (interactive "P")
20014 (cond
20015 ((run-hook-with-args-until-success 'org-metaup-hook))
20016 ((org-region-active-p)
20017 (let* ((a (min (region-beginning) (region-end)))
20018 (b (1- (max (region-beginning) (region-end))))
20019 (c (save-excursion (goto-char a)
20020 (move-beginning-of-line 0)))
20021 (d (save-excursion (goto-char a)
20022 (move-end-of-line 0) (point))))
20023 (transpose-regions a b c d)
20024 (goto-char c)))
20025 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20026 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20027 ((org-at-item-p) (call-interactively 'org-move-item-up))
20028 (t (org-drag-element-backward))))
20030 (defun org-metadown (&optional arg)
20031 "Move subtree down or move table row down.
20032 Calls `org-move-subtree-down' or `org-table-move-row' or
20033 `org-move-item-down', depending on context. See the individual
20034 commands for more information."
20035 (interactive "P")
20036 (cond
20037 ((run-hook-with-args-until-success 'org-metadown-hook))
20038 ((org-region-active-p)
20039 (let* ((a (min (region-beginning) (region-end)))
20040 (b (max (region-beginning) (region-end)))
20041 (c (save-excursion (goto-char b)
20042 (move-beginning-of-line 1)))
20043 (d (save-excursion (goto-char b)
20044 (move-end-of-line 1) (1+ (point)))))
20045 (transpose-regions a b c d)
20046 (goto-char d)))
20047 ((org-at-table-p) (call-interactively 'org-table-move-row))
20048 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20049 ((org-at-item-p) (call-interactively 'org-move-item-down))
20050 (t (org-drag-element-forward))))
20052 (defun org-shiftup (&optional arg)
20053 "Increase item in timestamp or increase priority of current headline.
20054 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20055 depending on context. See the individual commands for more information."
20056 (interactive "P")
20057 (cond
20058 ((run-hook-with-args-until-success 'org-shiftup-hook))
20059 ((and org-support-shift-select (org-region-active-p))
20060 (org-call-for-shift-select 'previous-line))
20061 ((org-at-timestamp-p t)
20062 (call-interactively (if org-edit-timestamp-down-means-later
20063 'org-timestamp-down 'org-timestamp-up)))
20064 ((and (not (eq org-support-shift-select 'always))
20065 org-enable-priority-commands
20066 (org-at-heading-p))
20067 (call-interactively 'org-priority-up))
20068 ((and (not org-support-shift-select) (org-at-item-p))
20069 (call-interactively 'org-previous-item))
20070 ((org-clocktable-try-shift 'up arg))
20071 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20072 (org-support-shift-select
20073 (org-call-for-shift-select 'previous-line))
20074 (t (org-shiftselect-error))))
20076 (defun org-shiftdown (&optional arg)
20077 "Decrease item in timestamp or decrease priority of current headline.
20078 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20079 depending on context. See the individual commands for more information."
20080 (interactive "P")
20081 (cond
20082 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20083 ((and org-support-shift-select (org-region-active-p))
20084 (org-call-for-shift-select 'next-line))
20085 ((org-at-timestamp-p t)
20086 (call-interactively (if org-edit-timestamp-down-means-later
20087 'org-timestamp-up 'org-timestamp-down)))
20088 ((and (not (eq org-support-shift-select 'always))
20089 org-enable-priority-commands
20090 (org-at-heading-p))
20091 (call-interactively 'org-priority-down))
20092 ((and (not org-support-shift-select) (org-at-item-p))
20093 (call-interactively 'org-next-item))
20094 ((org-clocktable-try-shift 'down arg))
20095 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20096 (org-support-shift-select
20097 (org-call-for-shift-select 'next-line))
20098 (t (org-shiftselect-error))))
20100 (defun org-shiftright (&optional arg)
20101 "Cycle the thing at point or in the current line, depending on context.
20102 Depending on context, this does one of the following:
20104 - switch a timestamp at point one day into the future
20105 - on a headline, switch to the next TODO keyword.
20106 - on an item, switch entire list to the next bullet type
20107 - on a property line, switch to the next allowed value
20108 - on a clocktable definition line, move time block into the future"
20109 (interactive "P")
20110 (cond
20111 ((run-hook-with-args-until-success 'org-shiftright-hook))
20112 ((and org-support-shift-select (org-region-active-p))
20113 (org-call-for-shift-select 'forward-char))
20114 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20115 ((and (not (eq org-support-shift-select 'always))
20116 (org-at-heading-p))
20117 (let ((org-inhibit-logging
20118 (not org-treat-S-cursor-todo-selection-as-state-change))
20119 (org-inhibit-blocking
20120 (not org-treat-S-cursor-todo-selection-as-state-change)))
20121 (org-call-with-arg 'org-todo 'right)))
20122 ((or (and org-support-shift-select
20123 (not (eq org-support-shift-select 'always))
20124 (org-at-item-bullet-p))
20125 (and (not org-support-shift-select) (org-at-item-p)))
20126 (org-call-with-arg 'org-cycle-list-bullet nil))
20127 ((and (not (eq org-support-shift-select 'always))
20128 (org-at-property-p))
20129 (call-interactively 'org-property-next-allowed-value))
20130 ((org-clocktable-try-shift 'right arg))
20131 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20132 (org-support-shift-select
20133 (org-call-for-shift-select 'forward-char))
20134 (t (org-shiftselect-error))))
20136 (defun org-shiftleft (&optional arg)
20137 "Cycle the thing at point or in the current line, depending on context.
20138 Depending on context, this does one of the following:
20140 - switch a timestamp at point one day into the past
20141 - on a headline, switch to the previous TODO keyword.
20142 - on an item, switch entire list to the previous bullet type
20143 - on a property line, switch to the previous allowed value
20144 - on a clocktable definition line, move time block into the past"
20145 (interactive "P")
20146 (cond
20147 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20148 ((and org-support-shift-select (org-region-active-p))
20149 (org-call-for-shift-select 'backward-char))
20150 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20151 ((and (not (eq org-support-shift-select 'always))
20152 (org-at-heading-p))
20153 (let ((org-inhibit-logging
20154 (not org-treat-S-cursor-todo-selection-as-state-change))
20155 (org-inhibit-blocking
20156 (not org-treat-S-cursor-todo-selection-as-state-change)))
20157 (org-call-with-arg 'org-todo 'left)))
20158 ((or (and org-support-shift-select
20159 (not (eq org-support-shift-select 'always))
20160 (org-at-item-bullet-p))
20161 (and (not org-support-shift-select) (org-at-item-p)))
20162 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20163 ((and (not (eq org-support-shift-select 'always))
20164 (org-at-property-p))
20165 (call-interactively 'org-property-previous-allowed-value))
20166 ((org-clocktable-try-shift 'left arg))
20167 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20168 (org-support-shift-select
20169 (org-call-for-shift-select 'backward-char))
20170 (t (org-shiftselect-error))))
20172 (defun org-shiftcontrolright ()
20173 "Switch to next TODO set."
20174 (interactive)
20175 (cond
20176 ((and org-support-shift-select (org-region-active-p))
20177 (org-call-for-shift-select 'forward-word))
20178 ((and (not (eq org-support-shift-select 'always))
20179 (org-at-heading-p))
20180 (org-call-with-arg 'org-todo 'nextset))
20181 (org-support-shift-select
20182 (org-call-for-shift-select 'forward-word))
20183 (t (org-shiftselect-error))))
20185 (defun org-shiftcontrolleft ()
20186 "Switch to previous TODO set."
20187 (interactive)
20188 (cond
20189 ((and org-support-shift-select (org-region-active-p))
20190 (org-call-for-shift-select 'backward-word))
20191 ((and (not (eq org-support-shift-select 'always))
20192 (org-at-heading-p))
20193 (org-call-with-arg 'org-todo 'previousset))
20194 (org-support-shift-select
20195 (org-call-for-shift-select 'backward-word))
20196 (t (org-shiftselect-error))))
20198 (defun org-shiftcontrolup (&optional n)
20199 "Change timestamps synchronously up in CLOCK log lines.
20200 Optional argument N tells to change by that many units."
20201 (interactive "P")
20202 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20203 (let (org-support-shift-select)
20204 (org-clock-timestamps-up n))
20205 (user-error "Not at a clock log")))
20207 (defun org-shiftcontroldown (&optional n)
20208 "Change timestamps synchronously down in CLOCK log lines.
20209 Optional argument N tells to change by that many units."
20210 (interactive "P")
20211 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20212 (let (org-support-shift-select)
20213 (org-clock-timestamps-down n))
20214 (user-error "Not at a clock log")))
20216 (defun org-ctrl-c-ret ()
20217 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20218 (interactive)
20219 (cond
20220 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20221 (t (call-interactively 'org-insert-heading))))
20223 (defun org-find-visible ()
20224 (let ((s (point)))
20225 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20226 (get-char-property s 'invisible)))
20228 (defun org-find-invisible ()
20229 (let ((s (point)))
20230 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20231 (not (get-char-property s 'invisible))))
20234 (defun org-copy-visible (beg end)
20235 "Copy the visible parts of the region."
20236 (interactive "r")
20237 (let (snippets s)
20238 (save-excursion
20239 (save-restriction
20240 (narrow-to-region beg end)
20241 (setq s (goto-char (point-min)))
20242 (while (not (= (point) (point-max)))
20243 (goto-char (org-find-invisible))
20244 (push (buffer-substring s (point)) snippets)
20245 (setq s (goto-char (org-find-visible))))))
20246 (kill-new (apply 'concat (nreverse snippets)))))
20248 (defun org-copy-special ()
20249 "Copy region in table or copy current subtree.
20250 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20251 See the individual commands for more information."
20252 (interactive)
20253 (call-interactively
20254 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20256 (defun org-cut-special ()
20257 "Cut region in table or cut current subtree.
20258 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20259 See the individual commands for more information."
20260 (interactive)
20261 (call-interactively
20262 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20264 (defun org-paste-special (arg)
20265 "Paste rectangular region into table, or past subtree relative to level.
20266 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20267 See the individual commands for more information."
20268 (interactive "P")
20269 (if (org-at-table-p)
20270 (org-table-paste-rectangle)
20271 (org-paste-subtree arg)))
20273 (defsubst org-in-fixed-width-region-p ()
20274 "Is point in a fixed-width region?"
20275 (save-match-data
20276 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20278 (defun org-edit-special (&optional arg)
20279 "Call a special editor for the element at point.
20280 When at a table, call the formula editor with `org-table-edit-formulas'.
20281 When in a source code block, call `org-edit-src-code'.
20282 When in a fixed-width region, call `org-edit-fixed-width-region'.
20283 When at an #+INCLUDE keyword, visit the included file.
20284 On a link, call `ffap' to visit the link at point.
20285 Otherwise, return a user error."
20286 (interactive "P")
20287 (let ((element (org-element-at-point)))
20288 (assert (not buffer-read-only) nil
20289 "Buffer is read-only: %s" (buffer-name))
20290 (case (org-element-type element)
20291 (src-block
20292 (if (not arg) (org-edit-src-code)
20293 (let* ((info (org-babel-get-src-block-info))
20294 (lang (nth 0 info))
20295 (params (nth 2 info))
20296 (session (cdr (assq :session params))))
20297 (if (not session) (org-edit-src-code)
20298 ;; At a src-block with a session and function called with
20299 ;; an ARG: switch to the buffer related to the inferior
20300 ;; process.
20301 (switch-to-buffer
20302 (funcall (intern (concat "org-babel-prep-session:" lang))
20303 session params))))))
20304 (keyword
20305 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20306 (find-file-other-window
20307 (org-remove-double-quotes
20308 (car (org-split-string (org-element-property :value element)))))
20309 (user-error "No special environment to edit here")))
20310 (table
20311 (if (eq (org-element-property :type element) 'table.el)
20312 (org-edit-src-code)
20313 (call-interactively 'org-table-edit-formulas)))
20314 ;; Only Org tables contain `table-row' type elements.
20315 (table-row (call-interactively 'org-table-edit-formulas))
20316 ((example-block export-block) (org-edit-src-code))
20317 (fixed-width (org-edit-fixed-width-region))
20318 (otherwise
20319 ;; No notable element at point. Though, we may be at a link,
20320 ;; which is an object. Thus, scan deeper.
20321 (if (eq (org-element-type (org-element-context element)) 'link)
20322 (call-interactively 'ffap)
20323 (user-error "No special environment to edit here"))))))
20325 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20326 (defun org-ctrl-c-ctrl-c (&optional arg)
20327 "Set tags in headline, or update according to changed information at point.
20329 This command does many different things, depending on context:
20331 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20332 this is what we do.
20334 - If the cursor is on a statistics cookie, update it.
20336 - If the cursor is in a headline, prompt for tags and insert them
20337 into the current line, aligned to `org-tags-column'. When called
20338 with prefix arg, realign all tags in the current buffer.
20340 - If the cursor is in one of the special #+KEYWORD lines, this
20341 triggers scanning the buffer for these lines and updating the
20342 information.
20344 - If the cursor is inside a table, realign the table. This command
20345 works even if the automatic table editor has been turned off.
20347 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20348 the entire table.
20350 - If the cursor is at a footnote reference or definition, jump to
20351 the corresponding definition or references, respectively.
20353 - If the cursor is a the beginning of a dynamic block, update it.
20355 - If the current buffer is a capture buffer, close note and file it.
20357 - If the cursor is on a <<<target>>>, update radio targets and
20358 corresponding links in this buffer.
20360 - If the cursor is on a numbered item in a plain list, renumber the
20361 ordered list.
20363 - If the cursor is on a checkbox, toggle it.
20365 - If the cursor is on a code block, evaluate it. The variable
20366 `org-confirm-babel-evaluate' can be used to control prompting
20367 before code block evaluation, by default every code block
20368 evaluation requires confirmation. Code block evaluation can be
20369 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20370 (interactive "P")
20371 (cond
20372 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20373 org-occur-highlights
20374 org-latex-fragment-image-overlays)
20375 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20376 (org-remove-occur-highlights)
20377 (org-remove-latex-fragment-image-overlays)
20378 (message "Temporary highlights/overlays removed from current buffer"))
20379 ((and (local-variable-p 'org-finish-function (current-buffer))
20380 (fboundp org-finish-function))
20381 (funcall org-finish-function))
20382 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20384 (let* ((context (org-element-context)) (type (org-element-type context)))
20385 ;; Test if point is within a blank line.
20386 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20387 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20388 (user-error "C-c C-c can do nothing useful at this location"))
20389 (case type
20390 ;; When at a link, act according to the parent instead.
20391 (link (setq context (org-element-property :parent context))
20392 (setq type (org-element-type context)))
20393 ;; Unsupported object types: check parent element instead.
20394 ((bold code entity export-snippet inline-babel-call inline-src-block
20395 italic latex-fragment line-break macro strike-through subscript
20396 superscript underline verbatim)
20397 (while (and (setq context (org-element-property :parent context))
20398 (not (memq (setq type (org-element-type context))
20399 '(paragraph verse-block table-cell)))))))
20400 ;; For convenience: at the first line of a paragraph on the
20401 ;; same line as an item, apply function on that item instead.
20402 (when (eq type 'paragraph)
20403 (let ((parent (org-element-property :parent context)))
20404 (when (and (eq (org-element-type parent) 'item)
20405 (= (point-at-bol) (org-element-property :begin parent)))
20406 (setq context parent type 'item))))
20407 ;; Act according to type of element or object at point.
20408 (case type
20409 (clock (org-clock-update-time-maybe))
20410 (dynamic-block
20411 (save-excursion
20412 (goto-char (org-element-property :post-affiliated context))
20413 (org-update-dblock)))
20414 (footnote-definition
20415 (goto-char (org-element-property :post-affiliated context))
20416 (call-interactively 'org-footnote-action))
20417 (footnote-reference (call-interactively 'org-footnote-action))
20418 ((headline inlinetask)
20419 (save-excursion (goto-char (org-element-property :begin context))
20420 (call-interactively 'org-set-tags)))
20421 (item
20422 ;; At an item: a double C-u set checkbox to "[-]"
20423 ;; unconditionally, whereas a single one will toggle its
20424 ;; presence. Without an universal argument, if the item
20425 ;; has a checkbox, toggle it. Otherwise repair the list.
20426 (let* ((box (org-element-property :checkbox context))
20427 (struct (org-element-property :structure context))
20428 (old-struct (copy-tree struct))
20429 (parents (org-list-parents-alist struct))
20430 (prevs (org-list-prevs-alist struct))
20431 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20432 (org-list-set-checkbox
20433 (org-element-property :begin context) struct
20434 (cond ((equal arg '(16)) "[-]")
20435 ((and (not box) (equal arg '(4))) "[ ]")
20436 ((or (not box) (equal arg '(4))) nil)
20437 ((eq box 'on) "[ ]")
20438 (t "[X]")))
20439 ;; Mimic `org-list-write-struct' but with grabbing
20440 ;; a return value from `org-list-struct-fix-box'.
20441 (org-list-struct-fix-ind struct parents 2)
20442 (org-list-struct-fix-item-end struct)
20443 (org-list-struct-fix-bul struct prevs)
20444 (org-list-struct-fix-ind struct parents)
20445 (let ((block-item
20446 (org-list-struct-fix-box struct parents prevs orderedp)))
20447 (if (and box (equal struct old-struct))
20448 (if (equal arg '(16))
20449 (message "Checkboxes already reset")
20450 (user-error "Cannot toggle this checkbox: %s"
20451 (if (eq box 'on)
20452 "all subitems checked"
20453 "unchecked subitems")))
20454 (org-list-struct-apply-struct struct old-struct)
20455 (org-update-checkbox-count-maybe))
20456 (when block-item
20457 (message "Checkboxes were removed due to empty box at line %d"
20458 (org-current-line block-item))))))
20459 (keyword
20460 (let ((org-inhibit-startup-visibility-stuff t)
20461 (org-startup-align-all-tables nil))
20462 (when (boundp 'org-table-coordinate-overlays)
20463 (mapc 'delete-overlay org-table-coordinate-overlays)
20464 (setq org-table-coordinate-overlays nil))
20465 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20466 (message "Local setup has been refreshed"))
20467 (plain-list
20468 ;; At a plain list, with a double C-u argument, set
20469 ;; checkboxes of each item to "[-]", whereas a single one
20470 ;; will toggle their presence according to the state of the
20471 ;; first item in the list. Without an argument, repair the
20472 ;; list.
20473 (let* ((begin (org-element-property :contents-begin context))
20474 (beginm (move-marker (make-marker) begin))
20475 (struct (org-element-property :structure context))
20476 (old-struct (copy-tree struct))
20477 (first-box (save-excursion
20478 (goto-char begin)
20479 (looking-at org-list-full-item-re)
20480 (match-string-no-properties 3)))
20481 (new-box (cond ((equal arg '(16)) "[-]")
20482 ((equal arg '(4)) (unless first-box "[ ]"))
20483 ((equal first-box "[X]") "[ ]")
20484 (t "[X]"))))
20485 (cond
20486 (arg
20487 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20488 (org-list-get-all-items
20489 begin struct (org-list-prevs-alist struct))))
20490 ((and first-box (eq (point) begin))
20491 ;; For convenience, when point is at bol on the first
20492 ;; item of the list and no argument is provided, simply
20493 ;; toggle checkbox of that item, if any.
20494 (org-list-set-checkbox begin struct new-box)))
20495 (org-list-write-struct
20496 struct (org-list-parents-alist struct) old-struct)
20497 (org-update-checkbox-count-maybe)
20498 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20499 ((property-drawer node-property)
20500 (call-interactively 'org-property-action))
20501 ((radio-target target)
20502 (call-interactively 'org-update-radio-target-regexp))
20503 (statistics-cookie
20504 (call-interactively 'org-update-statistics-cookies))
20505 ((table table-cell table-row)
20506 ;; At a table, recalculate every field and align it. Also
20507 ;; send the table if necessary. If the table has
20508 ;; a `table.el' type, just give up. At a table row or
20509 ;; cell, maybe recalculate line but always align table.
20510 (if (eq (org-element-property :type context) 'table.el)
20511 (message "Use C-c ' to edit table.el tables")
20512 (let ((org-enable-table-editor t))
20513 (if (or (eq type 'table)
20514 ;; Check if point is at a TBLFM line.
20515 (and (eq type 'table-row)
20516 (= (point) (org-element-property :end context))))
20517 (save-excursion
20518 (if (org-at-TBLFM-p)
20519 (progn (require 'org-table)
20520 (org-table-calc-current-TBLFM))
20521 (goto-char (org-element-property :contents-begin context))
20522 (org-call-with-arg 'org-table-recalculate (or arg t))
20523 (orgtbl-send-table 'maybe)))
20524 (org-table-maybe-eval-formula)
20525 (cond (arg (call-interactively 'org-table-recalculate))
20526 ((org-table-maybe-recalculate-line))
20527 (t (org-table-align)))))))
20528 (timestamp (org-timestamp-change 0 'day))
20529 (otherwise
20530 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20531 (user-error
20532 "C-c C-c can do nothing useful at this location")))))))))
20534 (defun org-mode-restart ()
20535 (interactive)
20536 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20537 (funcall major-mode)
20538 (hack-local-variables)
20539 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20540 (org-indent-mode -1)))
20541 (message "%s restarted" major-mode))
20543 (defun org-kill-note-or-show-branches ()
20544 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20545 (interactive)
20546 (if (not org-finish-function)
20547 (progn
20548 (hide-subtree)
20549 (call-interactively 'show-branches))
20550 (let ((org-note-abort t))
20551 (funcall org-finish-function))))
20553 (defun org-open-line (n)
20554 "Insert a new row in tables, call `open-line' elsewhere.
20555 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20556 (interactive "*p")
20557 (cond
20558 ((not org-special-ctrl-o)
20559 (open-line n))
20560 ((org-at-table-p)
20561 (org-table-insert-row))
20563 (open-line n))))
20565 (defun org-return (&optional indent)
20566 "Goto next table row or insert a newline.
20567 Calls `org-table-next-row' or `newline', depending on context.
20568 See the individual commands for more information."
20569 (interactive)
20570 (let (org-ts-what)
20571 (cond
20572 ((or (bobp) (org-in-src-block-p))
20573 (if indent (newline-and-indent) (newline)))
20574 ((org-at-table-p)
20575 (org-table-justify-field-maybe)
20576 (call-interactively 'org-table-next-row))
20577 ;; when `newline-and-indent' is called within a list, make sure
20578 ;; text moved stays inside the item.
20579 ((and (org-in-item-p) indent)
20580 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20581 (progn
20582 (save-match-data (newline))
20583 (org-indent-line-to (length (match-string 0))))
20584 (let ((ind (org-get-indentation)))
20585 (newline)
20586 (if (org-looking-back org-list-end-re)
20587 (org-indent-line)
20588 (org-indent-line-to ind)))))
20589 ((and org-return-follows-link
20590 (org-at-timestamp-p t)
20591 (not (eq org-ts-what 'after)))
20592 (org-follow-timestamp-link))
20593 ((and org-return-follows-link
20594 (let ((tprop (get-text-property (point) 'face)))
20595 (or (eq tprop 'org-link)
20596 (and (listp tprop) (memq 'org-link tprop)))))
20597 (call-interactively 'org-open-at-point))
20598 ((and (org-at-heading-p)
20599 (looking-at
20600 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20601 (org-show-entry)
20602 (end-of-line 1)
20603 (newline))
20604 (t (if indent (newline-and-indent) (newline))))))
20606 (defun org-return-indent ()
20607 "Goto next table row or insert a newline and indent.
20608 Calls `org-table-next-row' or `newline-and-indent', depending on
20609 context. See the individual commands for more information."
20610 (interactive)
20611 (org-return t))
20613 (defun org-ctrl-c-star ()
20614 "Compute table, or change heading status of lines.
20615 Calls `org-table-recalculate' or `org-toggle-heading',
20616 depending on context."
20617 (interactive)
20618 (cond
20619 ((org-at-table-p)
20620 (call-interactively 'org-table-recalculate))
20622 ;; Convert all lines in region to list items
20623 (call-interactively 'org-toggle-heading))))
20625 (defun org-ctrl-c-minus ()
20626 "Insert separator line in table or modify bullet status of line.
20627 Also turns a plain line or a region of lines into list items.
20628 Calls `org-table-insert-hline', `org-toggle-item', or
20629 `org-cycle-list-bullet', depending on context."
20630 (interactive)
20631 (cond
20632 ((org-at-table-p)
20633 (call-interactively 'org-table-insert-hline))
20634 ((org-region-active-p)
20635 (call-interactively 'org-toggle-item))
20636 ((org-in-item-p)
20637 (call-interactively 'org-cycle-list-bullet))
20639 (call-interactively 'org-toggle-item))))
20641 (defun org-toggle-item (arg)
20642 "Convert headings or normal lines to items, items to normal lines.
20643 If there is no active region, only the current line is considered.
20645 If the first non blank line in the region is a headline, convert
20646 all headlines to items, shifting text accordingly.
20648 If it is an item, convert all items to normal lines.
20650 If it is normal text, change region into a list of items.
20651 With a prefix argument ARG, change the region in a single item."
20652 (interactive "P")
20653 (let ((shift-text
20654 (function
20655 ;; Shift text in current section to IND, from point to END.
20656 ;; The function leaves point to END line.
20657 (lambda (ind end)
20658 (let ((min-i 1000) (end (copy-marker end)))
20659 ;; First determine the minimum indentation (MIN-I) of
20660 ;; the text.
20661 (save-excursion
20662 (catch 'exit
20663 (while (< (point) end)
20664 (let ((i (org-get-indentation)))
20665 (cond
20666 ;; Skip blank lines and inline tasks.
20667 ((looking-at "^[ \t]*$"))
20668 ((looking-at org-outline-regexp-bol))
20669 ;; We can't find less than 0 indentation.
20670 ((zerop i) (throw 'exit (setq min-i 0)))
20671 ((< i min-i) (setq min-i i))))
20672 (forward-line))))
20673 ;; Then indent each line so that a line indented to
20674 ;; MIN-I becomes indented to IND. Ignore blank lines
20675 ;; and inline tasks in the process.
20676 (let ((delta (- ind min-i)))
20677 (while (< (point) end)
20678 (unless (or (looking-at "^[ \t]*$")
20679 (looking-at org-outline-regexp-bol))
20680 (org-indent-line-to (+ (org-get-indentation) delta)))
20681 (forward-line)))))))
20682 (skip-blanks
20683 (function
20684 ;; Return beginning of first non-blank line, starting from
20685 ;; line at POS.
20686 (lambda (pos)
20687 (save-excursion
20688 (goto-char pos)
20689 (skip-chars-forward " \r\t\n")
20690 (point-at-bol)))))
20691 beg end)
20692 ;; Determine boundaries of changes.
20693 (if (org-region-active-p)
20694 (setq beg (funcall skip-blanks (region-beginning))
20695 end (copy-marker (region-end)))
20696 (setq beg (funcall skip-blanks (point-at-bol))
20697 end (copy-marker (point-at-eol))))
20698 ;; Depending on the starting line, choose an action on the text
20699 ;; between BEG and END.
20700 (org-with-limited-levels
20701 (save-excursion
20702 (goto-char beg)
20703 (cond
20704 ;; Case 1. Start at an item: de-itemize. Note that it only
20705 ;; happens when a region is active: `org-ctrl-c-minus'
20706 ;; would call `org-cycle-list-bullet' otherwise.
20707 ((org-at-item-p)
20708 (while (< (point) end)
20709 (when (org-at-item-p)
20710 (skip-chars-forward " \t")
20711 (delete-region (point) (match-end 0)))
20712 (forward-line)))
20713 ;; Case 2. Start at an heading: convert to items.
20714 ((org-at-heading-p)
20715 (let* ((bul (org-list-bullet-string "-"))
20716 (bul-len (length bul))
20717 (done (org-entry-is-done-p))
20718 (todo (org-entry-is-todo-p))
20719 ;; Indentation of the first heading. It should be
20720 ;; relative to the indentation of its parent, if any.
20721 (start-ind (save-excursion
20722 (cond
20723 ((not org-adapt-indentation) 0)
20724 ((not (outline-previous-heading)) 0)
20725 (t (length (match-string 0))))))
20726 ;; Level of first heading. Further headings will be
20727 ;; compared to it to determine hierarchy in the list.
20728 (ref-level (org-reduced-level (org-outline-level))))
20729 (when (or done todo) (org-todo ""))
20730 (while (< (point) end)
20731 (let* ((level (org-reduced-level (org-outline-level)))
20732 (delta (max 0 (- level ref-level))))
20733 ;; If current headline is less indented than the first
20734 ;; one, set it as reference, in order to preserve
20735 ;; subtrees.
20736 (when (< level ref-level) (setq ref-level level))
20737 (replace-match bul t t)
20738 (org-indent-line-to (+ start-ind (* delta bul-len)))
20739 (when (or done todo)
20740 (let* ((struct (org-list-struct))
20741 (old (copy-tree struct)))
20742 (org-list-set-checkbox (line-beginning-position)
20743 struct
20744 (if done "[X]" "[ ]"))
20745 (org-list-write-struct struct
20746 (org-list-parents-alist struct)
20747 old)))
20748 ;; Ensure all text down to END (or SECTION-END) belongs
20749 ;; to the newly created item.
20750 (let ((section-end (save-excursion
20751 (or (outline-next-heading) (point)))))
20752 (forward-line)
20753 (funcall shift-text
20754 (+ start-ind (* (1+ delta) bul-len))
20755 (min end section-end)))))))
20756 ;; Case 3. Normal line with ARG: make the first line of region
20757 ;; an item, and shift indentation of others lines to
20758 ;; set them as item's body.
20759 (arg (let* ((bul (org-list-bullet-string "-"))
20760 (bul-len (length bul))
20761 (ref-ind (org-get-indentation)))
20762 (skip-chars-forward " \t")
20763 (insert bul)
20764 (forward-line)
20765 (while (< (point) end)
20766 ;; Ensure that lines less indented than first one
20767 ;; still get included in item body.
20768 (funcall shift-text
20769 (+ ref-ind bul-len)
20770 (min end (save-excursion (or (outline-next-heading)
20771 (point)))))
20772 (forward-line))))
20773 ;; Case 4. Normal line without ARG: turn each non-item line
20774 ;; into an item.
20776 (while (< (point) end)
20777 (unless (or (org-at-heading-p) (org-at-item-p))
20778 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20779 (replace-match
20780 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20781 (forward-line))))))))
20783 (defun org-toggle-heading (&optional nstars)
20784 "Convert headings to normal text, or items or text to headings.
20785 If there is no active region, only convert the current line.
20787 With a \\[universal-argument] prefix, convert the whole list at
20788 point into heading.
20790 In a region:
20792 - If the first non blank line is a headline, remove the stars
20793 from all headlines in the region.
20795 - If it is a normal line, turn each and every normal line (i.e.,
20796 not an heading or an item) in the region into headings. If you
20797 want to convert only the first line of this region, use one
20798 universal prefix argument.
20800 - If it is a plain list item, turn all plain list items into headings.
20802 When converting a line into a heading, the number of stars is chosen
20803 such that the lines become children of the current entry. However,
20804 when a numeric prefix argument is given, its value determines the
20805 number of stars to add."
20806 (interactive "P")
20807 (let ((skip-blanks
20808 (function
20809 ;; Return beginning of first non-blank line, starting from
20810 ;; line at POS.
20811 (lambda (pos)
20812 (save-excursion
20813 (goto-char pos)
20814 (while (org-at-comment-p) (forward-line))
20815 (skip-chars-forward " \r\t\n")
20816 (point-at-bol)))))
20817 beg end toggled)
20818 ;; Determine boundaries of changes. If a universal prefix has
20819 ;; been given, put the list in a region. If region ends at a bol,
20820 ;; do not consider the last line to be in the region.
20822 (when (and current-prefix-arg (org-at-item-p))
20823 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20824 (org-mark-element))
20826 (if (org-region-active-p)
20827 (setq beg (funcall skip-blanks (region-beginning))
20828 end (copy-marker (save-excursion
20829 (goto-char (region-end))
20830 (if (bolp) (point) (point-at-eol)))))
20831 (setq beg (funcall skip-blanks (point-at-bol))
20832 end (copy-marker (point-at-eol))))
20833 ;; Ensure inline tasks don't count as headings.
20834 (org-with-limited-levels
20835 (save-excursion
20836 (goto-char beg)
20837 (cond
20838 ;; Case 1. Started at an heading: de-star headings.
20839 ((org-at-heading-p)
20840 (while (< (point) end)
20841 (when (org-at-heading-p t)
20842 (looking-at org-outline-regexp) (replace-match "")
20843 (setq toggled t))
20844 (forward-line)))
20845 ;; Case 2. Started at an item: change items into headlines.
20846 ;; One star will be added by `org-list-to-subtree'.
20847 ((org-at-item-p)
20848 (let* ((stars (make-string
20849 ;; subtract the star that will be added again by
20850 ;; `org-list-to-subtree'
20851 (if (numberp nstars) (1- nstars)
20852 (or (org-current-level) 0))
20853 ?*))
20854 (add-stars
20855 (cond (nstars "") ; stars from prefix only
20856 ((equal stars "") "") ; before first heading
20857 (org-odd-levels-only "*") ; inside heading, odd
20858 (t "")))) ; inside heading, oddeven
20859 (while (< (point) end)
20860 (when (org-at-item-p)
20861 ;; Pay attention to cases when region ends before list.
20862 (let* ((struct (org-list-struct))
20863 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20864 (save-restriction
20865 (narrow-to-region (point) list-end)
20866 (insert
20867 (org-list-to-subtree
20868 (org-list-parse-list t)
20869 '(:istart (concat stars add-stars (funcall get-stars depth))
20870 :icount (concat stars add-stars (funcall get-stars depth)))))))
20871 (setq toggled t))
20872 (forward-line))))
20873 ;; Case 3. Started at normal text: make every line an heading,
20874 ;; skipping headlines and items.
20875 (t (let* ((stars
20876 (make-string
20877 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20878 (add-stars
20879 (cond (nstars "") ; stars from prefix only
20880 ((equal stars "") "*") ; before first heading
20881 (org-odd-levels-only "**") ; inside heading, odd
20882 (t "*"))) ; inside heading, oddeven
20883 (rpl (concat stars add-stars " "))
20884 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20885 (while (< (point) (if (equal nstars '(4)) lend end))
20886 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20887 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20888 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20889 (forward-line)))))))
20890 (unless toggled (message "Cannot toggle heading from here"))))
20892 (defun org-meta-return (&optional arg)
20893 "Insert a new heading or wrap a region in a table.
20894 Calls `org-insert-heading' or `org-table-wrap-region', depending
20895 on context. See the individual commands for more information."
20896 (interactive "P")
20897 (org-check-before-invisible-edit 'insert)
20898 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20899 (let* ((element (org-element-at-point))
20900 (type (org-element-type element)))
20901 (when (eq type 'table-row)
20902 (setq element (org-element-property :parent element))
20903 (setq type 'table))
20904 (if (and (eq type 'table)
20905 (eq (org-element-property :type element) 'org)
20906 (>= (point) (org-element-property :contents-begin element))
20907 (< (point) (org-element-property :contents-end element)))
20908 (call-interactively 'org-table-wrap-region)
20909 (call-interactively 'org-insert-heading)))))
20911 ;;; Menu entries
20913 (defsubst org-in-subtree-not-table-p ()
20914 "Are we in a subtree and not in a table?"
20915 (and (not (org-before-first-heading-p))
20916 (not (org-at-table-p))))
20918 ;; Define the Org-mode menus
20919 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20920 '("Tbl"
20921 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20922 ["Next Field" org-cycle (org-at-table-p)]
20923 ["Previous Field" org-shifttab (org-at-table-p)]
20924 ["Next Row" org-return (org-at-table-p)]
20925 "--"
20926 ["Blank Field" org-table-blank-field (org-at-table-p)]
20927 ["Edit Field" org-table-edit-field (org-at-table-p)]
20928 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20929 "--"
20930 ("Column"
20931 ["Move Column Left" org-metaleft (org-at-table-p)]
20932 ["Move Column Right" org-metaright (org-at-table-p)]
20933 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20934 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20935 ("Row"
20936 ["Move Row Up" org-metaup (org-at-table-p)]
20937 ["Move Row Down" org-metadown (org-at-table-p)]
20938 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20939 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20940 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20941 "--"
20942 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20943 ("Rectangle"
20944 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20945 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20946 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20947 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20948 "--"
20949 ("Calculate"
20950 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20951 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20952 ["Edit Formulas" org-edit-special (org-at-table-p)]
20953 "--"
20954 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20955 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20956 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20957 "--"
20958 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20959 "--"
20960 ["Sum Column/Rectangle" org-table-sum
20961 (or (org-at-table-p) (org-region-active-p))]
20962 ["Which Column?" org-table-current-column (org-at-table-p)])
20963 ["Debug Formulas"
20964 org-table-toggle-formula-debugger
20965 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20966 ["Show Col/Row Numbers"
20967 org-table-toggle-coordinate-overlays
20968 :style toggle
20969 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20970 "--"
20971 ["Create" org-table-create (and (not (org-at-table-p))
20972 org-enable-table-editor)]
20973 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20974 ["Import from File" org-table-import (not (org-at-table-p))]
20975 ["Export to File" org-table-export (org-at-table-p)]
20976 "--"
20977 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20979 (easy-menu-define org-org-menu org-mode-map "Org menu"
20980 '("Org"
20981 ("Show/Hide"
20982 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20983 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20984 ["Sparse Tree..." org-sparse-tree t]
20985 ["Reveal Context" org-reveal t]
20986 ["Show All" show-all t]
20987 "--"
20988 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20989 "--"
20990 ["New Heading" org-insert-heading t]
20991 ("Navigate Headings"
20992 ["Up" outline-up-heading t]
20993 ["Next" outline-next-visible-heading t]
20994 ["Previous" outline-previous-visible-heading t]
20995 ["Next Same Level" outline-forward-same-level t]
20996 ["Previous Same Level" outline-backward-same-level t]
20997 "--"
20998 ["Jump" org-goto t])
20999 ("Edit Structure"
21000 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21001 "--"
21002 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
21003 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
21004 "--"
21005 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21006 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21007 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21008 "--"
21009 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21010 "--"
21011 ["Copy visible text" org-copy-visible t]
21012 "--"
21013 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21014 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21015 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21016 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21017 "--"
21018 ["Sort Region/Children" org-sort t]
21019 "--"
21020 ["Convert to odd levels" org-convert-to-odd-levels t]
21021 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21022 ("Editing"
21023 ["Emphasis..." org-emphasize t]
21024 ["Edit Source Example" org-edit-special t]
21025 "--"
21026 ["Footnote new/jump" org-footnote-action t]
21027 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21028 ("Archive"
21029 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21030 "--"
21031 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21032 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21033 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21035 "--"
21036 ("Hyperlinks"
21037 ["Store Link (Global)" org-store-link t]
21038 ["Find existing link to here" org-occur-link-in-agenda-files t]
21039 ["Insert Link" org-insert-link t]
21040 ["Follow Link" org-open-at-point t]
21041 "--"
21042 ["Next link" org-next-link t]
21043 ["Previous link" org-previous-link t]
21044 "--"
21045 ["Descriptive Links"
21046 org-toggle-link-display
21047 :style radio
21048 :selected org-descriptive-links
21050 ["Literal Links"
21051 org-toggle-link-display
21052 :style radio
21053 :selected (not org-descriptive-links)])
21054 "--"
21055 ("TODO Lists"
21056 ["TODO/DONE/-" org-todo t]
21057 ("Select keyword"
21058 ["Next keyword" org-shiftright (org-at-heading-p)]
21059 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21060 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21061 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21062 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21063 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21064 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21065 "--"
21066 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21067 :selected org-enforce-todo-dependencies :style toggle :active t]
21068 "Settings for tree at point"
21069 ["Do Children sequentially" org-toggle-ordered-property :style radio
21070 :selected (org-entry-get nil "ORDERED")
21071 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21072 ["Do Children parallel" org-toggle-ordered-property :style radio
21073 :selected (not (org-entry-get nil "ORDERED"))
21074 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21075 "--"
21076 ["Set Priority" org-priority t]
21077 ["Priority Up" org-shiftup t]
21078 ["Priority Down" org-shiftdown t]
21079 "--"
21080 ["Get news from all feeds" org-feed-update-all t]
21081 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21082 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21083 ("TAGS and Properties"
21084 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21085 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21086 "--"
21087 ["Set property" org-set-property (not (org-before-first-heading-p))]
21088 ["Column view of properties" org-columns t]
21089 ["Insert Column View DBlock" org-insert-columns-dblock t])
21090 ("Dates and Scheduling"
21091 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21092 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21093 ("Change Date"
21094 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21095 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21096 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21097 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21098 ["Compute Time Range" org-evaluate-time-range t]
21099 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21100 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21101 "--"
21102 ["Custom time format" org-toggle-time-stamp-overlays
21103 :style radio :selected org-display-custom-times]
21104 "--"
21105 ["Goto Calendar" org-goto-calendar t]
21106 ["Date from Calendar" org-date-from-calendar t]
21107 "--"
21108 ["Start/Restart Timer" org-timer-start t]
21109 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21110 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21111 ["Insert Timer String" org-timer t]
21112 ["Insert Timer Item" org-timer-item t])
21113 ("Logging work"
21114 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21115 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21116 ["Clock out" org-clock-out t]
21117 ["Clock cancel" org-clock-cancel t]
21118 "--"
21119 ["Mark as default task" org-clock-mark-default-task t]
21120 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21121 ["Goto running clock" org-clock-goto t]
21122 "--"
21123 ["Display times" org-clock-display t]
21124 ["Create clock table" org-clock-report t]
21125 "--"
21126 ["Record DONE time"
21127 (progn (setq org-log-done (not org-log-done))
21128 (message "Switching to %s will %s record a timestamp"
21129 (car org-done-keywords)
21130 (if org-log-done "automatically" "not")))
21131 :style toggle :selected org-log-done])
21132 "--"
21133 ["Agenda Command..." org-agenda t]
21134 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21135 ("File List for Agenda")
21136 ("Special views current file"
21137 ["TODO Tree" org-show-todo-tree t]
21138 ["Check Deadlines" org-check-deadlines t]
21139 ["Timeline" org-timeline t]
21140 ["Tags/Property tree" org-match-sparse-tree t])
21141 "--"
21142 ["Export/Publish..." org-export-dispatch t]
21143 ("LaTeX"
21144 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21145 :selected org-cdlatex-mode]
21146 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21147 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21148 ["Modify math symbol" org-cdlatex-math-modify
21149 (org-inside-LaTeX-fragment-p)]
21150 ["Insert citation" org-reftex-citation t]
21151 "--"
21152 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21153 "--"
21154 ("MobileOrg"
21155 ["Push Files and Views" org-mobile-push t]
21156 ["Get Captured and Flagged" org-mobile-pull t]
21157 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21158 "--"
21159 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21160 "--"
21161 ("Documentation"
21162 ["Show Version" org-version t]
21163 ["Info Documentation" org-info t])
21164 ("Customize"
21165 ["Browse Org Group" org-customize t]
21166 "--"
21167 ["Expand This Menu" org-create-customize-menu
21168 (fboundp 'customize-menu-create)])
21169 ["Send bug report" org-submit-bug-report t]
21170 "--"
21171 ("Refresh/Reload"
21172 ["Refresh setup current buffer" org-mode-restart t]
21173 ["Reload Org (after update)" org-reload t]
21174 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21177 (defun org-info (&optional node)
21178 "Read documentation for Org-mode in the info system.
21179 With optional NODE, go directly to that node."
21180 (interactive)
21181 (info (format "(org)%s" (or node ""))))
21183 ;;;###autoload
21184 (defun org-submit-bug-report ()
21185 "Submit a bug report on Org-mode via mail.
21187 Don't hesitate to report any problems or inaccurate documentation.
21189 If you don't have setup sending mail from (X)Emacs, please copy the
21190 output buffer into your mail program, as it gives us important
21191 information about your Org-mode version and configuration."
21192 (interactive)
21193 (require 'reporter)
21194 (org-load-modules-maybe)
21195 (org-require-autoloaded-modules)
21196 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21197 (reporter-submit-bug-report
21198 "emacs-orgmode@gnu.org"
21199 (org-version nil 'full)
21200 (let (list)
21201 (save-window-excursion
21202 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21203 (delete-other-windows)
21204 (erase-buffer)
21205 (insert "You are about to submit a bug report to the Org-mode mailing list.
21207 We would like to add your full Org-mode and Outline configuration to the
21208 bug report. This greatly simplifies the work of the maintainer and
21209 other experts on the mailing list.
21211 HOWEVER, some variables you have customized may contain private
21212 information. The names of customers, colleagues, or friends, might
21213 appear in the form of file names, tags, todo states, or search strings.
21214 If you answer yes to the prompt, you might want to check and remove
21215 such private information before sending the email.")
21216 (add-text-properties (point-min) (point-max) '(face org-warning))
21217 (when (yes-or-no-p "Include your Org-mode configuration ")
21218 (mapatoms
21219 (lambda (v)
21220 (and (boundp v)
21221 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21222 (or (and (symbol-value v)
21223 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21224 (and
21225 (get v 'custom-type) (get v 'standard-value)
21226 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21227 (push v list)))))
21228 (kill-buffer (get-buffer "*Warn about privacy*"))
21229 list))
21230 nil nil
21231 "Remember to cover the basics, that is, what you expected to happen and
21232 what in fact did happen. You don't know how to make a good report? See
21234 http://orgmode.org/manual/Feedback.html#Feedback
21236 Your bug report will be posted to the Org-mode mailing list.
21237 ------------------------------------------------------------------------")
21238 (save-excursion
21239 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21240 (replace-match "\\1Bug: \\3 [\\2]")))))
21243 (defun org-install-agenda-files-menu ()
21244 (let ((bl (buffer-list)))
21245 (save-excursion
21246 (while bl
21247 (set-buffer (pop bl))
21248 (if (derived-mode-p 'org-mode) (setq bl nil)))
21249 (when (derived-mode-p 'org-mode)
21250 (easy-menu-change
21251 '("Org") "File List for Agenda"
21252 (append
21253 (list
21254 ["Edit File List" (org-edit-agenda-file-list) t]
21255 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21256 ["Remove Current File from List" org-remove-file t]
21257 ["Cycle through agenda files" org-cycle-agenda-files t]
21258 ["Occur in all agenda files" org-occur-in-agenda-files t]
21259 "--")
21260 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21262 ;;;; Documentation
21264 (defun org-require-autoloaded-modules ()
21265 (interactive)
21266 (mapc 'require
21267 '(org-agenda org-archive org-attach org-clock org-colview org-id
21268 org-table org-timer)))
21270 ;;;###autoload
21271 (defun org-reload (&optional uncompiled)
21272 "Reload all org lisp files.
21273 With prefix arg UNCOMPILED, load the uncompiled versions."
21274 (interactive "P")
21275 (require 'loadhist)
21276 (let* ((org-dir (org-find-library-dir "org"))
21277 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21278 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21279 (remove-re (mapconcat 'identity
21280 (mapcar (lambda (f) (concat "^" f "$"))
21281 (list (if (featurep 'xemacs)
21282 "org-colview"
21283 "org-colview-xemacs")
21284 "org" "org-loaddefs" "org-version"))
21285 "\\|"))
21286 (feats (delete-dups
21287 (mapcar 'file-name-sans-extension
21288 (mapcar 'file-name-nondirectory
21289 (delq nil
21290 (mapcar 'feature-file
21291 features))))))
21292 (lfeat (append
21293 (sort
21294 (setq feats
21295 (delq nil (mapcar
21296 (lambda (f)
21297 (if (and (string-match feature-re f)
21298 (not (string-match remove-re f)))
21299 f nil))
21300 feats)))
21301 'string-lessp)
21302 (list "org-version" "org")))
21303 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21304 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21305 load-uncore load-misses)
21306 (setq load-misses
21307 (delq 't
21308 (mapcar (lambda (f)
21309 (or (org-load-noerror-mustsuffix (concat org-dir f))
21310 (and (string= org-dir contrib-dir)
21311 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21312 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21313 (add-to-list 'load-uncore f 'append)
21316 lfeat)))
21317 (if load-uncore
21318 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21319 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21320 (if load-misses
21321 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21322 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21323 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21325 ;;;###autoload
21326 (defun org-customize ()
21327 "Call the customize function with org as argument."
21328 (interactive)
21329 (org-load-modules-maybe)
21330 (org-require-autoloaded-modules)
21331 (customize-browse 'org))
21333 (defun org-create-customize-menu ()
21334 "Create a full customization menu for Org-mode, insert it into the menu."
21335 (interactive)
21336 (org-load-modules-maybe)
21337 (org-require-autoloaded-modules)
21338 (if (fboundp 'customize-menu-create)
21339 (progn
21340 (easy-menu-change
21341 '("Org") "Customize"
21342 `(["Browse Org group" org-customize t]
21343 "--"
21344 ,(customize-menu-create 'org)
21345 ["Set" Custom-set t]
21346 ["Save" Custom-save t]
21347 ["Reset to Current" Custom-reset-current t]
21348 ["Reset to Saved" Custom-reset-saved t]
21349 ["Reset to Standard Settings" Custom-reset-standard t]))
21350 (message "\"Org\"-menu now contains full customization menu"))
21351 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21353 ;;;; Miscellaneous stuff
21355 ;;; Generally useful functions
21357 (defun org-get-at-bol (property)
21358 "Get text property PROPERTY at beginning of line."
21359 (get-text-property (point-at-bol) property))
21361 (defun org-find-text-property-in-string (prop s)
21362 "Return the first non-nil value of property PROP in string S."
21363 (or (get-text-property 0 prop s)
21364 (get-text-property (or (next-single-property-change 0 prop s) 0)
21365 prop s)))
21367 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21368 "Display the given MESSAGE as a warning."
21369 (if (fboundp 'display-warning)
21370 (display-warning 'org message
21371 (if (featurep 'xemacs) 'warning :warning))
21372 (let ((buf (get-buffer-create "*Org warnings*")))
21373 (with-current-buffer buf
21374 (goto-char (point-max))
21375 (insert "Warning (Org): " message)
21376 (unless (bolp)
21377 (newline)))
21378 (display-buffer buf)
21379 (sit-for 0))))
21381 (defun org-eval (form)
21382 "Eval FORM and return result."
21383 (condition-case error
21384 (eval form)
21385 (error (format "%%![Error: %s]" error))))
21387 (defun org-in-clocktable-p ()
21388 "Check if the cursor is in a clocktable."
21389 (let ((pos (point)) start)
21390 (save-excursion
21391 (end-of-line 1)
21392 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21393 (setq start (match-beginning 0))
21394 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21395 (>= (match-end 0) pos)
21396 start))))
21398 (defun org-in-commented-line ()
21399 "Is point in a line starting with `#'?"
21400 (equal (char-after (point-at-bol)) ?#))
21402 (defun org-in-indented-comment-line ()
21403 "Is point in a line starting with `#' after some white space?"
21404 (save-excursion
21405 (save-match-data
21406 (goto-char (point-at-bol))
21407 (looking-at "[ \t]*#"))))
21409 (defun org-in-verbatim-emphasis ()
21410 (save-match-data
21411 (and (org-in-regexp org-emph-re 2)
21412 (>= (point) (match-beginning 3))
21413 (<= (point) (match-end 4))
21414 (member (match-string 3) '("=" "~")))))
21416 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21417 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21418 (if (and marker (marker-buffer marker)
21419 (buffer-live-p (marker-buffer marker)))
21420 (progn
21421 (org-pop-to-buffer-same-window (marker-buffer marker))
21422 (if (or (> marker (point-max)) (< marker (point-min)))
21423 (widen))
21424 (goto-char marker)
21425 (org-show-context 'org-goto))
21426 (if bookmark
21427 (bookmark-jump bookmark)
21428 (error "Cannot find location"))))
21430 (defun org-quote-csv-field (s)
21431 "Quote field for inclusion in CSV material."
21432 (if (string-match "[\",]" s)
21433 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21436 (defun org-force-self-insert (N)
21437 "Needed to enforce self-insert under remapping."
21438 (interactive "p")
21439 (self-insert-command N))
21441 (defun org-string-width (s)
21442 "Compute width of string, ignoring invisible characters.
21443 This ignores character with invisibility property `org-link', and also
21444 characters with property `org-cwidth', because these will become invisible
21445 upon the next fontification round."
21446 (let (b l)
21447 (when (or (eq t buffer-invisibility-spec)
21448 (assq 'org-link buffer-invisibility-spec))
21449 (while (setq b (text-property-any 0 (length s)
21450 'invisible 'org-link s))
21451 (setq s (concat (substring s 0 b)
21452 (substring s (or (next-single-property-change
21453 b 'invisible s) (length s)))))))
21454 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21455 (setq s (concat (substring s 0 b)
21456 (substring s (or (next-single-property-change
21457 b 'org-cwidth s) (length s))))))
21458 (setq l (string-width s) b -1)
21459 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21460 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21463 (defun org-shorten-string (s maxlength)
21464 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21465 If the string is shorter or has length MAXLENGTH, just return the
21466 original string. If it is longer, the functions finds a space in the
21467 string, breaks this string off at that locations and adds three dots
21468 as ellipsis. Including the ellipsis, the string will not be longer
21469 than MAXLENGTH. If finding a good breaking point in the string does
21470 not work, the string is just chopped off in the middle of a word
21471 if necessary."
21472 (if (<= (length s) maxlength)
21474 (let* ((n (max (- maxlength 4) 1))
21475 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21476 (if (string-match re s)
21477 (concat (match-string 1 s) "...")
21478 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21480 (defun org-get-indentation (&optional line)
21481 "Get the indentation of the current line, interpreting tabs.
21482 When LINE is given, assume it represents a line and compute its indentation."
21483 (if line
21484 (if (string-match "^ *" (org-remove-tabs line))
21485 (match-end 0))
21486 (save-excursion
21487 (beginning-of-line 1)
21488 (skip-chars-forward " \t")
21489 (current-column))))
21491 (defun org-get-string-indentation (s)
21492 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21493 (let ((n -1) (i 0) (w tab-width) c)
21494 (catch 'exit
21495 (while (< (setq n (1+ n)) (length s))
21496 (setq c (aref s n))
21497 (cond ((= c ?\ ) (setq i (1+ i)))
21498 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21499 (t (throw 'exit t)))))
21502 (defun org-remove-tabs (s &optional width)
21503 "Replace tabulators in S with spaces.
21504 Assumes that s is a single line, starting in column 0."
21505 (setq width (or width tab-width))
21506 (while (string-match "\t" s)
21507 (setq s (replace-match
21508 (make-string
21509 (- (* width (/ (+ (match-beginning 0) width) width))
21510 (match-beginning 0)) ?\ )
21511 t t s)))
21514 (defun org-fix-indentation (line ind)
21515 "Fix indentation in LINE.
21516 IND is a cons cell with target and minimum indentation.
21517 If the current indentation in LINE is smaller than the minimum,
21518 leave it alone. If it is larger than ind, set it to the target."
21519 (let* ((l (org-remove-tabs line))
21520 (i (org-get-indentation l))
21521 (i1 (car ind)) (i2 (cdr ind)))
21522 (if (>= i i2) (setq l (substring line i2)))
21523 (if (> i1 0)
21524 (concat (make-string i1 ?\ ) l)
21525 l)))
21527 (defun org-remove-indentation (code &optional n)
21528 "Remove the maximum common indentation from the lines in CODE.
21529 N may optionally be the number of spaces to remove."
21530 (with-temp-buffer
21531 (insert code)
21532 (org-do-remove-indentation n)
21533 (buffer-string)))
21535 (defun org-do-remove-indentation (&optional n)
21536 "Remove the maximum common indentation from the buffer."
21537 (untabify (point-min) (point-max))
21538 (let ((min 10000) re)
21539 (if n
21540 (setq min n)
21541 (goto-char (point-min))
21542 (while (re-search-forward "^ *[^ \n]" nil t)
21543 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21544 (unless (or (= min 0) (= min 10000))
21545 (setq re (format "^ \\{%d\\}" min))
21546 (goto-char (point-min))
21547 (while (re-search-forward re nil t)
21548 (replace-match "")
21549 (end-of-line 1))
21550 min)))
21552 (defun org-fill-template (template alist)
21553 "Find each %key of ALIST in TEMPLATE and replace it."
21554 (let ((case-fold-search nil)
21555 entry key value)
21556 (setq alist (sort (copy-sequence alist)
21557 (lambda (a b) (< (length (car a)) (length (car b))))))
21558 (while (setq entry (pop alist))
21559 (setq template
21560 (replace-regexp-in-string
21561 (concat "%" (regexp-quote (car entry)))
21562 (or (cdr entry) "") template t t)))
21563 template))
21565 (defun org-base-buffer (buffer)
21566 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21567 (if (not buffer)
21568 buffer
21569 (or (buffer-base-buffer buffer)
21570 buffer)))
21572 (defun org-trim (s)
21573 "Remove whitespace at beginning and end of string."
21574 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21575 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21578 (defun org-wrap (string &optional width lines)
21579 "Wrap string to either a number of lines, or a width in characters.
21580 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21581 that costs. If there is a word longer than WIDTH, the text is actually
21582 wrapped to the length of that word.
21583 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21584 many lines, whatever width that takes.
21585 The return value is a list of lines, without newlines at the end."
21586 (let* ((words (org-split-string string "[ \t\n]+"))
21587 (maxword (apply 'max (mapcar 'org-string-width words)))
21588 w ll)
21589 (cond (width
21590 (org-do-wrap words (max maxword width)))
21591 (lines
21592 (setq w maxword)
21593 (setq ll (org-do-wrap words maxword))
21594 (if (<= (length ll) lines)
21596 (setq ll words)
21597 (while (> (length ll) lines)
21598 (setq w (1+ w))
21599 (setq ll (org-do-wrap words w)))
21600 ll))
21601 (t (error "Cannot wrap this")))))
21603 (defun org-do-wrap (words width)
21604 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21605 (let (lines line)
21606 (while words
21607 (setq line (pop words))
21608 (while (and words (< (+ (length line) (length (car words))) width))
21609 (setq line (concat line " " (pop words))))
21610 (setq lines (push line lines)))
21611 (nreverse lines)))
21613 (defun org-split-string (string &optional separators)
21614 "Splits STRING into substrings at SEPARATORS.
21615 No empty strings are returned if there are matches at the beginning
21616 and end of string."
21617 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21618 (start 0)
21619 notfirst
21620 (list nil))
21621 (while (and (string-match rexp string
21622 (if (and notfirst
21623 (= start (match-beginning 0))
21624 (< start (length string)))
21625 (1+ start) start))
21626 (< (match-beginning 0) (length string)))
21627 (setq notfirst t)
21628 (or (eq (match-beginning 0) 0)
21629 (and (eq (match-beginning 0) (match-end 0))
21630 (eq (match-beginning 0) start))
21631 (setq list
21632 (cons (substring string start (match-beginning 0))
21633 list)))
21634 (setq start (match-end 0)))
21635 (or (eq start (length string))
21636 (setq list
21637 (cons (substring string start)
21638 list)))
21639 (nreverse list)))
21641 (defun org-quote-vert (s)
21642 "Replace \"|\" with \"\\vert\"."
21643 (while (string-match "|" s)
21644 (setq s (replace-match "\\vert" t t s)))
21647 (defun org-uuidgen-p (s)
21648 "Is S an ID created by UUIDGEN?"
21649 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21651 (defun org-in-src-block-p (&optional inside)
21652 "Whether point is in a code source block.
21653 When INSIDE is non-nil, don't consider we are within a src block
21654 when point is at #+BEGIN_SRC or #+END_SRC."
21655 (let ((case-fold-search t) ov)
21656 (or (and (setq ov (overlays-at (point)))
21657 (memq 'org-block-background
21658 (overlay-properties (car ov))))
21659 (and (not inside)
21660 (save-match-data
21661 (save-excursion
21662 (beginning-of-line)
21663 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21665 (defun org-context ()
21666 "Return a list of contexts of the current cursor position.
21667 If several contexts apply, all are returned.
21668 Each context entry is a list with a symbol naming the context, and
21669 two positions indicating start and end of the context. Possible
21670 contexts are:
21672 :headline anywhere in a headline
21673 :headline-stars on the leading stars in a headline
21674 :todo-keyword on a TODO keyword (including DONE) in a headline
21675 :tags on the TAGS in a headline
21676 :priority on the priority cookie in a headline
21677 :item on the first line of a plain list item
21678 :item-bullet on the bullet/number of a plain list item
21679 :checkbox on the checkbox in a plain list item
21680 :table in an org-mode table
21681 :table-special on a special filed in a table
21682 :table-table in a table.el table
21683 :clocktable in a clocktable
21684 :src-block in a source block
21685 :link on a hyperlink
21686 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21687 :target on a <<target>>
21688 :radio-target on a <<<radio-target>>>
21689 :latex-fragment on a LaTeX fragment
21690 :latex-preview on a LaTeX fragment with overlaid preview image
21692 This function expects the position to be visible because it uses font-lock
21693 faces as a help to recognize the following contexts: :table-special, :link,
21694 and :keyword."
21695 (let* ((f (get-text-property (point) 'face))
21696 (faces (if (listp f) f (list f)))
21697 (case-fold-search t)
21698 (p (point)) clist o)
21699 ;; First the large context
21700 (cond
21701 ((org-at-heading-p t)
21702 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21703 (when (progn
21704 (beginning-of-line 1)
21705 (looking-at org-todo-line-tags-regexp))
21706 (push (org-point-in-group p 1 :headline-stars) clist)
21707 (push (org-point-in-group p 2 :todo-keyword) clist)
21708 (push (org-point-in-group p 4 :tags) clist))
21709 (goto-char p)
21710 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21711 (if (looking-at "\\[#[A-Z0-9]\\]")
21712 (push (org-point-in-group p 0 :priority) clist)))
21714 ((org-at-item-p)
21715 (push (org-point-in-group p 2 :item-bullet) clist)
21716 (push (list :item (point-at-bol)
21717 (save-excursion (org-end-of-item) (point)))
21718 clist)
21719 (and (org-at-item-checkbox-p)
21720 (push (org-point-in-group p 0 :checkbox) clist)))
21722 ((org-at-table-p)
21723 (push (list :table (org-table-begin) (org-table-end)) clist)
21724 (if (memq 'org-formula faces)
21725 (push (list :table-special
21726 (previous-single-property-change p 'face)
21727 (next-single-property-change p 'face)) clist)))
21728 ((org-at-table-p 'any)
21729 (push (list :table-table) clist)))
21730 (goto-char p)
21732 (let ((case-fold-search t))
21733 ;; New the "medium" contexts: clocktables, source blocks
21734 (cond ((org-in-clocktable-p)
21735 (push (list :clocktable
21736 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21737 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21738 (match-beginning 1))
21739 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21740 (match-end 0))) clist))
21741 ((org-in-src-block-p)
21742 (push (list :src-block
21743 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21744 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21745 (match-beginning 1))
21746 (and (search-forward "#+END_SRC" nil t)
21747 (match-beginning 0))) clist))))
21748 (goto-char p)
21750 ;; Now the small context
21751 (cond
21752 ((org-at-timestamp-p)
21753 (push (org-point-in-group p 0 :timestamp) clist))
21754 ((memq 'org-link faces)
21755 (push (list :link
21756 (previous-single-property-change p 'face)
21757 (next-single-property-change p 'face)) clist))
21758 ((memq 'org-special-keyword faces)
21759 (push (list :keyword
21760 (previous-single-property-change p 'face)
21761 (next-single-property-change p 'face)) clist))
21762 ((org-at-target-p)
21763 (push (org-point-in-group p 0 :target) clist)
21764 (goto-char (1- (match-beginning 0)))
21765 (if (looking-at org-radio-target-regexp)
21766 (push (org-point-in-group p 0 :radio-target) clist))
21767 (goto-char p))
21768 ((setq o (car (delq nil
21769 (mapcar
21770 (lambda (x)
21771 (if (memq x org-latex-fragment-image-overlays) x))
21772 (overlays-at (point))))))
21773 (push (list :latex-fragment
21774 (overlay-start o) (overlay-end o)) clist)
21775 (push (list :latex-preview
21776 (overlay-start o) (overlay-end o)) clist))
21777 ((org-inside-LaTeX-fragment-p)
21778 ;; FIXME: positions wrong.
21779 (push (list :latex-fragment (point) (point)) clist)))
21781 (setq clist (nreverse (delq nil clist)))
21782 clist))
21784 ;; FIXME: Compare with at-regexp-p Do we need both?
21785 (defun org-in-regexp (re &optional nlines visually)
21786 "Check if point is inside a match of regexp.
21787 Normally only the current line is checked, but you can include NLINES extra
21788 lines both before and after point into the search.
21789 If VISUALLY is set, require that the cursor is not after the match but
21790 really on, so that the block visually is on the match."
21791 (catch 'exit
21792 (let ((pos (point))
21793 (eol (point-at-eol (+ 1 (or nlines 0))))
21794 (inc (if visually 1 0)))
21795 (save-excursion
21796 (beginning-of-line (- 1 (or nlines 0)))
21797 (while (re-search-forward re eol t)
21798 (if (and (<= (match-beginning 0) pos)
21799 (>= (+ inc (match-end 0)) pos))
21800 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21802 (defun org-at-regexp-p (regexp)
21803 "Is point inside a match of REGEXP in the current line?"
21804 (catch 'exit
21805 (save-excursion
21806 (let ((pos (point)) (end (point-at-eol)))
21807 (beginning-of-line 1)
21808 (while (re-search-forward regexp end t)
21809 (if (and (<= (match-beginning 0) pos)
21810 (>= (match-end 0) pos))
21811 (throw 'exit t)))
21812 nil))))
21814 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21815 "Non-nil when point is between matches of START-RE and END-RE.
21817 Also return a non-nil value when point is on one of the matches.
21819 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21820 buffer positions. Default values are the positions of headlines
21821 surrounding the point.
21823 The functions returns a cons cell whose car (resp. cdr) is the
21824 position before START-RE (resp. after END-RE)."
21825 (save-match-data
21826 (let ((pos (point))
21827 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21828 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21829 beg end)
21830 (save-excursion
21831 ;; Point is on a block when on START-RE or if START-RE can be
21832 ;; found before it...
21833 (and (or (org-at-regexp-p start-re)
21834 (re-search-backward start-re limit-up t))
21835 (setq beg (match-beginning 0))
21836 ;; ... and END-RE after it...
21837 (goto-char (match-end 0))
21838 (re-search-forward end-re limit-down t)
21839 (> (setq end (match-end 0)) pos)
21840 ;; ... without another START-RE in-between.
21841 (goto-char (match-beginning 0))
21842 (not (re-search-backward start-re (1+ beg) t))
21843 ;; Return value.
21844 (cons beg end))))))
21846 (defun org-in-block-p (names)
21847 "Non-nil when point belongs to a block whose name belongs to NAMES.
21849 NAMES is a list of strings containing names of blocks.
21851 Return first block name matched, or nil. Beware that in case of
21852 nested blocks, the returned name may not belong to the closest
21853 block from point."
21854 (save-match-data
21855 (catch 'exit
21856 (let ((case-fold-search t)
21857 (lim-up (save-excursion (outline-previous-heading)))
21858 (lim-down (save-excursion (outline-next-heading))))
21859 (mapc (lambda (name)
21860 (let ((n (regexp-quote name)))
21861 (when (org-between-regexps-p
21862 (concat "^[ \t]*#\\+begin_" n)
21863 (concat "^[ \t]*#\\+end_" n)
21864 lim-up lim-down)
21865 (throw 'exit n))))
21866 names))
21867 nil)))
21869 (defun org-in-drawer-p ()
21870 "Non-nil if point is within a drawer.
21871 If point is within a drawer, return it, as parsed data."
21872 (let ((element (save-match-data (org-element-at-point))))
21873 (while (and element (not (memq (org-element-type element)
21874 '(drawer property-drawer))))
21875 (setq element (org-element-property :parent element)))
21876 element))
21878 (defun org-occur-in-agenda-files (regexp &optional nlines)
21879 "Call `multi-occur' with buffers for all agenda files."
21880 (interactive "sOrg-files matching: \np")
21881 (let* ((files (org-agenda-files))
21882 (tnames (mapcar 'file-truename files))
21883 (extra org-agenda-text-search-extra-files)
21885 (when (eq (car extra) 'agenda-archives)
21886 (setq extra (cdr extra))
21887 (setq files (org-add-archive-files files)))
21888 (while (setq f (pop extra))
21889 (unless (member (file-truename f) tnames)
21890 (add-to-list 'files f 'append)
21891 (add-to-list 'tnames (file-truename f) 'append)))
21892 (multi-occur
21893 (mapcar (lambda (x)
21894 (with-current-buffer
21895 (or (get-file-buffer x) (find-file-noselect x))
21896 (widen)
21897 (current-buffer)))
21898 files)
21899 regexp)))
21901 (if (boundp 'occur-mode-find-occurrence-hook)
21902 ;; Emacs 23
21903 (add-hook 'occur-mode-find-occurrence-hook
21904 (lambda ()
21905 (when (derived-mode-p 'org-mode)
21906 (org-reveal))))
21907 ;; Emacs 22
21908 (defadvice occur-mode-goto-occurrence
21909 (after org-occur-reveal activate)
21910 (and (derived-mode-p 'org-mode) (org-reveal)))
21911 (defadvice occur-mode-goto-occurrence-other-window
21912 (after org-occur-reveal activate)
21913 (and (derived-mode-p 'org-mode) (org-reveal)))
21914 (defadvice occur-mode-display-occurrence
21915 (after org-occur-reveal activate)
21916 (when (derived-mode-p 'org-mode)
21917 (let ((pos (occur-mode-find-occurrence)))
21918 (with-current-buffer (marker-buffer pos)
21919 (save-excursion
21920 (goto-char pos)
21921 (org-reveal)))))))
21923 (defun org-occur-link-in-agenda-files ()
21924 "Create a link and search for it in the agendas.
21925 The link is not stored in `org-stored-links', it is just created
21926 for the search purpose."
21927 (interactive)
21928 (let ((link (condition-case nil
21929 (org-store-link nil)
21930 (error "Unable to create a link to here"))))
21931 (org-occur-in-agenda-files (regexp-quote link))))
21933 (defun org-reverse-string (string)
21934 "Return the reverse of STRING."
21935 (apply 'string (reverse (string-to-list string))))
21937 (defun org-uniquify-alist (alist)
21938 "Merge elements of ALIST with the same key.
21940 For example, in this alist:
21942 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21943 => '((a 1 3) (b 2))
21945 merge (a 1) and (a 3) into (a 1 3).
21947 The function returns the new ALIST."
21948 (let (rtn)
21949 (mapc
21950 (lambda (e)
21951 (let (n)
21952 (if (not (assoc (car e) rtn))
21953 (push e rtn)
21954 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21955 (setq rtn (assq-delete-all (car e) rtn))
21956 (push n rtn))))
21957 alist)
21958 rtn))
21960 (defun org-delete-all (elts list)
21961 "Remove all elements in ELTS from LIST."
21962 (while elts
21963 (setq list (delete (pop elts) list)))
21964 list)
21966 (defun org-count (cl-item cl-seq)
21967 "Count the number of occurrences of ITEM in SEQ.
21968 Taken from `count' in cl-seq.el with all keyword arguments removed."
21969 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21970 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21971 (while (< cl-start cl-end)
21972 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21973 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21974 (setq cl-start (1+ cl-start)))
21975 cl-count))
21977 (defun org-remove-if (predicate seq)
21978 "Remove everything from SEQ that fulfills PREDICATE."
21979 (let (res e)
21980 (while seq
21981 (setq e (pop seq))
21982 (if (not (funcall predicate e)) (push e res)))
21983 (nreverse res)))
21985 (defun org-remove-if-not (predicate seq)
21986 "Remove everything from SEQ that does not fulfill PREDICATE."
21987 (let (res e)
21988 (while seq
21989 (setq e (pop seq))
21990 (if (funcall predicate e) (push e res)))
21991 (nreverse res)))
21993 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21994 "Reduce two-argument FUNCTION across SEQ.
21995 Taken from `reduce' in cl-seq.el with all keyword arguments but
21996 \":initial-value\" removed."
21997 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21998 (cadr (memq :initial-value cl-keys)))
21999 (cl-seq (pop cl-seq))
22000 (t (funcall cl-func)))))
22001 (while cl-seq
22002 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22003 cl-accum))
22005 (defun org-every (pred seq)
22006 "Return true if PREDICATE is true of every element of SEQ.
22007 Adapted from `every' in cl.el."
22008 (catch 'org-every
22009 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22012 (defun org-some (pred seq)
22013 "Return true if PREDICATE is true of any element of SEQ.
22014 Adapted from `some' in cl.el."
22015 (catch 'org-some
22016 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22017 nil))
22019 (defun org-back-over-empty-lines ()
22020 "Move backwards over whitespace, to the beginning of the first empty line.
22021 Returns the number of empty lines passed."
22022 (let ((pos (point)))
22023 (if (cdr (assoc 'heading org-blank-before-new-entry))
22024 (skip-chars-backward " \t\n\r")
22025 (unless (eobp)
22026 (forward-line -1)))
22027 (beginning-of-line 2)
22028 (goto-char (min (point) pos))
22029 (count-lines (point) pos)))
22031 (defun org-skip-whitespace ()
22032 (skip-chars-forward " \t\n\r"))
22034 (defun org-point-in-group (point group &optional context)
22035 "Check if POINT is in match-group GROUP.
22036 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22037 match. If the match group does not exist or point is not inside it,
22038 return nil."
22039 (and (match-beginning group)
22040 (>= point (match-beginning group))
22041 (<= point (match-end group))
22042 (if context
22043 (list context (match-beginning group) (match-end group))
22044 t)))
22046 (defun org-switch-to-buffer-other-window (&rest args)
22047 "Switch to buffer in a second window on the current frame.
22048 In particular, do not allow pop-up frames.
22049 Returns the newly created buffer."
22050 (org-no-popups
22051 (apply 'switch-to-buffer-other-window args)))
22053 (defun org-combine-plists (&rest plists)
22054 "Create a single property list from all plists in PLISTS.
22055 The process starts by copying the first list, and then setting properties
22056 from the other lists. Settings in the last list are the most significant
22057 ones and overrule settings in the other lists."
22058 (let ((rtn (copy-sequence (pop plists)))
22059 p v ls)
22060 (while plists
22061 (setq ls (pop plists))
22062 (while ls
22063 (setq p (pop ls) v (pop ls))
22064 (setq rtn (plist-put rtn p v))))
22065 rtn))
22067 (defun org-replace-escapes (string table)
22068 "Replace %-escapes in STRING with values in TABLE.
22069 TABLE is an association list with keys like \"%a\" and string values.
22070 The sequences in STRING may contain normal field width and padding information,
22071 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22072 so values can contain further %-escapes if they are define later in TABLE."
22073 (let ((tbl (copy-alist table))
22074 (case-fold-search nil)
22075 (pchg 0)
22076 e re rpl)
22077 (while (setq e (pop tbl))
22078 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22079 (when (and (cdr e) (string-match re (cdr e)))
22080 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22081 (safe "SREF"))
22082 (add-text-properties 0 3 (list 'sref sref) safe)
22083 (setcdr e (replace-match safe t t (cdr e)))))
22084 (while (string-match re string)
22085 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22086 (cdr e)))
22087 (setq string (replace-match rpl t t string))))
22088 (while (setq pchg (next-property-change pchg string))
22089 (let ((sref (get-text-property pchg 'sref string)))
22090 (when (and sref (string-match "SREF" string pchg))
22091 (setq string (replace-match sref t t string)))))
22092 string))
22094 (defun org-sublist (list start end)
22095 "Return a section of LIST, from START to END.
22096 Counting starts at 1."
22097 (let (rtn (c start))
22098 (setq list (nthcdr (1- start) list))
22099 (while (and list (<= c end))
22100 (push (pop list) rtn)
22101 (setq c (1+ c)))
22102 (nreverse rtn)))
22104 (defun org-find-base-buffer-visiting (file)
22105 "Like `find-buffer-visiting' but always return the base buffer and
22106 not an indirect buffer."
22107 (let ((buf (or (get-file-buffer file)
22108 (find-buffer-visiting file))))
22109 (if buf
22110 (or (buffer-base-buffer buf) buf)
22111 nil)))
22113 (defun org-image-file-name-regexp (&optional extensions)
22114 "Return regexp matching the file names of images.
22115 If EXTENSIONS is given, only match these."
22116 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22117 (image-file-name-regexp)
22118 (let ((image-file-name-extensions
22119 (or extensions
22120 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22121 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22122 (concat "\\."
22123 (regexp-opt (nconc (mapcar 'upcase
22124 image-file-name-extensions)
22125 image-file-name-extensions)
22127 "\\'"))))
22129 (defun org-file-image-p (file &optional extensions)
22130 "Return non-nil if FILE is an image."
22131 (save-match-data
22132 (string-match (org-image-file-name-regexp extensions) file)))
22134 (defun org-get-cursor-date (&optional with-time)
22135 "Return the date at cursor in as a time.
22136 This works in the calendar and in the agenda, anywhere else it just
22137 returns the current time.
22138 If WITH-TIME is non-nil, returns the time of the event at point (in
22139 the agenda) or the current time of the day."
22140 (let (date day defd tp tm hod mod)
22141 (when with-time
22142 (setq tp (get-text-property (point) 'time))
22143 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22144 (setq hod (string-to-number (match-string 1 tp))
22145 mod (string-to-number (match-string 2 tp))))
22146 (or tp (setq hod (nth 2 (decode-time (current-time)))
22147 mod (nth 1 (decode-time (current-time))))))
22148 (cond
22149 ((eq major-mode 'calendar-mode)
22150 (setq date (calendar-cursor-to-date)
22151 defd (encode-time 0 (or mod 0) (or hod 0)
22152 (nth 1 date) (nth 0 date) (nth 2 date))))
22153 ((eq major-mode 'org-agenda-mode)
22154 (setq day (get-text-property (point) 'day))
22155 (if day
22156 (setq date (calendar-gregorian-from-absolute day)
22157 defd (encode-time 0 (or mod 0) (or hod 0)
22158 (nth 1 date) (nth 0 date) (nth 2 date))))))
22159 (or defd (current-time))))
22161 (defun org-mark-subtree (&optional up)
22162 "Mark the current subtree.
22163 This puts point at the start of the current subtree, and mark at
22164 the end. If a numeric prefix UP is given, move up into the
22165 hierarchy of headlines by UP levels before marking the subtree."
22166 (interactive "P")
22167 (org-with-limited-levels
22168 (cond ((org-at-heading-p) (beginning-of-line))
22169 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22170 (t (outline-previous-visible-heading 1))))
22171 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22172 (if (org-called-interactively-p 'any)
22173 (call-interactively 'org-mark-element)
22174 (org-mark-element)))
22177 ;;; Indentation
22179 (defun org-indent-line ()
22180 "Indent line depending on context."
22181 (interactive)
22182 (let* ((pos (point))
22183 (itemp (org-at-item-p))
22184 (case-fold-search t)
22185 (org-drawer-regexp (or org-drawer-regexp "\000"))
22186 (inline-task-p (and (featurep 'org-inlinetask)
22187 (org-inlinetask-in-task-p)))
22188 (inline-re (and inline-task-p
22189 (org-inlinetask-outline-regexp)))
22190 column)
22191 (if (and orgstruct-is-++ (eq pos (point)))
22192 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22193 (indent-according-to-mode))
22194 (beginning-of-line 1)
22195 (cond
22196 ;; Headings
22197 ((looking-at org-outline-regexp) (setq column 0))
22198 ;; Footnote definition
22199 ((looking-at org-footnote-definition-re) (setq column 0))
22200 ;; Literal examples
22201 ((looking-at "[ \t]*:\\( \\|$\\)")
22202 (setq column (org-get-indentation))) ; do nothing
22203 ;; Lists
22204 ((ignore-errors (goto-char (org-in-item-p)))
22205 (setq column (if itemp
22206 (org-get-indentation)
22207 (org-list-item-body-column (point))))
22208 (goto-char pos))
22209 ;; Drawers
22210 ((and (looking-at "[ \t]*:END:")
22211 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22212 (save-excursion
22213 (goto-char (1- (match-beginning 1)))
22214 (setq column (current-column))))
22215 ;; Special blocks
22216 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22217 (save-excursion
22218 (re-search-backward
22219 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22220 (setq column (org-get-indentation (match-string 0))))
22221 ((and (not (looking-at "[ \t]*#\\+begin_"))
22222 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22223 (save-excursion
22224 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22225 (setq column
22226 (cond ((equal (downcase (match-string 1)) "src")
22227 ;; src blocks: let `org-edit-src-exit' handle them
22228 (org-get-indentation))
22229 ((equal (downcase (match-string 1)) "example")
22230 (max (org-get-indentation)
22231 (org-get-indentation (match-string 0))))
22233 (org-get-indentation (match-string 0))))))
22234 ;; This line has nothing special, look at the previous relevant
22235 ;; line to compute indentation
22237 (beginning-of-line 0)
22238 (while (and (not (bobp))
22239 (not (looking-at org-table-line-regexp))
22240 (not (looking-at org-drawer-regexp))
22241 ;; When point started in an inline task, do not move
22242 ;; above task starting line.
22243 (not (and inline-task-p (looking-at inline-re)))
22244 ;; Skip drawers, blocks, empty lines, verbatim,
22245 ;; comments, tables, footnotes definitions, lists,
22246 ;; inline tasks.
22247 (or (and (looking-at "[ \t]*:END:")
22248 (re-search-backward org-drawer-regexp nil t))
22249 (and (looking-at "[ \t]*#\\+end_")
22250 (re-search-backward "[ \t]*#\\+begin_"nil t))
22251 (looking-at "[ \t]*[\n:#|]")
22252 (looking-at org-footnote-definition-re)
22253 (and (not inline-task-p)
22254 (featurep 'org-inlinetask)
22255 (org-inlinetask-in-task-p)
22256 (or (org-inlinetask-goto-beginning) t))))
22257 (beginning-of-line 0))
22258 (cond
22259 ;; There was a list item above.
22260 ((ignore-errors (goto-char (org-in-item-p)))
22261 (goto-char (org-list-get-top-point (org-list-struct)))
22262 (setq column (org-get-indentation)))
22263 ;; There was an heading above.
22264 ((looking-at "\\*+[ \t]+")
22265 (if (not org-adapt-indentation)
22266 (setq column 0)
22267 (goto-char (match-end 0))
22268 (setq column (current-column))))
22269 ;; A drawer had started and is unfinished
22270 ((looking-at org-drawer-regexp)
22271 (goto-char (1- (match-beginning 1)))
22272 (setq column (current-column)))
22273 ;; Else, nothing noticeable found: get indentation and go on.
22274 (t (setq column (org-get-indentation))))))
22275 ;; Now apply indentation and move cursor accordingly
22276 (goto-char pos)
22277 (if (<= (current-column) (current-indentation))
22278 (org-indent-line-to column)
22279 (save-excursion (org-indent-line-to column)))
22280 ;; Special polishing for properties, see `org-property-format'
22281 (setq column (current-column))
22282 (beginning-of-line 1)
22283 (if (looking-at org-property-re)
22284 (replace-match (concat (match-string 4)
22285 (format org-property-format
22286 (match-string 1) (match-string 3)))
22287 t t))
22288 (org-move-to-column column))))
22290 (defun org-indent-drawer ()
22291 "Indent the drawer at point."
22292 (interactive)
22293 (let ((p (point))
22294 (e (and (save-excursion (re-search-forward ":END:" nil t))
22295 (match-end 0)))
22296 (folded
22297 (save-excursion
22298 (end-of-line)
22299 (when (overlays-at (point))
22300 (member 'invisible (overlay-properties
22301 (car (overlays-at (point)))))))))
22302 (when folded (org-cycle))
22303 (indent-for-tab-command)
22304 (while (and (move-beginning-of-line 2) (< (point) e))
22305 (indent-for-tab-command))
22306 (goto-char p)
22307 (when folded (org-cycle)))
22308 (message "Drawer at point indented"))
22310 (defun org-indent-block ()
22311 "Indent the block at point."
22312 (interactive)
22313 (let ((p (point))
22314 (case-fold-search t)
22315 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22316 (match-end 0)))
22317 (folded
22318 (save-excursion
22319 (end-of-line)
22320 (when (overlays-at (point))
22321 (member 'invisible (overlay-properties
22322 (car (overlays-at (point)))))))))
22323 (when folded (org-cycle))
22324 (indent-for-tab-command)
22325 (while (and (move-beginning-of-line 2) (< (point) e))
22326 (indent-for-tab-command))
22327 (goto-char p)
22328 (when folded (org-cycle)))
22329 (message "Block at point indented"))
22331 (defun org-indent-region (start end)
22332 "Indent region."
22333 (interactive "r")
22334 (save-excursion
22335 (let ((line-end (org-current-line end)))
22336 (goto-char start)
22337 (while (< (org-current-line) line-end)
22338 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22339 (t (call-interactively 'org-indent-line)))
22340 (move-beginning-of-line 2)))))
22343 ;;; Filling
22345 ;; We use our own fill-paragraph and auto-fill functions.
22347 ;; `org-fill-paragraph' relies on adaptive filling and context
22348 ;; checking. Appropriate `fill-prefix' is computed with
22349 ;; `org-adaptive-fill-function'.
22351 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22352 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22353 ;; `org-adaptive-fill-function' value. Internally,
22354 ;; `org-comment-line-break-function' breaks the line.
22356 ;; `org-setup-filling' installs filling and auto-filling related
22357 ;; variables during `org-mode' initialization.
22359 (defvar org-element-paragraph-separate) ; org-element.el
22360 (defun org-setup-filling ()
22361 (require 'org-element)
22362 ;; Prevent auto-fill from inserting unwanted new items.
22363 (when (boundp 'fill-nobreak-predicate)
22364 (org-set-local
22365 'fill-nobreak-predicate
22366 (org-uniquify
22367 (append fill-nobreak-predicate
22368 '(org-fill-line-break-nobreak-p
22369 org-fill-paragraph-with-timestamp-nobreak-p)))))
22370 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22371 (org-set-local 'paragraph-start paragraph-ending)
22372 (org-set-local 'paragraph-separate paragraph-ending))
22373 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22374 (org-set-local 'auto-fill-inhibit-regexp nil)
22375 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22376 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22377 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22379 (defun org-fill-line-break-nobreak-p ()
22380 "Non-nil when a new line at point would create an Org line break."
22381 (save-excursion
22382 (skip-chars-backward "[ \t]")
22383 (skip-chars-backward "\\\\")
22384 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22386 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22387 "Non-nil when a new line at point would split a timestamp."
22388 (and (org-at-timestamp-p t)
22389 (not (looking-at org-ts-regexp-both))))
22391 (declare-function message-in-body-p "message" ())
22392 (defvar orgtbl-line-start-regexp) ; From org-table.el
22393 (defun org-adaptive-fill-function ()
22394 "Compute a fill prefix for the current line.
22395 Return fill prefix, as a string, or nil if current line isn't
22396 meant to be filled. For convenience, if `adaptive-fill-regexp'
22397 matches in paragraphs or comments, use it."
22398 (catch 'exit
22399 (when (derived-mode-p 'message-mode)
22400 (save-excursion
22401 (beginning-of-line)
22402 (cond ((or (not (message-in-body-p))
22403 (looking-at orgtbl-line-start-regexp))
22404 (throw 'exit nil))
22405 ((looking-at message-cite-prefix-regexp)
22406 (throw 'exit (match-string-no-properties 0)))
22407 ((looking-at org-outline-regexp)
22408 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22409 (org-with-wide-buffer
22410 (let* ((p (line-beginning-position))
22411 (element (save-excursion
22412 (beginning-of-line)
22413 (or (ignore-errors (org-element-at-point))
22414 (user-error "An element cannot be parsed line %d"
22415 (line-number-at-pos (point))))))
22416 (type (org-element-type element))
22417 (post-affiliated (org-element-property :post-affiliated element)))
22418 (unless (and post-affiliated (< p post-affiliated))
22419 (case type
22420 (comment
22421 (save-excursion
22422 (beginning-of-line)
22423 (looking-at "[ \t]*")
22424 (concat (match-string 0) "# ")))
22425 (footnote-definition "")
22426 ((item plain-list)
22427 (make-string (org-list-item-body-column
22428 (or post-affiliated
22429 (org-element-property :begin element)))
22430 ? ))
22431 (paragraph
22432 ;; Fill prefix is usually the same as the current line,
22433 ;; unless the paragraph is at the beginning of an item.
22434 (let ((parent (org-element-property :parent element)))
22435 (save-excursion
22436 (beginning-of-line)
22437 (cond ((eq (org-element-type parent) 'item)
22438 (make-string (org-list-item-body-column
22439 (org-element-property :begin parent))
22440 ? ))
22441 ((and adaptive-fill-regexp
22442 ;; Locally disable
22443 ;; `adaptive-fill-function' to let
22444 ;; `fill-context-prefix' handle
22445 ;; `adaptive-fill-regexp' variable.
22446 (let (adaptive-fill-function)
22447 (fill-context-prefix
22448 post-affiliated
22449 (org-element-property :end element)))))
22450 ((looking-at "[ \t]+") (match-string 0))
22451 (t "")))))
22452 (comment-block
22453 ;; Only fill contents if P is within block boundaries.
22454 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22455 (forward-line)
22456 (point)))
22457 (cend (save-excursion
22458 (goto-char (org-element-property :end element))
22459 (skip-chars-backward " \r\t\n")
22460 (line-beginning-position))))
22461 (when (and (>= p cbeg) (< p cend))
22462 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22463 (match-string 0)
22464 ""))))))))))
22466 (declare-function message-goto-body "message" ())
22467 (defvar message-cite-prefix-regexp) ; From message.el
22468 (defun org-fill-paragraph (&optional justify)
22469 "Fill element at point, when applicable.
22471 This function only applies to comment blocks, comments, example
22472 blocks and paragraphs. Also, as a special case, re-align table
22473 when point is at one.
22475 If JUSTIFY is non-nil (interactively, with prefix argument),
22476 justify as well. If `sentence-end-double-space' is non-nil, then
22477 period followed by one space does not end a sentence, so don't
22478 break a line there. The variable `fill-column' controls the
22479 width for filling.
22481 For convenience, when point is at a plain list, an item or
22482 a footnote definition, try to fill the first paragraph within."
22483 (interactive)
22484 (if (and (derived-mode-p 'message-mode)
22485 (or (not (message-in-body-p))
22486 (save-excursion (move-beginning-of-line 1)
22487 (looking-at message-cite-prefix-regexp))))
22488 ;; First ensure filling is correct in message-mode.
22489 (let ((fill-paragraph-function
22490 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22491 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22492 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22493 (paragraph-separate
22494 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22495 (fill-paragraph nil))
22496 (with-syntax-table org-mode-transpose-word-syntax-table
22497 ;; Move to end of line in order to get the first paragraph
22498 ;; within a plain list or a footnote definition.
22499 (let ((element (save-excursion
22500 (end-of-line)
22501 (or (ignore-errors (org-element-at-point))
22502 (user-error "An element cannot be parsed line %d"
22503 (line-number-at-pos (point)))))))
22504 ;; First check if point is in a blank line at the beginning of
22505 ;; the buffer. In that case, ignore filling.
22506 (case (org-element-type element)
22507 ;; Use major mode filling function is src blocks.
22508 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22509 ;; Align Org tables, leave table.el tables as-is.
22510 (table-row (org-table-align) t)
22511 (table
22512 (when (eq (org-element-property :type element) 'org)
22513 (save-excursion
22514 (goto-char (org-element-property :post-affiliated element))
22515 (org-table-align)))
22517 (paragraph
22518 ;; Paragraphs may contain `line-break' type objects.
22519 (let ((beg (max (point-min)
22520 (org-element-property :contents-begin element)))
22521 (end (min (point-max)
22522 (org-element-property :contents-end element))))
22523 ;; Do nothing if point is at an affiliated keyword.
22524 (if (< (line-end-position) beg) t
22525 (when (derived-mode-p 'message-mode)
22526 ;; In `message-mode', do not fill following citation
22527 ;; in current paragraph nor text before message body.
22528 (let ((body-start (save-excursion (message-goto-body))))
22529 (when body-start (setq beg (max body-start beg))))
22530 (when (save-excursion
22531 (re-search-forward
22532 (concat "^" message-cite-prefix-regexp) end t))
22533 (setq end (match-beginning 0))))
22534 ;; Fill paragraph, taking line breaks into account.
22535 ;; For that, slice the paragraph using line breaks as
22536 ;; separators, and fill the parts in reverse order to
22537 ;; avoid messing with markers.
22538 (save-excursion
22539 (goto-char end)
22540 (mapc
22541 (lambda (pos)
22542 (fill-region-as-paragraph pos (point) justify)
22543 (goto-char pos))
22544 ;; Find the list of ending positions for line breaks
22545 ;; in the current paragraph. Add paragraph
22546 ;; beginning to include first slice.
22547 (nreverse
22548 (cons beg
22549 (org-element-map
22550 (org-element--parse-objects
22551 beg end nil (org-element-restriction 'paragraph))
22552 'line-break
22553 (lambda (lb) (org-element-property :end lb)))))))
22554 t)))
22555 ;; Contents of `comment-block' type elements should be
22556 ;; filled as plain text, but only if point is within block
22557 ;; markers.
22558 (comment-block
22559 (let* ((case-fold-search t)
22560 (beg (save-excursion
22561 (goto-char (org-element-property :begin element))
22562 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22563 (forward-line)
22564 (point)))
22565 (end (save-excursion
22566 (goto-char (org-element-property :end element))
22567 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22568 (line-beginning-position))))
22569 (if (or (< (point) beg) (> (point) end)) t
22570 (fill-region-as-paragraph
22571 (save-excursion (end-of-line)
22572 (re-search-backward "^[ \t]*$" beg 'move)
22573 (line-beginning-position))
22574 (save-excursion (beginning-of-line)
22575 (re-search-forward "^[ \t]*$" end 'move)
22576 (line-beginning-position))
22577 justify))))
22578 ;; Fill comments.
22579 (comment
22580 (let ((begin (org-element-property :post-affiliated element))
22581 (end (org-element-property :end element)))
22582 (when (and (>= (point) begin) (<= (point) end))
22583 (let ((begin (save-excursion
22584 (end-of-line)
22585 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22586 (progn (forward-line) (point))
22587 begin)))
22588 (end (save-excursion
22589 (end-of-line)
22590 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22591 (1- (line-beginning-position))
22592 (skip-chars-backward " \r\t\n")
22593 (line-end-position)))))
22594 ;; Do not fill comments when at a blank line.
22595 (when (> end begin)
22596 (let ((fill-prefix
22597 (save-excursion
22598 (beginning-of-line)
22599 (looking-at "[ \t]*#")
22600 (let ((comment-prefix (match-string 0)))
22601 (goto-char (match-end 0))
22602 (if (looking-at adaptive-fill-regexp)
22603 (concat comment-prefix (match-string 0))
22604 (concat comment-prefix " "))))))
22605 (save-excursion
22606 (fill-region-as-paragraph begin end justify))))))
22608 ;; Ignore every other element.
22609 (otherwise t))))))
22611 (defun org-auto-fill-function ()
22612 "Auto-fill function."
22613 ;; Check if auto-filling is meaningful.
22614 (let ((fc (current-fill-column)))
22615 (when (and fc (> (current-column) fc))
22616 (let* ((fill-prefix (org-adaptive-fill-function))
22617 ;; Enforce empty fill prefix, if required. Otherwise, it
22618 ;; will be computed again.
22619 (adaptive-fill-mode (not (equal fill-prefix ""))))
22620 (when fill-prefix (do-auto-fill))))))
22622 (defun org-comment-line-break-function (&optional soft)
22623 "Break line at point and indent, continuing comment if within one.
22624 The inserted newline is marked hard if variable
22625 `use-hard-newlines' is true, unless optional argument SOFT is
22626 non-nil."
22627 (if soft (insert-and-inherit ?\n) (newline 1))
22628 (save-excursion (forward-char -1) (delete-horizontal-space))
22629 (delete-horizontal-space)
22630 (indent-to-left-margin)
22631 (insert-before-markers-and-inherit fill-prefix))
22634 ;;; Fixed Width Areas
22636 (defun org-toggle-fixed-width ()
22637 "Toggle fixed-width markup.
22639 Add or remove fixed-width markup on current line, whenever it
22640 makes sense. Return an error otherwise.
22642 If a region is active and if it contains only fixed-width areas
22643 or blank lines, remove all fixed-width markup in it. If the
22644 region contains anything else, convert all non-fixed-width lines
22645 to fixed-width ones.
22647 Blank lines at the end of the region are ignored unless the
22648 region only contains such lines."
22649 (interactive)
22650 (if (not (org-region-active-p))
22651 ;; No region:
22653 ;; Remove fixed width marker only in a fixed-with element.
22655 ;; Add fixed width maker in paragraphs, in blank lines after
22656 ;; elements or at the beginning of a headline or an inlinetask,
22657 ;; and before any one-line elements (e.g., a clock).
22658 (progn
22659 (beginning-of-line)
22660 (let* ((element (org-element-at-point))
22661 (type (org-element-type element)))
22662 (cond
22663 ((and (eq type 'fixed-width)
22664 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22665 (replace-match
22666 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22667 ((and (memq type '(babel-call clock comment diary-sexp headline
22668 horizontal-rule keyword paragraph
22669 planning))
22670 (or (not (org-element-property :post-affiliated element))
22671 (<= (org-element-property :post-affiliated element)
22672 (point))))
22673 (skip-chars-forward " \t")
22674 (insert ": "))
22675 ((and (org-looking-at-p "[ \t]*$")
22676 (or (eq type 'inlinetask)
22677 (save-excursion
22678 (skip-chars-forward " \r\t\n")
22679 (<= (org-element-property :end element) (point)))))
22680 (delete-region (point) (line-end-position))
22681 (org-indent-line)
22682 (insert ": "))
22683 (t (user-error "Cannot insert a fixed-width line here")))))
22684 ;; Region active.
22685 (let* ((begin (save-excursion
22686 (goto-char (region-beginning))
22687 (line-beginning-position)))
22688 (end (copy-marker
22689 (save-excursion
22690 (goto-char (region-end))
22691 (unless (eolp) (beginning-of-line))
22692 (if (save-excursion (re-search-backward "\\S-" begin t))
22693 (progn (skip-chars-backward " \r\t\n") (point))
22694 (point)))))
22695 (all-fixed-width-p
22696 (catch 'not-all-p
22697 (save-excursion
22698 (goto-char begin)
22699 (skip-chars-forward " \r\t\n")
22700 (when (eobp) (throw 'not-all-p nil))
22701 (while (< (point) end)
22702 (let ((element (org-element-at-point)))
22703 (if (eq (org-element-type element) 'fixed-width)
22704 (goto-char (org-element-property :end element))
22705 (throw 'not-all-p nil))))
22706 t))))
22707 (if all-fixed-width-p
22708 (save-excursion
22709 (goto-char begin)
22710 (while (< (point) end)
22711 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22712 (replace-match
22713 "" nil nil nil
22714 (if (= (line-end-position) (match-end 0)) 0 1)))
22715 (forward-line)))
22716 (let ((min-ind (point-max)))
22717 ;; Find minimum indentation across all lines.
22718 (save-excursion
22719 (goto-char begin)
22720 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22721 (setq min-ind 0)
22722 (catch 'zerop
22723 (while (< (point) end)
22724 (unless (org-looking-at-p "[ \t]*$")
22725 (let ((ind (org-get-indentation)))
22726 (setq min-ind (min min-ind ind))
22727 (when (zerop ind) (throw 'zerop t))))
22728 (forward-line)))))
22729 ;; Loop over all lines and add fixed-width markup everywhere
22730 ;; but in fixed-width lines.
22731 (save-excursion
22732 (goto-char begin)
22733 (while (< (point) end)
22734 (cond
22735 ((org-at-heading-p)
22736 (insert ": ")
22737 (forward-line)
22738 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
22739 (insert ":")
22740 (forward-line)))
22741 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
22742 (let* ((element (org-element-at-point))
22743 (element-end (org-element-property :end element)))
22744 (if (eq (org-element-type element) 'fixed-width)
22745 (progn (goto-char element-end)
22746 (skip-chars-backward " \r\t\n")
22747 (forward-line))
22748 (let ((limit (min end element-end)))
22749 (while (< (point) limit)
22750 (org-move-to-column min-ind t)
22751 (insert ": ")
22752 (forward-line))))))
22754 (org-move-to-column min-ind t)
22755 (insert ": ")
22756 (forward-line)))))))
22757 (set-marker end nil))))
22760 ;;; Comments
22762 ;; Org comments syntax is quite complex. It requires the entire line
22763 ;; to be just a comment. Also, even with the right syntax at the
22764 ;; beginning of line, some some elements (i.e. verse-block or
22765 ;; example-block) don't accept comments. Usual Emacs comment commands
22766 ;; cannot cope with those requirements. Therefore, Org replaces them.
22768 ;; Org still relies on `comment-dwim', but cannot trust
22769 ;; `comment-only-p'. So, `comment-region-function' and
22770 ;; `uncomment-region-function' both point
22771 ;; to`org-comment-or-uncomment-region'. Eventually,
22772 ;; `org-insert-comment' takes care of insertion of comments at the
22773 ;; beginning of line.
22775 ;; `org-setup-comments-handling' install comments related variables
22776 ;; during `org-mode' initialization.
22778 (defun org-setup-comments-handling ()
22779 (interactive)
22780 (org-set-local 'comment-use-syntax nil)
22781 (org-set-local 'comment-start "# ")
22782 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22783 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22784 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22785 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22787 (defun org-insert-comment ()
22788 "Insert an empty comment above current line.
22789 If the line is empty, insert comment at its beginning. When
22790 point is within a source block, comment according to the related
22791 major mode."
22792 (if (let ((element (org-element-at-point)))
22793 (and (eq (org-element-type element) 'src-block)
22794 (< (save-excursion
22795 (goto-char (org-element-property :post-affiliated element))
22796 (line-end-position))
22797 (point))
22798 (> (save-excursion
22799 (goto-char (org-element-property :end element))
22800 (skip-chars-backward " \r\t\n")
22801 (line-beginning-position))
22802 (point))))
22803 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22804 (beginning-of-line)
22805 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22806 (open-line 1))
22807 (org-indent-line)
22808 (insert "# ")))
22810 (defvar comment-empty-lines) ; From newcomment.el.
22811 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22812 "Comment or uncomment each non-blank line in the region.
22813 Uncomment each non-blank line between BEG and END if it only
22814 contains commented lines. Otherwise, comment them. If region is
22815 strictly within a source block, use appropriate comment syntax."
22816 (if (let ((element (org-element-at-point)))
22817 (and (eq (org-element-type element) 'src-block)
22818 (< (save-excursion
22819 (goto-char (org-element-property :post-affiliated element))
22820 (line-end-position))
22821 beg)
22822 (>= (save-excursion
22823 (goto-char (org-element-property :end element))
22824 (skip-chars-backward " \r\t\n")
22825 (line-beginning-position))
22826 end)))
22827 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22828 (save-restriction
22829 ;; Restrict region
22830 (narrow-to-region (save-excursion (goto-char beg)
22831 (skip-chars-forward " \r\t\n" end)
22832 (line-beginning-position))
22833 (save-excursion (goto-char end)
22834 (skip-chars-backward " \r\t\n" beg)
22835 (line-end-position)))
22836 (let ((uncommentp
22837 ;; UNCOMMENTP is non-nil when every non blank line between
22838 ;; BEG and END is a comment.
22839 (save-excursion
22840 (goto-char (point-min))
22841 (while (and (not (eobp))
22842 (let ((element (org-element-at-point)))
22843 (and (eq (org-element-type element) 'comment)
22844 (goto-char (min (point-max)
22845 (org-element-property
22846 :end element)))))))
22847 (eobp))))
22848 (if uncommentp
22849 ;; Only blank lines and comments in region: uncomment it.
22850 (save-excursion
22851 (goto-char (point-min))
22852 (while (not (eobp))
22853 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22854 (replace-match "" nil nil nil 1))
22855 (forward-line)))
22856 ;; Comment each line in region.
22857 (let ((min-indent (point-max)))
22858 ;; First find the minimum indentation across all lines.
22859 (save-excursion
22860 (goto-char (point-min))
22861 (while (and (not (eobp)) (not (zerop min-indent)))
22862 (unless (looking-at "[ \t]*$")
22863 (setq min-indent (min min-indent (current-indentation))))
22864 (forward-line)))
22865 ;; Then loop over all lines.
22866 (save-excursion
22867 (goto-char (point-min))
22868 (while (not (eobp))
22869 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22870 ;; Don't get fooled by invisible text (e.g. link path)
22871 ;; when moving to column MIN-INDENT.
22872 (let ((buffer-invisibility-spec nil))
22873 (org-move-to-column min-indent t))
22874 (insert comment-start))
22875 (forward-line)))))))))
22877 (defun org-comment-dwim (arg)
22878 (interactive "*P")
22879 "Call `comment-dwim' within a source edit buffer if needed."
22880 (if (org-in-src-block-p)
22881 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22882 (call-interactively #'comment-dwim)))
22885 ;;; Planning
22887 ;; This section contains tools to operate on timestamp objects, as
22888 ;; returned by, e.g. `org-element-context'.
22890 (defun org-timestamp-has-time-p (timestamp)
22891 "Non-nil when TIMESTAMP has a time specified."
22892 (org-element-property :hour-start timestamp))
22894 (defun org-timestamp-format (timestamp format &optional end utc)
22895 "Format a TIMESTAMP element into a string.
22897 FORMAT is a format specifier to be passed to
22898 `format-time-string'.
22900 When optional argument END is non-nil, use end of date-range or
22901 time-range, if possible.
22903 When optional argument UTC is non-nil, time will be expressed as
22904 Universal Time."
22905 (format-time-string
22906 format
22907 (apply 'encode-time
22908 (cons 0
22909 (mapcar
22910 (lambda (prop) (or (org-element-property prop timestamp) 0))
22911 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22912 '(:minute-start :hour-start :day-start :month-start
22913 :year-start)))))
22914 utc))
22916 (defun org-timestamp-split-range (timestamp &optional end)
22917 "Extract a timestamp object from a date or time range.
22919 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22920 the end of the range. Otherwise, extract its start.
22922 Return a new timestamp object sharing the same parent as
22923 TIMESTAMP."
22924 (let ((type (org-element-property :type timestamp)))
22925 (if (memq type '(active inactive diary)) timestamp
22926 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22927 ;; Set new type.
22928 (org-element-put-property
22929 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22930 ;; Copy start properties over end properties if END is
22931 ;; non-nil. Otherwise, copy end properties over `start' ones.
22932 (let ((p-alist '((:minute-start . :minute-end)
22933 (:hour-start . :hour-end)
22934 (:day-start . :day-end)
22935 (:month-start . :month-end)
22936 (:year-start . :year-end))))
22937 (dolist (p-cell p-alist)
22938 (org-element-put-property
22939 split-ts
22940 (funcall (if end 'car 'cdr) p-cell)
22941 (org-element-property
22942 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22943 ;; Eventually refresh `:raw-value'.
22944 (org-element-put-property split-ts :raw-value nil)
22945 (org-element-put-property
22946 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22948 (defun org-timestamp-translate (timestamp &optional boundary)
22949 "Apply `org-translate-time' on a TIMESTAMP object.
22950 When optional argument BOUNDARY is non-nil, it is either the
22951 symbol `start' or `end'. In this case, only translate the
22952 starting or ending part of TIMESTAMP if it is a date or time
22953 range. Otherwise, translate both parts."
22954 (if (and (not boundary)
22955 (memq (org-element-property :type timestamp)
22956 '(active-range inactive-range)))
22957 (concat
22958 (org-translate-time
22959 (org-element-property :raw-value
22960 (org-timestamp-split-range timestamp)))
22961 "--"
22962 (org-translate-time
22963 (org-element-property :raw-value
22964 (org-timestamp-split-range timestamp t))))
22965 (org-translate-time
22966 (org-element-property
22967 :raw-value
22968 (if (not boundary) timestamp
22969 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22973 ;;; Other stuff.
22975 (defun org-reftex-citation ()
22976 "Use reftex-citation to insert a citation into the buffer.
22977 This looks for a line like
22979 #+BIBLIOGRAPHY: foo plain option:-d
22981 and derives from it that foo.bib is the bibliography file relevant
22982 for this document. It then installs the necessary environment for RefTeX
22983 to work in this buffer and calls `reftex-citation' to insert a citation
22984 into the buffer.
22986 Export of such citations to both LaTeX and HTML is handled by the contributed
22987 package ox-bibtex by Taru Karttunen."
22988 (interactive)
22989 (let ((reftex-docstruct-symbol 'rds)
22990 (reftex-cite-format "\\cite{%l}")
22991 rds bib)
22992 (save-excursion
22993 (save-restriction
22994 (widen)
22995 (let ((case-fold-search t)
22996 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22997 (if (not (save-excursion
22998 (or (re-search-forward re nil t)
22999 (re-search-backward re nil t))))
23000 (error "No bibliography defined in file")
23001 (setq bib (concat (match-string 1) ".bib")
23002 rds (list (list 'bib bib)))))))
23003 (call-interactively 'reftex-citation)))
23005 ;;;; Functions extending outline functionality
23007 (defun org-beginning-of-line (&optional arg)
23008 "Go to the beginning of the current line. If that is invisible, continue
23009 to a visible line beginning. This makes the function of C-a more intuitive.
23010 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23011 first attempt, and only move to after the tags when the cursor is already
23012 beyond the end of the headline."
23013 (interactive "P")
23014 (let ((pos (point))
23015 (special (if (consp org-special-ctrl-a/e)
23016 (car org-special-ctrl-a/e)
23017 org-special-ctrl-a/e))
23018 deactivate-mark refpos)
23019 (if (org-bound-and-true-p visual-line-mode)
23020 (beginning-of-visual-line 1)
23021 (beginning-of-line 1))
23022 (if (and arg (fboundp 'move-beginning-of-line))
23023 (call-interactively 'move-beginning-of-line)
23024 (if (bobp)
23026 (backward-char 1)
23027 (if (org-truely-invisible-p)
23028 (while (and (not (bobp)) (org-truely-invisible-p))
23029 (backward-char 1)
23030 (beginning-of-line 1))
23031 (forward-char 1))))
23032 (when special
23033 (cond
23034 ((and (looking-at org-complex-heading-regexp)
23035 (= (char-after (match-end 1)) ?\ ))
23036 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23037 (point-at-eol)))
23038 (goto-char
23039 (if (eq special t)
23040 (cond ((> pos refpos) refpos)
23041 ((= pos (point)) refpos)
23042 (t (point)))
23043 (cond ((> pos (point)) (point))
23044 ((not (eq last-command this-command)) (point))
23045 (t refpos)))))
23046 ((org-at-item-p)
23047 ;; Being at an item and not looking at an the item means point
23048 ;; was previously moved to beginning of a visual line, which
23049 ;; doesn't contain the item. Therefore, do nothing special,
23050 ;; just stay here.
23051 (when (looking-at org-list-full-item-re)
23052 ;; Set special position at first white space character after
23053 ;; bullet, and check-box, if any.
23054 (let ((after-bullet
23055 (let ((box (match-end 3)))
23056 (if (not box) (match-end 1)
23057 (let ((after (char-after box)))
23058 (if (and after (= after ? )) (1+ box) box))))))
23059 ;; Special case: Move point to special position when
23060 ;; currently after it or at beginning of line.
23061 (if (eq special t)
23062 (when (or (> pos after-bullet) (= (point) pos))
23063 (goto-char after-bullet))
23064 ;; Reversed case: Move point to special position when
23065 ;; point was already at beginning of line and command is
23066 ;; repeated.
23067 (when (and (= (point) pos) (eq last-command this-command))
23068 (goto-char after-bullet))))))))
23069 (org-no-warnings
23070 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23071 (setq disable-point-adjustment
23072 (or (not (invisible-p (point)))
23073 (not (invisible-p (max (point-min) (1- (point))))))))
23075 (defun org-end-of-line (&optional arg)
23076 "Go to the end of the line.
23077 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23078 tags on the first attempt, and only move to after the tags when
23079 the cursor is already beyond the end of the headline."
23080 (interactive "P")
23081 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23082 org-special-ctrl-a/e))
23083 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23084 'end-of-visual-line)
23085 ((fboundp 'move-end-of-line) 'move-end-of-line)
23086 (t 'end-of-line)))
23087 deactivate-mark)
23088 (if (or (not special) arg) (call-interactively move-fun)
23089 (let* ((element (save-excursion (beginning-of-line)
23090 (org-element-at-point)))
23091 (type (org-element-type element)))
23092 (cond
23093 ((memq type '(headline inlinetask))
23094 (let ((pos (point)))
23095 (beginning-of-line 1)
23096 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23097 (if (eq special t)
23098 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23099 (goto-char (match-beginning 1))
23100 (goto-char (match-end 0)))
23101 (if (or (< pos (match-end 0))
23102 (not (eq this-command last-command)))
23103 (goto-char (match-end 0))
23104 (goto-char (match-beginning 1))))
23105 (call-interactively move-fun))))
23106 ((outline-invisible-p (line-end-position))
23107 ;; If element is hidden, `move-end-of-line' would put point
23108 ;; after it. Use `end-of-line' to stay on current line.
23109 (call-interactively 'end-of-line))
23110 (t (call-interactively move-fun)))))
23111 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23112 (setq disable-point-adjustment
23113 (or (not (invisible-p (point)))
23114 (not (invisible-p (max (point-min) (1- (point))))))))
23116 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23117 (define-key org-mode-map "\C-e" 'org-end-of-line)
23119 (defun org-backward-sentence (&optional arg)
23120 "Go to beginning of sentence, or beginning of table field.
23121 This will call `backward-sentence' or `org-table-beginning-of-field',
23122 depending on context."
23123 (interactive "P")
23124 (cond
23125 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
23126 (t (call-interactively 'backward-sentence))))
23128 (defun org-forward-sentence (&optional arg)
23129 "Go to end of sentence, or end of table field.
23130 This will call `forward-sentence' or `org-table-end-of-field',
23131 depending on context."
23132 (interactive "P")
23133 (cond
23134 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
23135 (t (call-interactively 'forward-sentence))))
23137 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23138 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23140 (defun org-kill-line (&optional arg)
23141 "Kill line, to tags or end of line."
23142 (interactive "P")
23143 (cond
23144 ((or (not org-special-ctrl-k)
23145 (bolp)
23146 (not (org-at-heading-p)))
23147 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23148 org-ctrl-k-protect-subtree)
23149 (if (or (eq org-ctrl-k-protect-subtree 'error)
23150 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23151 (user-error "C-k aborted as it would kill a hidden subtree")))
23152 (call-interactively
23153 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23154 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23155 (kill-region (point) (match-beginning 1))
23156 (org-set-tags nil t))
23157 (t (kill-region (point) (point-at-eol)))))
23159 (define-key org-mode-map "\C-k" 'org-kill-line)
23161 (defun org-yank (&optional arg)
23162 "Yank. If the kill is a subtree, treat it specially.
23163 This command will look at the current kill and check if is a single
23164 subtree, or a series of subtrees[1]. If it passes the test, and if the
23165 cursor is at the beginning of a line or after the stars of a currently
23166 empty headline, then the yank is handled specially. How exactly depends
23167 on the value of the following variables, both set by default.
23169 org-yank-folded-subtrees
23170 When set, the subtree(s) will be folded after insertion, but only
23171 if doing so would now swallow text after the yanked text.
23173 org-yank-adjusted-subtrees
23174 When set, the subtree will be promoted or demoted in order to
23175 fit into the local outline tree structure, which means that the level
23176 will be adjusted so that it becomes the smaller one of the two
23177 *visible* surrounding headings.
23179 Any prefix to this command will cause `yank' to be called directly with
23180 no special treatment. In particular, a simple \\[universal-argument] prefix \
23181 will just
23182 plainly yank the text as it is.
23184 \[1] The test checks if the first non-white line is a heading
23185 and if there are no other headings with fewer stars."
23186 (interactive "P")
23187 (org-yank-generic 'yank arg))
23189 (defun org-yank-generic (command arg)
23190 "Perform some yank-like command.
23192 This function implements the behavior described in the `org-yank'
23193 documentation. However, it has been generalized to work for any
23194 interactive command with similar behavior."
23196 ;; pretend to be command COMMAND
23197 (setq this-command command)
23199 (if arg
23200 (call-interactively command)
23202 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23203 (and (org-kill-is-subtree-p)
23204 (or (bolp)
23205 (and (looking-at "[ \t]*$")
23206 (string-match
23207 "\\`\\*+\\'"
23208 (buffer-substring (point-at-bol) (point)))))))
23209 swallowp)
23210 (cond
23211 ((and subtreep org-yank-folded-subtrees)
23212 (let ((beg (point))
23213 end)
23214 (if (and subtreep org-yank-adjusted-subtrees)
23215 (org-paste-subtree nil nil 'for-yank)
23216 (call-interactively command))
23218 (setq end (point))
23219 (goto-char beg)
23220 (when (and (bolp) subtreep
23221 (not (setq swallowp
23222 (org-yank-folding-would-swallow-text beg end))))
23223 (org-with-limited-levels
23224 (or (looking-at org-outline-regexp)
23225 (re-search-forward org-outline-regexp-bol end t))
23226 (while (and (< (point) end) (looking-at org-outline-regexp))
23227 (hide-subtree)
23228 (org-cycle-show-empty-lines 'folded)
23229 (condition-case nil
23230 (outline-forward-same-level 1)
23231 (error (goto-char end))))))
23232 (when swallowp
23233 (message
23234 "Inserted text not folded because that would swallow text"))
23236 (goto-char end)
23237 (skip-chars-forward " \t\n\r")
23238 (beginning-of-line 1)
23239 (push-mark beg 'nomsg)))
23240 ((and subtreep org-yank-adjusted-subtrees)
23241 (let ((beg (point-at-bol)))
23242 (org-paste-subtree nil nil 'for-yank)
23243 (push-mark beg 'nomsg)))
23245 (call-interactively command))))))
23247 (defun org-yank-folding-would-swallow-text (beg end)
23248 "Would hide-subtree at BEG swallow any text after END?"
23249 (let (level)
23250 (org-with-limited-levels
23251 (save-excursion
23252 (goto-char beg)
23253 (when (or (looking-at org-outline-regexp)
23254 (re-search-forward org-outline-regexp-bol end t))
23255 (setq level (org-outline-level)))
23256 (goto-char end)
23257 (skip-chars-forward " \t\r\n\v\f")
23258 (if (or (eobp)
23259 (and (bolp) (looking-at org-outline-regexp)
23260 (<= (org-outline-level) level)))
23261 nil ; Nothing would be swallowed
23262 t))))) ; something would swallow
23264 (define-key org-mode-map "\C-y" 'org-yank)
23266 (defun org-truely-invisible-p ()
23267 "Check if point is at a character currently not visible.
23268 This version does not only check the character property, but also
23269 `visible-mode'."
23270 ;; Early versions of noutline don't have `outline-invisible-p'.
23271 (if (org-bound-and-true-p visible-mode)
23273 (outline-invisible-p)))
23275 (defun org-invisible-p2 ()
23276 "Check if point is at a character currently not visible."
23277 (save-excursion
23278 (if (and (eolp) (not (bobp))) (backward-char 1))
23279 ;; Early versions of noutline don't have `outline-invisible-p'.
23280 (outline-invisible-p)))
23282 (defun org-back-to-heading (&optional invisible-ok)
23283 "Call `outline-back-to-heading', but provide a better error message."
23284 (condition-case nil
23285 (outline-back-to-heading invisible-ok)
23286 (error (error "Before first headline at position %d in buffer %s"
23287 (point) (current-buffer)))))
23289 (defun org-before-first-heading-p ()
23290 "Before first heading?"
23291 (save-excursion
23292 (end-of-line)
23293 (null (re-search-backward org-outline-regexp-bol nil t))))
23295 (defun org-at-heading-p (&optional ignored)
23296 (outline-on-heading-p t))
23297 ;; Compatibility alias with Org versions < 7.8.03
23298 (defalias 'org-on-heading-p 'org-at-heading-p)
23300 (defun org-at-comment-p nil
23301 "Is cursor in a line starting with a # character?"
23302 (save-excursion
23303 (beginning-of-line)
23304 (looking-at "^#")))
23306 (defun org-at-drawer-p nil
23307 "Is cursor at a drawer keyword?"
23308 (save-excursion
23309 (move-beginning-of-line 1)
23310 (looking-at org-drawer-regexp)))
23312 (defun org-at-block-p nil
23313 "Is cursor at a block keyword?"
23314 (save-excursion
23315 (move-beginning-of-line 1)
23316 (looking-at org-block-regexp)))
23318 (defun org-point-at-end-of-empty-headline ()
23319 "If point is at the end of an empty headline, return t, else nil.
23320 If the heading only contains a TODO keyword, it is still still considered
23321 empty."
23322 (and (looking-at "[ \t]*$")
23323 (when org-todo-line-regexp
23324 (save-excursion
23325 (beginning-of-line 1)
23326 (let ((case-fold-search nil))
23327 (looking-at org-todo-line-regexp)
23328 (string= (match-string 3) ""))))))
23330 (defun org-at-heading-or-item-p ()
23331 (or (org-at-heading-p) (org-at-item-p)))
23333 (defun org-at-target-p ()
23334 (or (org-in-regexp org-radio-target-regexp)
23335 (org-in-regexp org-target-regexp)))
23336 ;; Compatibility alias with Org versions < 7.8.03
23337 (defalias 'org-on-target-p 'org-at-target-p)
23339 (defun org-up-heading-all (arg)
23340 "Move to the heading line of which the present line is a subheading.
23341 This function considers both visible and invisible heading lines.
23342 With argument, move up ARG levels."
23343 (if (fboundp 'outline-up-heading-all)
23344 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23345 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23347 (defun org-up-heading-safe ()
23348 "Move to the heading line of which the present line is a subheading.
23349 This version will not throw an error. It will return the level of the
23350 headline found, or nil if no higher level is found.
23352 Also, this function will be a lot faster than `outline-up-heading',
23353 because it relies on stars being the outline starters. This can really
23354 make a significant difference in outlines with very many siblings."
23355 (let (start-level re)
23356 (org-back-to-heading t)
23357 (setq start-level (funcall outline-level))
23358 (if (equal start-level 1)
23360 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23361 (if (re-search-backward re nil t)
23362 (funcall outline-level)))))
23364 (defun org-first-sibling-p ()
23365 "Is this heading the first child of its parents?"
23366 (interactive)
23367 (let ((re org-outline-regexp-bol)
23368 level l)
23369 (unless (org-at-heading-p t)
23370 (user-error "Not at a heading"))
23371 (setq level (funcall outline-level))
23372 (save-excursion
23373 (if (not (re-search-backward re nil t))
23375 (setq l (funcall outline-level))
23376 (< l level)))))
23378 (defun org-goto-sibling (&optional previous)
23379 "Goto the next sibling, even if it is invisible.
23380 When PREVIOUS is set, go to the previous sibling instead. Returns t
23381 when a sibling was found. When none is found, return nil and don't
23382 move point."
23383 (let ((fun (if previous 're-search-backward 're-search-forward))
23384 (pos (point))
23385 (re org-outline-regexp-bol)
23386 level l)
23387 (when (condition-case nil (org-back-to-heading t) (error nil))
23388 (setq level (funcall outline-level))
23389 (catch 'exit
23390 (or previous (forward-char 1))
23391 (while (funcall fun re nil t)
23392 (setq l (funcall outline-level))
23393 (when (< l level) (goto-char pos) (throw 'exit nil))
23394 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23395 (goto-char pos)
23396 nil))))
23398 (defun org-show-siblings ()
23399 "Show all siblings of the current headline."
23400 (save-excursion
23401 (while (org-goto-sibling) (org-flag-heading nil)))
23402 (save-excursion
23403 (while (org-goto-sibling 'previous)
23404 (org-flag-heading nil))))
23406 (defun org-goto-first-child ()
23407 "Goto the first child, even if it is invisible.
23408 Return t when a child was found. Otherwise don't move point and
23409 return nil."
23410 (let (level (pos (point)) (re org-outline-regexp-bol))
23411 (when (condition-case nil (org-back-to-heading t) (error nil))
23412 (setq level (outline-level))
23413 (forward-char 1)
23414 (if (and (re-search-forward re nil t) (> (outline-level) level))
23415 (progn (goto-char (match-beginning 0)) t)
23416 (goto-char pos) nil))))
23418 (defun org-show-hidden-entry ()
23419 "Show an entry where even the heading is hidden."
23420 (save-excursion
23421 (org-show-entry)))
23423 (defun org-flag-heading (flag &optional entry)
23424 "Flag the current heading. FLAG non-nil means make invisible.
23425 When ENTRY is non-nil, show the entire entry."
23426 (save-excursion
23427 (org-back-to-heading t)
23428 ;; Check if we should show the entire entry
23429 (if entry
23430 (progn
23431 (org-show-entry)
23432 (save-excursion
23433 (and (outline-next-heading)
23434 (org-flag-heading nil))))
23435 (outline-flag-region (max (point-min) (1- (point)))
23436 (save-excursion (outline-end-of-heading) (point))
23437 flag))))
23439 (defun org-get-next-sibling ()
23440 "Move to next heading of the same level, and return point.
23441 If there is no such heading, return nil.
23442 This is like outline-next-sibling, but invisible headings are ok."
23443 (let ((level (funcall outline-level)))
23444 (outline-next-heading)
23445 (while (and (not (eobp)) (> (funcall outline-level) level))
23446 (outline-next-heading))
23447 (if (or (eobp) (< (funcall outline-level) level))
23449 (point))))
23451 (defun org-get-last-sibling ()
23452 "Move to previous heading of the same level, and return point.
23453 If there is no such heading, return nil."
23454 (let ((opoint (point))
23455 (level (funcall outline-level)))
23456 (outline-previous-heading)
23457 (when (and (/= (point) opoint) (outline-on-heading-p t))
23458 (while (and (> (funcall outline-level) level)
23459 (not (bobp)))
23460 (outline-previous-heading))
23461 (if (< (funcall outline-level) level)
23463 (point)))))
23465 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23466 "Goto to the end of a subtree."
23467 ;; This contains an exact copy of the original function, but it uses
23468 ;; `org-back-to-heading', to make it work also in invisible
23469 ;; trees. And is uses an invisible-ok argument.
23470 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23471 ;; Furthermore, when used inside Org, finding the end of a large subtree
23472 ;; with many children and grandchildren etc, this can be much faster
23473 ;; than the outline version.
23474 (org-back-to-heading invisible-ok)
23475 (let ((first t)
23476 (level (funcall outline-level)))
23477 (if (and (derived-mode-p 'org-mode) (< level 1000))
23478 ;; A true heading (not a plain list item), in Org-mode
23479 ;; This means we can easily find the end by looking
23480 ;; only for the right number of stars. Using a regexp to do
23481 ;; this is so much faster than using a Lisp loop.
23482 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23483 (forward-char 1)
23484 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23485 ;; something else, do it the slow way
23486 (while (and (not (eobp))
23487 (or first (> (funcall outline-level) level)))
23488 (setq first nil)
23489 (outline-next-heading)))
23490 (unless to-heading
23491 (if (memq (preceding-char) '(?\n ?\^M))
23492 (progn
23493 ;; Go to end of line before heading
23494 (forward-char -1)
23495 (if (memq (preceding-char) '(?\n ?\^M))
23496 ;; leave blank line before heading
23497 (forward-char -1))))))
23498 (point))
23500 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23501 "Use Org version in org-mode, for dramatic speed-up."
23502 (if (derived-mode-p 'org-mode)
23503 (progn
23504 (org-end-of-subtree nil t)
23505 (unless (eobp) (backward-char 1)))
23506 ad-do-it))
23508 (defun org-end-of-meta-data-and-drawers ()
23509 "Jump to the first text after meta data and drawers in the current entry.
23510 This will move over empty lines, lines with planning time stamps,
23511 clocking lines, and drawers."
23512 (org-back-to-heading t)
23513 (let ((end (save-excursion (outline-next-heading) (point)))
23514 (re (concat "\\(" org-drawer-regexp "\\)"
23515 "\\|" "[ \t]*" org-keyword-time-regexp)))
23516 (forward-line 1)
23517 (while (re-search-forward re end t)
23518 (if (not (match-end 1))
23519 ;; empty or planning line
23520 (forward-line 1)
23521 ;; a drawer, find the end
23522 (re-search-forward "^[ \t]*:END:" end 'move)
23523 (forward-line 1)))
23524 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23525 (point)))
23527 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23528 "Move forward to the ARG'th subheading at same level as this one.
23529 Stop at the first and last subheadings of a superior heading.
23530 Normally this only looks at visible headings, but when INVISIBLE-OK is
23531 non-nil it will also look at invisible ones."
23532 (interactive "p")
23533 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23534 (if (and arg (< arg 0))
23535 (goto-char (point-min))
23536 (outline-next-heading))
23537 (org-at-heading-p)
23538 (let ((level (- (match-end 0) (match-beginning 0) 1))
23539 (f (if (and arg (< arg 0))
23540 're-search-backward
23541 're-search-forward))
23542 (count (if arg (abs arg) 1))
23543 (result (point)))
23544 (while (and (prog1 (> count 0)
23545 (forward-char (if (and arg (< arg 0)) -1 1)))
23546 (funcall f org-outline-regexp-bol nil 'move))
23547 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23548 (cond ((< l level) (setq count 0))
23549 ((and (= l level)
23550 (or invisible-ok
23551 (progn
23552 (goto-char (line-beginning-position))
23553 (not (outline-invisible-p)))))
23554 (setq count (1- count))
23555 (when (eq l level)
23556 (setq result (point)))))))
23557 (goto-char result))
23558 (beginning-of-line 1)))
23560 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23561 "Move backward to the ARG'th subheading at same level as this one.
23562 Stop at the first and last subheadings of a superior heading."
23563 (interactive "p")
23564 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23566 (defun org-next-block (arg &optional backward block-regexp)
23567 "Jump to the next block.
23568 With a prefix argument ARG, jump forward ARG many source blocks.
23569 When BACKWARD is non-nil, jump to the previous block.
23570 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23571 (interactive "p")
23572 (let ((re (or block-regexp org-block-regexp))
23573 (re-search-fn (or (and backward 're-search-backward)
23574 're-search-forward)))
23575 (if (looking-at re) (forward-char 1))
23576 (condition-case nil
23577 (funcall re-search-fn re nil nil arg)
23578 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23579 (goto-char (match-beginning 0)) (org-show-context)))
23581 (defun org-previous-block (arg &optional block-regexp)
23582 "Jump to the previous block.
23583 With a prefix argument ARG, jump backward ARG many source blocks.
23584 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23585 (interactive "p")
23586 (org-next-block arg t block-regexp))
23588 (defun org-forward-paragraph ()
23589 "Move forward to beginning of next paragraph or equivalent.
23591 The function moves point to the beginning of the next visible
23592 structural element, which can be a paragraph, a table, a list
23593 item, etc. It also provides some special moves for convenience:
23595 - On an affiliated keyword, jump to the beginning of the
23596 relative element.
23597 - On an item or a footnote definition, move to the second
23598 element inside, if any.
23599 - On a table or a property drawer, jump after it.
23600 - On a verse or source block, stop after blank lines."
23601 (interactive)
23602 (when (eobp) (user-error "Cannot move further down"))
23603 (let* ((deactivate-mark nil)
23604 (element (org-element-at-point))
23605 (type (org-element-type element))
23606 (post-affiliated (org-element-property :post-affiliated element))
23607 (contents-begin (org-element-property :contents-begin element))
23608 (contents-end (org-element-property :contents-end element))
23609 (end (let ((end (org-element-property :end element)) (parent element))
23610 (while (and (setq parent (org-element-property :parent parent))
23611 (= (org-element-property :contents-end parent) end))
23612 (setq end (org-element-property :end parent)))
23613 end)))
23614 (cond ((not element)
23615 (skip-chars-forward " \r\t\n")
23616 (or (eobp) (beginning-of-line)))
23617 ;; On affiliated keywords, move to element's beginning.
23618 ((and post-affiliated (< (point) post-affiliated))
23619 (goto-char post-affiliated))
23620 ;; At a table row, move to the end of the table. Similarly,
23621 ;; at a node property, move to the end of the property
23622 ;; drawer.
23623 ((memq type '(node-property table-row))
23624 (goto-char (org-element-property
23625 :end (org-element-property :parent element))))
23626 ((memq type '(property-drawer table)) (goto-char end))
23627 ;; Consider blank lines as separators in verse and source
23628 ;; blocks to ease editing.
23629 ((memq type '(src-block verse-block))
23630 (when (eq type 'src-block)
23631 (setq contents-end
23632 (save-excursion (goto-char end)
23633 (skip-chars-backward " \r\t\n")
23634 (line-beginning-position))))
23635 (beginning-of-line)
23636 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23637 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23638 (goto-char end)
23639 (skip-chars-forward " \r\t\n")
23640 (if (= (point) contents-end) (goto-char end)
23641 (beginning-of-line))))
23642 ;; With no contents, just skip element.
23643 ((not contents-begin) (goto-char end))
23644 ;; If contents are invisible, skip the element altogether.
23645 ((outline-invisible-p (line-end-position))
23646 (case type
23647 (headline
23648 (org-with-limited-levels (outline-next-visible-heading 1)))
23649 ;; At a plain list, make sure we move to the next item
23650 ;; instead of skipping the whole list.
23651 (plain-list (forward-char)
23652 (org-forward-paragraph))
23653 (otherwise (goto-char end))))
23654 ((>= (point) contents-end) (goto-char end))
23655 ((>= (point) contents-begin)
23656 ;; This can only happen on paragraphs and plain lists.
23657 (case type
23658 (paragraph (goto-char end))
23659 ;; At a plain list, try to move to second element in
23660 ;; first item, if possible.
23661 (plain-list (end-of-line)
23662 (org-forward-paragraph))))
23663 ;; When contents start on the middle of a line (e.g. in
23664 ;; items and footnote definitions), try to reach first
23665 ;; element starting after current line.
23666 ((> (line-end-position) contents-begin)
23667 (end-of-line)
23668 (org-forward-paragraph))
23669 (t (goto-char contents-begin)))))
23671 (defun org-backward-paragraph ()
23672 "Move backward to start of previous paragraph or equivalent.
23674 The function moves point to the beginning of the current
23675 structural element, which can be a paragraph, a table, a list
23676 item, etc., or to the beginning of the previous visible one if
23677 point is already there. It also provides some special moves for
23678 convenience:
23680 - On an affiliated keyword, jump to the first one.
23681 - On a table or a property drawer, move to its beginning.
23682 - On a verse or source block, stop before blank lines."
23683 (interactive)
23684 (when (bobp) (user-error "Cannot move further up"))
23685 (let* ((deactivate-mark nil)
23686 (element (org-element-at-point))
23687 (type (org-element-type element))
23688 (contents-begin (org-element-property :contents-begin element))
23689 (contents-end (org-element-property :contents-end element))
23690 (post-affiliated (org-element-property :post-affiliated element))
23691 (begin (org-element-property :begin element)))
23692 (cond
23693 ((not element) (goto-char (point-min)))
23694 ((= (point) begin)
23695 (backward-char)
23696 (org-backward-paragraph))
23697 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23698 ((memq type '(node-property table-row))
23699 (goto-char (org-element-property
23700 :post-affiliated (org-element-property :parent element))))
23701 ((memq type '(property-drawer table)) (goto-char begin))
23702 ((memq type '(src-block verse-block))
23703 (when (eq type 'src-block)
23704 (setq contents-begin
23705 (save-excursion (goto-char begin) (forward-line) (point))))
23706 (if (= (point) contents-begin) (goto-char post-affiliated)
23707 ;; Inside a verse block, see blank lines as paragraph
23708 ;; separators.
23709 (let ((origin (point)))
23710 (skip-chars-backward " \r\t\n" contents-begin)
23711 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23712 (skip-chars-forward " \r\t\n" origin)
23713 (if (= (point) origin) (goto-char contents-begin)
23714 (beginning-of-line))))))
23715 ((not contents-begin) (goto-char (or post-affiliated begin)))
23716 ((eq type 'paragraph)
23717 (goto-char contents-begin)
23718 ;; When at first paragraph in an item or a footnote definition,
23719 ;; move directly to beginning of line.
23720 (let ((parent-contents
23721 (org-element-property
23722 :contents-begin (org-element-property :parent element))))
23723 (when (and parent-contents (= parent-contents contents-begin))
23724 (beginning-of-line))))
23725 ;; At the end of a greater element, move to the beginning of the
23726 ;; last element within.
23727 ((>= (point) contents-end)
23728 (goto-char (1- contents-end))
23729 (org-backward-paragraph))
23730 (t (goto-char (or post-affiliated begin))))
23731 ;; Ensure we never leave point invisible.
23732 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23734 (defun org-forward-element ()
23735 "Move forward by one element.
23736 Move to the next element at the same level, when possible."
23737 (interactive)
23738 (cond ((eobp) (user-error "Cannot move further down"))
23739 ((org-with-limited-levels (org-at-heading-p))
23740 (let ((origin (point)))
23741 (goto-char (org-end-of-subtree nil t))
23742 (unless (org-with-limited-levels (org-at-heading-p))
23743 (goto-char origin)
23744 (user-error "Cannot move further down"))))
23746 (let* ((elem (org-element-at-point))
23747 (end (org-element-property :end elem))
23748 (parent (org-element-property :parent elem)))
23749 (cond ((and parent (= (org-element-property :contents-end parent) end))
23750 (goto-char (org-element-property :end parent)))
23751 ((integer-or-marker-p end) (goto-char end))
23752 (t (message "No element at point")))))))
23754 (defun org-backward-element ()
23755 "Move backward by one element.
23756 Move to the previous element at the same level, when possible."
23757 (interactive)
23758 (cond ((bobp) (user-error "Cannot move further up"))
23759 ((org-with-limited-levels (org-at-heading-p))
23760 ;; At a headline, move to the previous one, if any, or stay
23761 ;; here.
23762 (let ((origin (point)))
23763 (org-with-limited-levels (org-backward-heading-same-level 1))
23764 ;; When current headline has no sibling above, move to its
23765 ;; parent.
23766 (when (= (point) origin)
23767 (or (org-with-limited-levels (org-up-heading-safe))
23768 (progn (goto-char origin)
23769 (user-error "Cannot move further up"))))))
23771 (let* ((elem (org-element-at-point))
23772 (beg (org-element-property :begin elem)))
23773 (cond
23774 ;; Move to beginning of current element if point isn't
23775 ;; there already.
23776 ((null beg) (message "No element at point"))
23777 ((/= (point) beg) (goto-char beg))
23778 (t (goto-char beg)
23779 (skip-chars-backward " \r\t\n")
23780 (unless (bobp)
23781 (let ((prev (org-element-at-point)))
23782 (goto-char (org-element-property :begin prev))
23783 (while (and (setq prev (org-element-property :parent prev))
23784 (<= (org-element-property :end prev) beg))
23785 (goto-char (org-element-property :begin prev)))))))))))
23787 (defun org-up-element ()
23788 "Move to upper element."
23789 (interactive)
23790 (if (org-with-limited-levels (org-at-heading-p))
23791 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23792 (let* ((elem (org-element-at-point))
23793 (parent (org-element-property :parent elem)))
23794 (if parent (goto-char (org-element-property :begin parent))
23795 (if (org-with-limited-levels (org-before-first-heading-p))
23796 (user-error "No surrounding element")
23797 (org-with-limited-levels (org-back-to-heading)))))))
23799 (defvar org-element-greater-elements)
23800 (defun org-down-element ()
23801 "Move to inner element."
23802 (interactive)
23803 (let ((element (org-element-at-point)))
23804 (cond
23805 ((memq (org-element-type element) '(plain-list table))
23806 (goto-char (org-element-property :contents-begin element))
23807 (forward-char))
23808 ((memq (org-element-type element) org-element-greater-elements)
23809 ;; If contents are hidden, first disclose them.
23810 (when (outline-invisible-p (line-end-position)) (org-cycle))
23811 (goto-char (or (org-element-property :contents-begin element)
23812 (user-error "No content for this element"))))
23813 (t (user-error "No inner element")))))
23815 (defun org-drag-element-backward ()
23816 "Move backward element at point."
23817 (interactive)
23818 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23819 (let* ((elem (org-element-at-point))
23820 (prev-elem
23821 (save-excursion
23822 (goto-char (org-element-property :begin elem))
23823 (skip-chars-backward " \r\t\n")
23824 (unless (bobp)
23825 (let* ((beg (org-element-property :begin elem))
23826 (prev (org-element-at-point))
23827 (up prev))
23828 (while (and (setq up (org-element-property :parent up))
23829 (<= (org-element-property :end prev) beg))
23830 (setq prev up))
23831 prev)))))
23832 ;; Error out if no previous element or previous element is
23833 ;; a parent of the current one.
23834 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23835 (user-error "Cannot drag element backward")
23836 (let ((pos (point)))
23837 (org-element-swap-A-B prev-elem elem)
23838 (goto-char (+ (org-element-property :begin prev-elem)
23839 (- pos (org-element-property :begin elem)))))))))
23841 (defun org-drag-element-forward ()
23842 "Move forward element at point."
23843 (interactive)
23844 (let* ((pos (point))
23845 (elem (org-element-at-point)))
23846 (when (= (point-max) (org-element-property :end elem))
23847 (user-error "Cannot drag element forward"))
23848 (goto-char (org-element-property :end elem))
23849 (let ((next-elem (org-element-at-point)))
23850 (when (or (org-element-nested-p elem next-elem)
23851 (and (eq (org-element-type next-elem) 'headline)
23852 (not (eq (org-element-type elem) 'headline))))
23853 (goto-char pos)
23854 (user-error "Cannot drag element forward"))
23855 ;; Compute new position of point: it's shifted by NEXT-ELEM
23856 ;; body's length (without final blanks) and by the length of
23857 ;; blanks between ELEM and NEXT-ELEM.
23858 (let ((size-next (- (save-excursion
23859 (goto-char (org-element-property :end next-elem))
23860 (skip-chars-backward " \r\t\n")
23861 (forward-line)
23862 ;; Small correction if buffer doesn't end
23863 ;; with a newline character.
23864 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23865 (org-element-property :begin next-elem)))
23866 (size-blank (- (org-element-property :end elem)
23867 (save-excursion
23868 (goto-char (org-element-property :end elem))
23869 (skip-chars-backward " \r\t\n")
23870 (forward-line)
23871 (point)))))
23872 (org-element-swap-A-B elem next-elem)
23873 (goto-char (+ pos size-next size-blank))))))
23875 (defun org-drag-line-forward (arg)
23876 "Drag the line at point ARG lines forward."
23877 (interactive "p")
23878 (dotimes (n (abs arg))
23879 (let ((c (current-column)))
23880 (if (< 0 arg)
23881 (progn
23882 (beginning-of-line 2)
23883 (transpose-lines 1)
23884 (beginning-of-line 0))
23885 (transpose-lines 1)
23886 (beginning-of-line -1))
23887 (org-move-to-column c))))
23889 (defun org-drag-line-backward (arg)
23890 "Drag the line at point ARG lines backward."
23891 (interactive "p")
23892 (org-drag-line-forward (- arg)))
23894 (defun org-mark-element ()
23895 "Put point at beginning of this element, mark at end.
23897 Interactively, if this command is repeated or (in Transient Mark
23898 mode) if the mark is active, it marks the next element after the
23899 ones already marked."
23900 (interactive)
23901 (let (deactivate-mark)
23902 (if (and (org-called-interactively-p 'any)
23903 (or (and (eq last-command this-command) (mark t))
23904 (and transient-mark-mode mark-active)))
23905 (set-mark
23906 (save-excursion
23907 (goto-char (mark))
23908 (goto-char (org-element-property :end (org-element-at-point)))))
23909 (let ((element (org-element-at-point)))
23910 (end-of-line)
23911 (push-mark (org-element-property :end element) t t)
23912 (goto-char (org-element-property :begin element))))))
23914 (defun org-narrow-to-element ()
23915 "Narrow buffer to current element."
23916 (interactive)
23917 (let ((elem (org-element-at-point)))
23918 (cond
23919 ((eq (car elem) 'headline)
23920 (narrow-to-region
23921 (org-element-property :begin elem)
23922 (org-element-property :end elem)))
23923 ((memq (car elem) org-element-greater-elements)
23924 (narrow-to-region
23925 (org-element-property :contents-begin elem)
23926 (org-element-property :contents-end elem)))
23928 (narrow-to-region
23929 (org-element-property :begin elem)
23930 (org-element-property :end elem))))))
23932 (defun org-transpose-element ()
23933 "Transpose current and previous elements, keeping blank lines between.
23934 Point is moved after both elements."
23935 (interactive)
23936 (org-skip-whitespace)
23937 (let ((end (org-element-property :end (org-element-at-point))))
23938 (org-drag-element-backward)
23939 (goto-char end)))
23941 (defun org-unindent-buffer ()
23942 "Un-indent the visible part of the buffer.
23943 Relative indentation (between items, inside blocks, etc.) isn't
23944 modified."
23945 (interactive)
23946 (unless (eq major-mode 'org-mode)
23947 (user-error "Cannot un-indent a buffer not in Org mode"))
23948 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23949 unindent-tree ; For byte-compiler.
23950 (unindent-tree
23951 (function
23952 (lambda (contents)
23953 (mapc
23954 (lambda (element)
23955 (if (memq (org-element-type element) '(headline section))
23956 (funcall unindent-tree (org-element-contents element))
23957 (save-excursion
23958 (save-restriction
23959 (narrow-to-region
23960 (org-element-property :begin element)
23961 (org-element-property :end element))
23962 (org-do-remove-indentation)))))
23963 (reverse contents))))))
23964 (funcall unindent-tree (org-element-contents parse-tree))))
23966 (defun org-show-subtree ()
23967 "Show everything after this heading at deeper levels."
23968 (interactive)
23969 (outline-flag-region
23970 (point)
23971 (save-excursion
23972 (org-end-of-subtree t t))
23973 nil))
23975 (defun org-show-entry ()
23976 "Show the body directly following this heading.
23977 Show the heading too, if it is currently invisible."
23978 (interactive)
23979 (save-excursion
23980 (condition-case nil
23981 (progn
23982 (org-back-to-heading t)
23983 (outline-flag-region
23984 (max (point-min) (1- (point)))
23985 (save-excursion
23986 (if (re-search-forward
23987 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23988 (match-beginning 1)
23989 (point-max)))
23990 nil)
23991 (org-cycle-hide-drawers 'children))
23992 (error nil))))
23994 (defun org-make-options-regexp (kwds &optional extra)
23995 "Make a regular expression for keyword lines."
23996 (concat
23997 "^[ \t]*#\\+\\("
23998 (mapconcat 'regexp-quote kwds "\\|")
23999 (if extra (concat "\\|" extra))
24000 "\\):[ \t]*\\(.*\\)"))
24002 ;; Make isearch reveal the necessary context
24003 (defun org-isearch-end ()
24004 "Reveal context after isearch exits."
24005 (when isearch-success ; only if search was successful
24006 (if (featurep 'xemacs)
24007 ;; Under XEmacs, the hook is run in the correct place,
24008 ;; we directly show the context.
24009 (org-show-context 'isearch)
24010 ;; In Emacs the hook runs *before* restoring the overlays.
24011 ;; So we have to use a one-time post-command-hook to do this.
24012 ;; (Emacs 22 has a special variable, see function `org-mode')
24013 (unless (and (boundp 'isearch-mode-end-hook-quit)
24014 isearch-mode-end-hook-quit)
24015 ;; Only when the isearch was not quitted.
24016 (org-add-hook 'post-command-hook 'org-isearch-post-command
24017 'append 'local)))
24018 (org-fix-ellipsis-at-bol)))
24020 (defun org-isearch-post-command ()
24021 "Remove self from hook, and show context."
24022 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24023 (org-show-context 'isearch))
24026 ;;;; Integration with and fixes for other packages
24028 ;;; Imenu support
24030 (defvar org-imenu-markers nil
24031 "All markers currently used by Imenu.")
24032 (make-variable-buffer-local 'org-imenu-markers)
24034 (defun org-imenu-new-marker (&optional pos)
24035 "Return a new marker for use by Imenu, and remember the marker."
24036 (let ((m (make-marker)))
24037 (move-marker m (or pos (point)))
24038 (push m org-imenu-markers)
24041 (defun org-imenu-get-tree ()
24042 "Produce the index for Imenu."
24043 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24044 (setq org-imenu-markers nil)
24045 (let* ((n org-imenu-depth)
24046 (re (concat "^" (org-get-limited-outline-regexp)))
24047 (subs (make-vector (1+ n) nil))
24048 (last-level 0)
24049 m level head0 head)
24050 (save-excursion
24051 (save-restriction
24052 (widen)
24053 (goto-char (point-max))
24054 (while (re-search-backward re nil t)
24055 (setq level (org-reduced-level (funcall outline-level)))
24056 (when (and (<= level n)
24057 (looking-at org-complex-heading-regexp)
24058 (setq head0 (org-match-string-no-properties 4)))
24059 (setq head (org-link-display-format head0)
24060 m (org-imenu-new-marker))
24061 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24062 (if (>= level last-level)
24063 (push (cons head m) (aref subs level))
24064 (push (cons head (aref subs (1+ level))) (aref subs level))
24065 (loop for i from (1+ level) to n do (aset subs i nil)))
24066 (setq last-level level)))))
24067 (aref subs 1)))
24069 (eval-after-load "imenu"
24070 '(progn
24071 (add-hook 'imenu-after-jump-hook
24072 (lambda ()
24073 (if (derived-mode-p 'org-mode)
24074 (org-show-context 'org-goto))))))
24076 (defun org-link-display-format (link)
24077 "Replace a link with its the description.
24078 If there is no description, use the link target."
24079 (save-match-data
24080 (if (string-match org-bracket-link-analytic-regexp link)
24081 (replace-match (if (match-end 5)
24082 (match-string 5 link)
24083 (concat (match-string 1 link)
24084 (match-string 3 link)))
24085 nil t link)
24086 link)))
24088 (defun org-toggle-link-display ()
24089 "Toggle the literal or descriptive display of links."
24090 (interactive)
24091 (if org-descriptive-links
24092 (progn (org-remove-from-invisibility-spec '(org-link))
24093 (org-restart-font-lock)
24094 (setq org-descriptive-links nil))
24095 (progn (add-to-invisibility-spec '(org-link))
24096 (org-restart-font-lock)
24097 (setq org-descriptive-links t))))
24099 ;; Speedbar support
24101 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24102 "Overlay marking the agenda restriction line in speedbar.")
24103 (overlay-put org-speedbar-restriction-lock-overlay
24104 'face 'org-agenda-restriction-lock)
24105 (overlay-put org-speedbar-restriction-lock-overlay
24106 'help-echo "Agendas are currently limited to this item.")
24107 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24109 (defun org-speedbar-set-agenda-restriction ()
24110 "Restrict future agenda commands to the location at point in speedbar.
24111 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24112 (interactive)
24113 (require 'org-agenda)
24114 (let (p m tp np dir txt)
24115 (cond
24116 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24117 'org-imenu t))
24118 (setq m (get-text-property p 'org-imenu-marker))
24119 (with-current-buffer (marker-buffer m)
24120 (goto-char m)
24121 (org-agenda-set-restriction-lock 'subtree)))
24122 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24123 'speedbar-function 'speedbar-find-file))
24124 (setq tp (previous-single-property-change
24125 (1+ p) 'speedbar-function)
24126 np (next-single-property-change
24127 tp 'speedbar-function)
24128 dir (speedbar-line-directory)
24129 txt (buffer-substring-no-properties (or tp (point-min))
24130 (or np (point-max))))
24131 (with-current-buffer (find-file-noselect
24132 (let ((default-directory dir))
24133 (expand-file-name txt)))
24134 (unless (derived-mode-p 'org-mode)
24135 (user-error "Cannot restrict to non-Org-mode file"))
24136 (org-agenda-set-restriction-lock 'file)))
24137 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24138 (move-overlay org-speedbar-restriction-lock-overlay
24139 (point-at-bol) (point-at-eol))
24140 (setq current-prefix-arg nil)
24141 (org-agenda-maybe-redo)))
24143 (defvar speedbar-file-key-map)
24144 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24145 (eval-after-load "speedbar"
24146 '(progn
24147 (speedbar-add-supported-extension ".org")
24148 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24149 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24150 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24151 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24152 (add-hook 'speedbar-visiting-tag-hook
24153 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24155 ;;; Fixes and Hacks for problems with other packages
24157 (defun org-mode-flyspell-verify ()
24158 "Function used for `flyspell-generic-check-word-predicate'."
24159 (if (org-at-heading-p)
24160 ;; At a headline or an inlinetask, check title only. This is
24161 ;; faster than relying on `org-element-at-point'.
24162 (and (save-excursion (beginning-of-line)
24163 (and (let ((case-fold-search t))
24164 (not (looking-at "\\*+ END[ \t]*$")))
24165 (looking-at org-complex-heading-regexp)))
24166 (match-beginning 4)
24167 (>= (point) (match-beginning 4))
24168 (or (not (match-beginning 5))
24169 (< (point) (match-beginning 5))))
24170 (let* ((element (org-element-at-point))
24171 (post-affiliated (org-element-property :post-affiliated element))
24172 (object-check
24173 (function
24174 ;; Non-nil if checks can be done for object at point.
24175 (lambda ()
24176 (let ((object (save-excursion
24177 (when (org-looking-at-p "\\>") (backward-char))
24178 (org-element-context element))))
24179 (case (org-element-type object)
24180 ;; Prevent checks in links due to keybinding conflict
24181 ;; with Flyspell.
24182 ((code entity export-snippet inline-babel-call
24183 inline-src-block line-break latex-fragment link macro
24184 statistics-cookie target timestamp verbatim)
24185 nil)
24186 (footnote-reference
24187 ;; Only in inline footnotes, within the definition.
24188 (and (eq (org-element-property :type object) 'inline)
24189 (< (save-excursion
24190 (goto-char (org-element-property :begin object))
24191 (search-forward ":" nil t 2))
24192 (point))))
24193 (otherwise t)))))))
24194 (cond
24195 ;; Ignore checks in all affiliated keywords but captions.
24196 ((and post-affiliated (< (point) post-affiliated))
24197 (and (save-excursion
24198 (beginning-of-line)
24199 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24200 (> (point) (match-end 0))
24201 (funcall object-check)))
24202 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24203 ((and org-log-into-drawer
24204 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24205 (parent element))
24206 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24207 (setq parent (org-element-property :parent parent)))
24208 (and parent
24209 (eq (compare-strings
24210 log nil nil
24211 (org-element-property :drawer-name parent) nil nil t)
24212 t))))
24213 nil)
24215 (case (org-element-type element)
24216 ((comment quote-section) t)
24217 (comment-block
24218 ;; Allow checks between block markers, not on them.
24219 (and (> (line-beginning-position)
24220 (org-element-property :post-affiliated element))
24221 (save-excursion
24222 (end-of-line)
24223 (skip-chars-forward " \r\t\n")
24224 (< (point) (org-element-property :end element)))))
24225 ;; Arbitrary list of keywords where checks are meaningful.
24226 ;; Make sure point is on the value part of the element.
24227 (keyword
24228 (and (member (org-element-property :key element)
24229 '("DESCRIPTION" "TITLE"))
24230 (< (save-excursion
24231 (beginning-of-line) (search-forward ":") (point))
24232 (point))))
24233 ;; Check is globally allowed in paragraphs verse blocks and
24234 ;; table rows (after affiliated keywords) but some objects
24235 ;; must not be affected.
24236 ((paragraph table-row verse-block)
24237 (and (>= (point) (org-element-property :contents-begin element))
24238 (< (point) (org-element-property :contents-end element))
24239 (funcall object-check)))))))))
24240 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24242 (defun org-remove-flyspell-overlays-in (beg end)
24243 "Remove flyspell overlays in region."
24244 (and (org-bound-and-true-p flyspell-mode)
24245 (fboundp 'flyspell-delete-region-overlays)
24246 (flyspell-delete-region-overlays beg end)))
24248 (defvar flyspell-delayed-commands)
24249 (eval-after-load "flyspell"
24250 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24252 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24253 (eval-after-load "bookmark"
24254 '(if (boundp 'bookmark-after-jump-hook)
24255 ;; We can use the hook
24256 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24257 ;; Hook not available, use advice
24258 (defadvice bookmark-jump (after org-make-visible activate)
24259 "Make the position visible."
24260 (org-bookmark-jump-unhide))))
24262 ;; Make sure saveplace shows the location if it was hidden
24263 (eval-after-load "saveplace"
24264 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24265 "Make the position visible."
24266 (org-bookmark-jump-unhide)))
24268 ;; Make sure ecb shows the location if it was hidden
24269 (eval-after-load "ecb"
24270 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24271 "Make hierarchy visible when jumping into location from ECB tree buffer."
24272 (if (derived-mode-p 'org-mode)
24273 (org-show-context))))
24275 (defun org-bookmark-jump-unhide ()
24276 "Unhide the current position, to show the bookmark location."
24277 (and (derived-mode-p 'org-mode)
24278 (or (outline-invisible-p)
24279 (save-excursion (goto-char (max (point-min) (1- (point))))
24280 (outline-invisible-p)))
24281 (org-show-context 'bookmark-jump)))
24283 ;; Make session.el ignore our circular variable
24284 (defvar session-globals-exclude)
24285 (eval-after-load "session"
24286 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24288 ;;;; Finish up
24290 (provide 'org)
24292 (run-hooks 'org-load-hook)
24294 ;;; org.el ends here