Fix `org-open-at-point' in comments
[org-mode.git] / lisp / org.el
blob52f7fbfba7217d8b5fbe0e98ece5b7991a4712ce
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 in the echo area.
301 With prefix argument HERE, insert it at point.
302 When FULL is non-nil, use a verbose version string.
303 When MESSAGE is non-nil, display a message with the version."
304 (interactive "P")
305 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
306 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
307 (load-suffixes (list ".el"))
308 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
309 (org-trash (or
310 (and (fboundp 'org-release) (fboundp 'org-git-version))
311 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
312 (load-suffixes save-load-suffixes)
313 (org-version (org-release))
314 (git-version (org-git-version))
315 (version (format "Org-mode version %s (%s @ %s)"
316 org-version
317 git-version
318 (if org-install-dir
319 (if (string= org-dir org-install-dir)
320 org-install-dir
321 (concat "mixed installation! " org-install-dir " and " org-dir))
322 "org-loaddefs.el can not be found!")))
323 (version1 (if full version org-version)))
324 (if (org-called-interactively-p 'interactive)
325 (if here
326 (insert version)
327 (message version))
328 (if message (message version1))
329 version1)))
331 (defconst org-version (org-version))
334 ;;; Syntax Constants
336 ;;;; Block
338 (defconst org-block-regexp
339 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
340 "Regular expression for hiding blocks.")
342 (defconst org-dblock-start-re
343 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
344 "Matches the start line of a dynamic block, with parameters.")
346 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
347 "Matches the end of a dynamic block.")
349 ;;;; Clock and Planning
351 (defconst org-clock-string "CLOCK:"
352 "String used as prefix for timestamps clocking work hours on an item.")
354 (defconst org-closed-string "CLOSED:"
355 "String used as the prefix for timestamps logging closing a TODO entry.")
357 (defconst org-deadline-string "DEADLINE:"
358 "String to mark deadline entries.
359 A deadline is this string, followed by a time stamp. Should be a word,
360 terminated by a colon. You can insert a schedule keyword and
361 a timestamp with \\[org-deadline].")
363 (defconst org-scheduled-string "SCHEDULED:"
364 "String to mark scheduled TODO entries.
365 A schedule is this string, followed by a time stamp. Should be a word,
366 terminated by a colon. You can insert a schedule keyword and
367 a timestamp with \\[org-schedule].")
369 (defconst org-planning-or-clock-line-re
370 (concat "^[ \t]*"
371 (regexp-opt
372 (list org-clock-string org-closed-string org-deadline-string
373 org-scheduled-string)
375 "Matches a line with planning or clock info.
376 Matched keyword is in group 1.")
378 ;;;; Drawer
380 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
381 "Matches first or last line of a hidden block.
382 Group 1 contains drawer's name or \"END\".")
384 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
385 "Regular expression matching the first line of a property drawer.")
387 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
388 "Regular expression matching the last line of a property drawer.")
390 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
391 "Regular expression matching the first line of a clock drawer.")
393 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
394 "Regular expression matching the last line of a clock drawer.")
396 (defconst org-property-drawer-re
397 (concat "\\(" org-property-start-re "\\)[^\000]*?\\("
398 org-property-end-re "\\)\n?")
399 "Matches an entire property drawer.")
401 (defconst org-clock-drawer-re
402 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
403 org-clock-drawer-end-re "\\)\n?")
404 "Matches an entire clock drawer.")
406 ;;;; Headline
408 (defconst org-heading-keyword-regexp-format
409 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
410 "Printf format for a regexp matching a headline with some keyword.
411 This regexp will match the headline of any node which has the
412 exact keyword that is put into the format. The keyword isn't in
413 any group by default, but the stars and the body are.")
415 (defconst org-heading-keyword-maybe-regexp-format
416 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
417 "Printf format for a regexp matching a headline, possibly with some keyword.
418 This regexp can match any headline with the specified keyword, or
419 without a keyword. The keyword isn't in any group by default,
420 but the stars and the body are.")
422 (defconst org-archive-tag "ARCHIVE"
423 "The tag that marks a subtree as archived.
424 An archived subtree does not open during visibility cycling, and does
425 not contribute to the agenda listings.")
427 (defconst org-comment-string "COMMENT"
428 "Entries starting with this keyword will never be exported.
429 An entry can be toggled between COMMENT and normal with
430 \\[org-toggle-comment].")
433 ;;;; LaTeX Environments and Fragments
435 (defconst org-latex-regexps
436 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
437 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
438 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
439 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
440 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
441 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
442 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
443 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
444 "Regular expressions for matching embedded LaTeX.")
446 ;;;; Node Property
448 (defconst org-effort-property "Effort"
449 "The property that is being used to keep track of effort estimates.
450 Effort estimates given in this property need to have the format H:MM.")
452 ;;;; Table
454 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
455 "Detect an org-type or table-type table.")
457 (defconst org-table-line-regexp "^[ \t]*|"
458 "Detect an org-type table line.")
460 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
461 "Detect an org-type table line.")
463 (defconst org-table-hline-regexp "^[ \t]*|-"
464 "Detect an org-type table hline.")
466 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
467 "Detect a table-type table hline.")
469 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
470 "Detect the first line outside a table when searching from within it.
471 This works for both table types.")
473 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
474 "Detect a #+TBLFM line.")
476 ;;;; Timestamp
478 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
479 "Regular expression for fast time stamp matching.")
481 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
482 "Regular expression for fast time stamp matching.")
484 (defconst org-ts-regexp0
485 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
486 "Regular expression matching time strings for analysis.
487 This one does not require the space after the date, so it can be used
488 on a string that terminates immediately after the date.")
490 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
491 "Regular expression matching time strings for analysis.")
493 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
494 "Regular expression matching time stamps, with groups.")
496 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
497 "Regular expression matching time stamps (also [..]), with groups.")
499 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
500 "Regular expression matching a time stamp range.")
502 (defconst org-tr-regexp-both
503 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
504 "Regular expression matching a time stamp range.")
506 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
507 org-ts-regexp "\\)?")
508 "Regular expression matching a time stamp or time stamp range.")
510 (defconst org-tsr-regexp-both
511 (concat org-ts-regexp-both "\\(--?-?"
512 org-ts-regexp-both "\\)?")
513 "Regular expression matching a time stamp or time stamp range.
514 The time stamps may be either active or inactive.")
516 (defconst org-repeat-re
517 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
518 "Regular expression for specifying repeated events.
519 After a match, group 1 contains the repeat expression.")
521 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
522 "Formats for `format-time-string' which are used for time stamps.")
525 ;;; The custom variables
527 (defgroup org nil
528 "Outline-based notes management and organizer."
529 :tag "Org"
530 :group 'outlines
531 :group 'calendar)
533 (defcustom org-mode-hook nil
534 "Mode hook for Org-mode, run after the mode was turned on."
535 :group 'org
536 :type 'hook)
538 (defcustom org-load-hook nil
539 "Hook that is run after org.el has been loaded."
540 :group 'org
541 :type 'hook)
543 (defcustom org-log-buffer-setup-hook nil
544 "Hook that is run after an Org log buffer is created."
545 :group 'org
546 :version "24.1"
547 :type 'hook)
549 (defvar org-modules) ; defined below
550 (defvar org-modules-loaded nil
551 "Have the modules been loaded already?")
553 (defun org-load-modules-maybe (&optional force)
554 "Load all extensions listed in `org-modules'."
555 (when (or force (not org-modules-loaded))
556 (mapc (lambda (ext)
557 (condition-case nil (require ext)
558 (error (message "Problems while trying to load feature `%s'" ext))))
559 org-modules)
560 (setq org-modules-loaded t)))
562 (defun org-set-modules (var value)
563 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
564 (set var value)
565 (when (featurep 'org)
566 (org-load-modules-maybe 'force)
567 (org-element-cache-reset 'all)))
569 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
570 "Modules that should always be loaded together with org.el.
572 If a description starts with <C>, the file is not part of Emacs
573 and loading it will require that you have downloaded and properly
574 installed the Org mode distribution.
576 You can also use this system to load external packages (i.e. neither Org
577 core modules, nor modules from the CONTRIB directory). Just add symbols
578 to the end of the list. If the package is called org-xyz.el, then you need
579 to add the symbol `xyz', and the package must have a call to:
581 \(provide 'org-xyz)
583 For export specific modules, see also `org-export-backends'."
584 :group 'org
585 :set 'org-set-modules
586 :version "24.4"
587 :package-version '(Org . "8.0")
588 :type
589 '(set :greedy t
590 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
591 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
592 (const :tag " crypt: Encryption of subtrees" org-crypt)
593 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
594 (const :tag " docview: Links to doc-view buffers" org-docview)
595 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
596 (const :tag " habit: Track your consistency with habits" org-habit)
597 (const :tag " id: Global IDs for identifying entries" org-id)
598 (const :tag " info: Links to Info nodes" org-info)
599 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
600 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
601 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
602 (const :tag " mouse: Additional mouse support" org-mouse)
603 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
604 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
605 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
607 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
608 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
609 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
610 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
611 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
612 (const :tag "C collector: Collect properties into tables" org-collector)
613 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
614 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
615 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
616 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
617 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
618 (const :tag "C eval: Include command output as text" org-eval)
619 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
620 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
621 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
622 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
623 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
624 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
625 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
626 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
627 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
628 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
629 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
630 (const :tag "C mew: Links to Mew folders/messages" org-mew)
631 (const :tag "C mtags: Support for muse-like tags" org-mtags)
632 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
633 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
634 (const :tag "C registry: A registry for Org-mode links" org-registry)
635 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
636 (const :tag "C secretary: Team management with org-mode" org-secretary)
637 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
638 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
639 (const :tag "C track: Keep up with Org-mode development" org-track)
640 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
641 (const :tag "C vm: Links to VM folders/messages" org-vm)
642 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
643 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
644 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
646 (defvar org-export--registered-backends) ; From ox.el.
647 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
648 (declare-function org-export-backend-name "ox" (backend))
649 (defcustom org-export-backends '(ascii html icalendar latex)
650 "List of export back-ends that should be always available.
652 If a description starts with <C>, the file is not part of Emacs
653 and loading it will require that you have downloaded and properly
654 installed the Org mode distribution.
656 Unlike to `org-modules', libraries in this list will not be
657 loaded along with Org, but only once the export framework is
658 needed.
660 This variable needs to be set before org.el is loaded. If you
661 need to make a change while Emacs is running, use the customize
662 interface or run the following code, where VAL stands for the new
663 value of the variable, after updating it:
665 \(progn
666 \(setq org-export--registered-backends
667 \(org-remove-if-not
668 \(lambda (backend)
669 \(let ((name (org-export-backend-name backend)))
670 \(or (memq name val)
671 \(catch 'parentp
672 \(dolist (b val)
673 \(and (org-export-derived-backend-p b name)
674 \(throw 'parentp t)))))))
675 org-export--registered-backends))
676 \(let ((new-list (mapcar 'org-export-backend-name
677 org-export--registered-backends)))
678 \(dolist (backend val)
679 \(cond
680 \((not (load (format \"ox-%s\" backend) t t))
681 \(message \"Problems while trying to load export back-end `%s'\"
682 backend))
683 \((not (memq backend new-list)) (push backend new-list))))
684 \(set-default 'org-export-backends new-list)))
686 Adding a back-end to this list will also pull the back-end it
687 depends on, if any."
688 :group 'org
689 :group 'org-export
690 :version "24.4"
691 :package-version '(Org . "8.0")
692 :initialize 'custom-initialize-set
693 :set (lambda (var val)
694 (if (not (featurep 'ox)) (set-default var val)
695 ;; Any back-end not required anymore (not present in VAL and not
696 ;; a parent of any back-end in the new value) is removed from the
697 ;; list of registered back-ends.
698 (setq org-export--registered-backends
699 (org-remove-if-not
700 (lambda (backend)
701 (let ((name (org-export-backend-name backend)))
702 (or (memq name val)
703 (catch 'parentp
704 (dolist (b val)
705 (and (org-export-derived-backend-p b name)
706 (throw 'parentp t)))))))
707 org-export--registered-backends))
708 ;; Now build NEW-LIST of both new back-ends and required
709 ;; parents.
710 (let ((new-list (mapcar 'org-export-backend-name
711 org-export--registered-backends)))
712 (dolist (backend val)
713 (cond
714 ((not (load (format "ox-%s" backend) t t))
715 (message "Problems while trying to load export back-end `%s'"
716 backend))
717 ((not (memq backend new-list)) (push backend new-list))))
718 ;; Set VAR to that list with fixed dependencies.
719 (set-default var new-list))))
720 :type '(set :greedy t
721 (const :tag " ascii Export buffer to ASCII format" ascii)
722 (const :tag " beamer Export buffer to Beamer presentation" beamer)
723 (const :tag " html Export buffer to HTML format" html)
724 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
725 (const :tag " latex Export buffer to LaTeX format" latex)
726 (const :tag " man Export buffer to MAN format" man)
727 (const :tag " md Export buffer to Markdown format" md)
728 (const :tag " odt Export buffer to ODT format" odt)
729 (const :tag " org Export buffer to Org format" org)
730 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
731 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
732 (const :tag "C deck Export buffer to deck.js presentations" deck)
733 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
734 (const :tag "C groff Export buffer to Groff format" groff)
735 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
736 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
737 (const :tag "C s5 Export buffer to s5 presentations" s5)
738 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
740 (eval-after-load 'ox
741 '(mapc
742 (lambda (backend)
743 (condition-case nil (require (intern (format "ox-%s" backend)))
744 (error (message "Problems while trying to load export back-end `%s'"
745 backend))))
746 org-export-backends))
748 (defcustom org-support-shift-select nil
749 "Non-nil means make shift-cursor commands select text when possible.
751 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
752 start selecting a region, or enlarge regions started in this way.
753 In Org-mode, in special contexts, these same keys are used for
754 other purposes, important enough to compete with shift selection.
755 Org tries to balance these needs by supporting `shift-select-mode'
756 outside these special contexts, under control of this variable.
758 The default of this variable is nil, to avoid confusing behavior. Shifted
759 cursor keys will then execute Org commands in the following contexts:
760 - on a headline, changing TODO state (left/right) and priority (up/down)
761 - on a time stamp, changing the time
762 - in a plain list item, changing the bullet type
763 - in a property definition line, switching between allowed values
764 - in the BEGIN line of a clock table (changing the time block).
765 Outside these contexts, the commands will throw an error.
767 When this variable is t and the cursor is not in a special
768 context, Org-mode will support shift-selection for making and
769 enlarging regions. To make this more effective, the bullet
770 cycling will no longer happen anywhere in an item line, but only
771 if the cursor is exactly on the bullet.
773 If you set this variable to the symbol `always', then the keys
774 will not be special in headlines, property lines, and item lines,
775 to make shift selection work there as well. If this is what you
776 want, you can use the following alternative commands: `C-c C-t'
777 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
778 can be used to switch TODO sets, `C-c -' to cycle item bullet
779 types, and properties can be edited by hand or in column view.
781 However, when the cursor is on a timestamp, shift-cursor commands
782 will still edit the time stamp - this is just too good to give up.
784 XEmacs user should have this variable set to nil, because
785 `shift-select-mode' is in Emacs 23 or later only."
786 :group 'org
787 :type '(choice
788 (const :tag "Never" nil)
789 (const :tag "When outside special context" t)
790 (const :tag "Everywhere except timestamps" always)))
792 (defcustom org-loop-over-headlines-in-active-region nil
793 "Shall some commands act upon headlines in the active region?
795 When set to `t', some commands will be performed in all headlines
796 within the active region.
798 When set to `start-level', some commands will be performed in all
799 headlines within the active region, provided that these headlines
800 are of the same level than the first one.
802 When set to a string, those commands will be performed on the
803 matching headlines within the active region. Such string must be
804 a tags/property/todo match as it is used in the agenda tags view.
806 The list of commands is: `org-schedule', `org-deadline',
807 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
808 `org-archive-to-archive-sibling'. The archiving commands skip
809 already archived entries."
810 :type '(choice (const :tag "Don't loop" nil)
811 (const :tag "All headlines in active region" t)
812 (const :tag "In active region, headlines at the same level than the first one" start-level)
813 (string :tag "Tags/Property/Todo matcher"))
814 :version "24.1"
815 :group 'org-todo
816 :group 'org-archive)
818 (defgroup org-startup nil
819 "Options concerning startup of Org-mode."
820 :tag "Org Startup"
821 :group 'org)
823 (defcustom org-startup-folded t
824 "Non-nil means entering Org-mode will switch to OVERVIEW.
825 This can also be configured on a per-file basis by adding one of
826 the following lines anywhere in the buffer:
828 #+STARTUP: fold (or `overview', this is equivalent)
829 #+STARTUP: nofold (or `showall', this is equivalent)
830 #+STARTUP: content
831 #+STARTUP: showeverything
833 By default, this option is ignored when Org opens agenda files
834 for the first time. If you want the agenda to honor the startup
835 option, set `org-agenda-inhibit-startup' to nil."
836 :group 'org-startup
837 :type '(choice
838 (const :tag "nofold: show all" nil)
839 (const :tag "fold: overview" t)
840 (const :tag "content: all headlines" content)
841 (const :tag "show everything, even drawers" showeverything)))
843 (defcustom org-startup-truncated t
844 "Non-nil means entering Org-mode will set `truncate-lines'.
845 This is useful since some lines containing links can be very long and
846 uninteresting. Also tables look terrible when wrapped."
847 :group 'org-startup
848 :type 'boolean)
850 (defcustom org-startup-indented nil
851 "Non-nil means turn on `org-indent-mode' on startup.
852 This can also be configured on a per-file basis by adding one of
853 the following lines anywhere in the buffer:
855 #+STARTUP: indent
856 #+STARTUP: noindent"
857 :group 'org-structure
858 :type '(choice
859 (const :tag "Not" nil)
860 (const :tag "Globally (slow on startup in large files)" t)))
862 (defcustom org-use-sub-superscripts t
863 "Non-nil means interpret \"_\" and \"^\" for display.
865 If you want to control how Org exports those characters, see
866 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
867 used to be an alias for `org-export-with-sub-superscripts' in
868 Org <8.0, it is not anymore.
870 When this option is turned on, you can use TeX-like syntax for
871 sub- and superscripts within the buffer. Several characters after
872 \"_\" or \"^\" will be considered as a single item - so grouping
873 with {} is normally not needed. For example, the following things
874 will be parsed as single sub- or superscripts:
876 10^24 or 10^tau several digits will be considered 1 item.
877 10^-12 or 10^-tau a leading sign with digits or a word
878 x^2-y^3 will be read as x^2 - y^3, because items are
879 terminated by almost any nonword/nondigit char.
880 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
882 Still, ambiguity is possible. So when in doubt, use {} to enclose
883 the sub/superscript. If you set this variable to the symbol `{}',
884 the braces are *required* in order to trigger interpretations as
885 sub/superscript. This can be helpful in documents that need \"_\"
886 frequently in plain text."
887 :group 'org-startup
888 :version "24.4"
889 :package-version '(Org . "8.0")
890 :type '(choice
891 (const :tag "Always interpret" t)
892 (const :tag "Only with braces" {})
893 (const :tag "Never interpret" nil)))
895 (defcustom org-startup-with-beamer-mode nil
896 "Non-nil means turn on `org-beamer-mode' on startup.
897 This can also be configured on a per-file basis by adding one of
898 the following lines anywhere in the buffer:
900 #+STARTUP: beamer"
901 :group 'org-startup
902 :version "24.1"
903 :type 'boolean)
905 (defcustom org-startup-align-all-tables nil
906 "Non-nil means align all tables when visiting a file.
907 This is useful when the column width in tables is forced with <N> cookies
908 in table fields. Such tables will look correct only after the first re-align.
909 This can also be configured on a per-file basis by adding one of
910 the following lines anywhere in the buffer:
911 #+STARTUP: align
912 #+STARTUP: noalign"
913 :group 'org-startup
914 :type 'boolean)
916 (defcustom org-startup-with-inline-images nil
917 "Non-nil means show inline images when loading a new Org file.
918 This can also be configured on a per-file basis by adding one of
919 the following lines anywhere in the buffer:
920 #+STARTUP: inlineimages
921 #+STARTUP: noinlineimages"
922 :group 'org-startup
923 :version "24.1"
924 :type 'boolean)
926 (defcustom org-startup-with-latex-preview nil
927 "Non-nil means preview LaTeX fragments when loading a new Org file.
929 This can also be configured on a per-file basis by adding one of
930 the following lines anywhere in the buffer:
931 #+STARTUP: latexpreview
932 #+STARTUP: nolatexpreview"
933 :group 'org-startup
934 :version "24.4"
935 :package-version '(Org . "8.0")
936 :type 'boolean)
938 (defcustom org-insert-mode-line-in-empty-file nil
939 "Non-nil means insert the first line setting Org-mode in empty files.
940 When the function `org-mode' is called interactively in an empty file, this
941 normally means that the file name does not automatically trigger Org-mode.
942 To ensure that the file will always be in Org-mode in the future, a
943 line enforcing Org-mode will be inserted into the buffer, if this option
944 has been set."
945 :group 'org-startup
946 :type 'boolean)
948 (defcustom org-replace-disputed-keys nil
949 "Non-nil means use alternative key bindings for some keys.
950 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
951 These keys are also used by other packages like shift-selection-mode'
952 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
953 If you want to use Org-mode together with one of these other modes,
954 or more generally if you would like to move some Org-mode commands to
955 other keys, set this variable and configure the keys with the variable
956 `org-disputed-keys'.
958 This option is only relevant at load-time of Org-mode, and must be set
959 *before* org.el is loaded. Changing it requires a restart of Emacs to
960 become effective."
961 :group 'org-startup
962 :type 'boolean)
964 (defcustom org-use-extra-keys nil
965 "Non-nil means use extra key sequence definitions for certain commands.
966 This happens automatically if you run XEmacs or if `window-system'
967 is nil. This variable lets you do the same manually. You must
968 set it before loading org.
970 Example: on Carbon Emacs 22 running graphically, with an external
971 keyboard on a Powerbook, the default way of setting M-left might
972 not work for either Alt or ESC. Setting this variable will make
973 it work for ESC."
974 :group 'org-startup
975 :type 'boolean)
977 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
979 (defcustom org-disputed-keys
980 '(([(shift up)] . [(meta p)])
981 ([(shift down)] . [(meta n)])
982 ([(shift left)] . [(meta -)])
983 ([(shift right)] . [(meta +)])
984 ([(control shift right)] . [(meta shift +)])
985 ([(control shift left)] . [(meta shift -)]))
986 "Keys for which Org-mode and other modes compete.
987 This is an alist, cars are the default keys, second element specifies
988 the alternative to use when `org-replace-disputed-keys' is t.
990 Keys can be specified in any syntax supported by `define-key'.
991 The value of this option takes effect only at Org-mode's startup,
992 therefore you'll have to restart Emacs to apply it after changing."
993 :group 'org-startup
994 :type 'alist)
996 (defun org-key (key)
997 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
998 Or return the original if not disputed.
999 Also apply the translations defined in `org-xemacs-key-equivalents'."
1000 (when org-replace-disputed-keys
1001 (let* ((nkey (key-description key))
1002 (x (org-find-if (lambda (x)
1003 (equal (key-description (car x)) nkey))
1004 org-disputed-keys)))
1005 (setq key (if x (cdr x) key))))
1006 (when (featurep 'xemacs)
1007 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1008 key)
1010 (defun org-find-if (predicate seq)
1011 (catch 'exit
1012 (while seq
1013 (if (funcall predicate (car seq))
1014 (throw 'exit (car seq))
1015 (pop seq)))))
1017 (defun org-defkey (keymap key def)
1018 "Define a key, possibly translated, as returned by `org-key'."
1019 (define-key keymap (org-key key) def))
1021 (defcustom org-ellipsis nil
1022 "The ellipsis to use in the Org-mode outline.
1023 When nil, just use the standard three dots.
1024 When a string, use that string instead.
1025 When a face, use the standard 3 dots, but with the specified face.
1026 The change affects only Org-mode (which will then use its own display table).
1027 Changing this requires executing `M-x org-mode RET' in a buffer to become
1028 effective."
1029 :group 'org-startup
1030 :type '(choice (const :tag "Default" nil)
1031 (face :tag "Face" :value org-warning)
1032 (string :tag "String" :value "...#")))
1034 (defvar org-display-table nil
1035 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1037 (defgroup org-keywords nil
1038 "Keywords in Org-mode."
1039 :tag "Org Keywords"
1040 :group 'org)
1042 (defcustom org-closed-keep-when-no-todo nil
1043 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1044 :group 'org-todo
1045 :group 'org-keywords
1046 :version "24.4"
1047 :package-version '(Org . "8.0")
1048 :type 'boolean)
1050 (defgroup org-structure nil
1051 "Options concerning the general structure of Org-mode files."
1052 :tag "Org Structure"
1053 :group 'org)
1055 (defgroup org-reveal-location nil
1056 "Options about how to make context of a location visible."
1057 :tag "Org Reveal Location"
1058 :group 'org-structure)
1060 (defconst org-context-choice
1061 '(choice
1062 (const :tag "Always" t)
1063 (const :tag "Never" nil)
1064 (repeat :greedy t :tag "Individual contexts"
1065 (cons
1066 (choice :tag "Context"
1067 (const agenda)
1068 (const org-goto)
1069 (const occur-tree)
1070 (const tags-tree)
1071 (const link-search)
1072 (const mark-goto)
1073 (const bookmark-jump)
1074 (const isearch)
1075 (const default))
1076 (boolean))))
1077 "Contexts for the reveal options.")
1079 (defcustom org-show-hierarchy-above '((default . t))
1080 "Non-nil means show full hierarchy when revealing a location.
1081 Org-mode often shows locations in an org-mode file which might have
1082 been invisible before. When this is set, the hierarchy of headings
1083 above the exposed location is shown.
1084 Turning this off for example for sparse trees makes them very compact.
1085 Instead of t, this can also be an alist specifying this option for different
1086 contexts. Valid contexts are
1087 agenda when exposing an entry from the agenda
1088 org-goto when using the command `org-goto' on key C-c C-j
1089 occur-tree when using the command `org-occur' on key C-c /
1090 tags-tree when constructing a sparse tree based on tags matches
1091 link-search when exposing search matches associated with a link
1092 mark-goto when exposing the jump goal of a mark
1093 bookmark-jump when exposing a bookmark location
1094 isearch when exiting from an incremental search
1095 default default for all contexts not set explicitly"
1096 :group 'org-reveal-location
1097 :type org-context-choice)
1099 (defcustom org-show-following-heading '((default . nil))
1100 "Non-nil means show following heading when revealing a location.
1101 Org-mode often shows locations in an org-mode file which might have
1102 been invisible before. When this is set, the heading following the
1103 match is shown.
1104 Turning this off for example for sparse trees makes them very compact,
1105 but makes it harder to edit the location of the match. In such a case,
1106 use the command \\[org-reveal] to show more context.
1107 Instead of t, this can also be an alist specifying this option for different
1108 contexts. See `org-show-hierarchy-above' for valid contexts."
1109 :group 'org-reveal-location
1110 :type org-context-choice)
1112 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
1113 "Non-nil means show all sibling heading when revealing a location.
1114 Org-mode often shows locations in an org-mode file which might have
1115 been invisible before. When this is set, the sibling of the current entry
1116 heading are all made visible. If `org-show-hierarchy-above' is t,
1117 the same happens on each level of the hierarchy above the current entry.
1119 By default this is on for the isearch context, off for all other contexts.
1120 Turning this off for example for sparse trees makes them very compact,
1121 but makes it harder to edit the location of the match. In such a case,
1122 use the command \\[org-reveal] to show more context.
1123 Instead of t, this can also be an alist specifying this option for different
1124 contexts. See `org-show-hierarchy-above' for valid contexts."
1125 :group 'org-reveal-location
1126 :type org-context-choice
1127 :version "24.4"
1128 :package-version '(Org . "8.0"))
1130 (defcustom org-show-entry-below '((default . nil))
1131 "Non-nil means show the entry below a headline when revealing a location.
1132 Org-mode often shows locations in an org-mode file which might have
1133 been invisible before. When this is set, the text below the headline that is
1134 exposed is also shown.
1136 By default this is off for all contexts.
1137 Instead of t, this can also be an alist specifying this option for different
1138 contexts. See `org-show-hierarchy-above' for valid contexts."
1139 :group 'org-reveal-location
1140 :type org-context-choice)
1142 (defcustom org-indirect-buffer-display 'other-window
1143 "How should indirect tree buffers be displayed?
1144 This applies to indirect buffers created with the commands
1145 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1146 Valid values are:
1147 current-window Display in the current window
1148 other-window Just display in another window.
1149 dedicated-frame Create one new frame, and re-use it each time.
1150 new-frame Make a new frame each time. Note that in this case
1151 previously-made indirect buffers are kept, and you need to
1152 kill these buffers yourself."
1153 :group 'org-structure
1154 :group 'org-agenda-windows
1155 :type '(choice
1156 (const :tag "In current window" current-window)
1157 (const :tag "In current frame, other window" other-window)
1158 (const :tag "Each time a new frame" new-frame)
1159 (const :tag "One dedicated frame" dedicated-frame)))
1161 (defcustom org-use-speed-commands nil
1162 "Non-nil means activate single letter commands at beginning of a headline.
1163 This may also be a function to test for appropriate locations where speed
1164 commands should be active.
1166 For example, to activate speed commands when the point is on any
1167 star at the beginning of the headline, you can do this:
1169 (setq org-use-speed-commands
1170 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1171 :group 'org-structure
1172 :type '(choice
1173 (const :tag "Never" nil)
1174 (const :tag "At beginning of headline stars" t)
1175 (function)))
1177 (defcustom org-speed-commands-user nil
1178 "Alist of additional speed commands.
1179 This list will be checked before `org-speed-commands-default'
1180 when the variable `org-use-speed-commands' is non-nil
1181 and when the cursor is at the beginning of a headline.
1182 The car if each entry is a string with a single letter, which must
1183 be assigned to `self-insert-command' in the global map.
1184 The cdr is either a command to be called interactively, a function
1185 to be called, or a form to be evaluated.
1186 An entry that is just a list with a single string will be interpreted
1187 as a descriptive headline that will be added when listing the speed
1188 commands in the Help buffer using the `?' speed command."
1189 :group 'org-structure
1190 :type '(repeat :value ("k" . ignore)
1191 (choice :value ("k" . ignore)
1192 (list :tag "Descriptive Headline" (string :tag "Headline"))
1193 (cons :tag "Letter and Command"
1194 (string :tag "Command letter")
1195 (choice
1196 (function)
1197 (sexp))))))
1199 (defcustom org-bookmark-names-plist
1200 '(:last-capture "org-capture-last-stored"
1201 :last-refile "org-refile-last-stored"
1202 :last-capture-marker "org-capture-last-stored-marker")
1203 "Names for bookmarks automatically set by some Org commands.
1204 This can provide strings as names for a number of bookmarks Org sets
1205 automatically. The following keys are currently implemented:
1206 :last-capture
1207 :last-capture-marker
1208 :last-refile
1209 When a key does not show up in the property list, the corresponding bookmark
1210 is not set."
1211 :group 'org-structure
1212 :type 'plist)
1214 (defgroup org-cycle nil
1215 "Options concerning visibility cycling in Org-mode."
1216 :tag "Org Cycle"
1217 :group 'org-structure)
1219 (defcustom org-cycle-skip-children-state-if-no-children t
1220 "Non-nil means skip CHILDREN state in entries that don't have any."
1221 :group 'org-cycle
1222 :type 'boolean)
1224 (defcustom org-cycle-max-level nil
1225 "Maximum level which should still be subject to visibility cycling.
1226 Levels higher than this will, for cycling, be treated as text, not a headline.
1227 When `org-odd-levels-only' is set, a value of N in this variable actually
1228 means 2N-1 stars as the limiting headline.
1229 When nil, cycle all levels.
1230 Note that the limiting level of cycling is also influenced by
1231 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1232 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1233 than its value."
1234 :group 'org-cycle
1235 :type '(choice
1236 (const :tag "No limit" nil)
1237 (integer :tag "Maximum level")))
1239 (defcustom org-hide-block-startup nil
1240 "Non-nil means entering Org-mode will fold all blocks.
1241 This can also be set in on a per-file basis with
1243 #+STARTUP: hideblocks
1244 #+STARTUP: showblocks"
1245 :group 'org-startup
1246 :group 'org-cycle
1247 :type 'boolean)
1249 (defcustom org-cycle-global-at-bob nil
1250 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1251 This makes it possible to do global cycling without having to use S-TAB or
1252 \\[universal-argument] TAB. For this special case to work, the first line
1253 of the buffer must not be a headline -- it may be empty or some other text.
1254 When used in this way, `org-cycle-hook' is disabled temporarily to make
1255 sure the cursor stays at the beginning of the buffer. When this option is
1256 nil, don't do anything special at the beginning of the buffer."
1257 :group 'org-cycle
1258 :type 'boolean)
1260 (defcustom org-cycle-level-after-item/entry-creation t
1261 "Non-nil means cycle entry level or item indentation in new empty entries.
1263 When the cursor is at the end of an empty headline, i.e., with only stars
1264 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1265 and then all possible ancestor states, before returning to the original state.
1266 This makes data entry extremely fast: M-RET to create a new headline,
1267 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1269 When the cursor is at the end of an empty plain list item, one TAB will
1270 make it a subitem, two or more tabs will back up to make this an item
1271 higher up in the item hierarchy."
1272 :group 'org-cycle
1273 :type 'boolean)
1275 (defcustom org-cycle-emulate-tab t
1276 "Where should `org-cycle' emulate TAB.
1277 nil Never
1278 white Only in completely white lines
1279 whitestart Only at the beginning of lines, before the first non-white char
1280 t Everywhere except in headlines
1281 exc-hl-bol Everywhere except at the start of a headline
1282 If TAB is used in a place where it does not emulate TAB, the current subtree
1283 visibility is cycled."
1284 :group 'org-cycle
1285 :type '(choice (const :tag "Never" nil)
1286 (const :tag "Only in completely white lines" white)
1287 (const :tag "Before first char in a line" whitestart)
1288 (const :tag "Everywhere except in headlines" t)
1289 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1291 (defcustom org-cycle-separator-lines 2
1292 "Number of empty lines needed to keep an empty line between collapsed trees.
1293 If you leave an empty line between the end of a subtree and the following
1294 headline, this empty line is hidden when the subtree is folded.
1295 Org-mode will leave (exactly) one empty line visible if the number of
1296 empty lines is equal or larger to the number given in this variable.
1297 So the default 2 means at least 2 empty lines after the end of a subtree
1298 are needed to produce free space between a collapsed subtree and the
1299 following headline.
1301 If the number is negative, and the number of empty lines is at least -N,
1302 all empty lines are shown.
1304 Special case: when 0, never leave empty lines in collapsed view."
1305 :group 'org-cycle
1306 :type 'integer)
1307 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1309 (defcustom org-pre-cycle-hook nil
1310 "Hook that is run before visibility cycling is happening.
1311 The function(s) in this hook must accept a single argument which indicates
1312 the new state that will be set right after running this hook. The
1313 argument is a symbol. Before a global state change, it can have the values
1314 `overview', `content', or `all'. Before a local state change, it can have
1315 the values `folded', `children', or `subtree'."
1316 :group 'org-cycle
1317 :type 'hook)
1319 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1320 org-cycle-hide-drawers
1321 org-cycle-hide-inline-tasks
1322 org-cycle-show-empty-lines
1323 org-optimize-window-after-visibility-change)
1324 "Hook that is run after `org-cycle' has changed the buffer visibility.
1325 The function(s) in this hook must accept a single argument which indicates
1326 the new state that was set by the most recent `org-cycle' command. The
1327 argument is a symbol. After a global state change, it can have the values
1328 `overview', `contents', or `all'. After a local state change, it can have
1329 the values `folded', `children', or `subtree'."
1330 :group 'org-cycle
1331 :type 'hook)
1333 (defgroup org-edit-structure nil
1334 "Options concerning structure editing in Org-mode."
1335 :tag "Org Edit Structure"
1336 :group 'org-structure)
1338 (defcustom org-odd-levels-only nil
1339 "Non-nil means skip even levels and only use odd levels for the outline.
1340 This has the effect that two stars are being added/taken away in
1341 promotion/demotion commands. It also influences how levels are
1342 handled by the exporters.
1343 Changing it requires restart of `font-lock-mode' to become effective
1344 for fontification also in regions already fontified.
1345 You may also set this on a per-file basis by adding one of the following
1346 lines to the buffer:
1348 #+STARTUP: odd
1349 #+STARTUP: oddeven"
1350 :group 'org-edit-structure
1351 :group 'org-appearance
1352 :type 'boolean)
1354 (defcustom org-adapt-indentation t
1355 "Non-nil means adapt indentation to outline node level.
1357 When this variable is set, Org assumes that you write outlines by
1358 indenting text in each node to align with the headline (after the stars).
1359 The following issues are influenced by this variable:
1361 - When this is set and the *entire* text in an entry is indented, the
1362 indentation is increased by one space in a demotion command, and
1363 decreased by one in a promotion command. If any line in the entry
1364 body starts with text at column 0, indentation is not changed at all.
1366 - Property drawers and planning information is inserted indented when
1367 this variable s set. When nil, they will not be indented.
1369 - TAB indents a line relative to context. The lines below a headline
1370 will be indented when this variable is set.
1372 Note that this is all about true indentation, by adding and removing
1373 space characters. See also `org-indent.el' which does level-dependent
1374 indentation in a virtual way, i.e. at display time in Emacs."
1375 :group 'org-edit-structure
1376 :type 'boolean)
1378 (defcustom org-special-ctrl-a/e nil
1379 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1381 When t, `C-a' will bring back the cursor to the beginning of the
1382 headline text, i.e. after the stars and after a possible TODO
1383 keyword. In an item, this will be the position after bullet and
1384 check-box, if any. When the cursor is already at that position,
1385 another `C-a' will bring it to the beginning of the line.
1387 `C-e' will jump to the end of the headline, ignoring the presence
1388 of tags in the headline. A second `C-e' will then jump to the
1389 true end of the line, after any tags. This also means that, when
1390 this variable is non-nil, `C-e' also will never jump beyond the
1391 end of the heading of a folded section, i.e. not after the
1392 ellipses.
1394 When set to the symbol `reversed', the first `C-a' or `C-e' works
1395 normally, going to the true line boundary first. Only a directly
1396 following, identical keypress will bring the cursor to the
1397 special positions.
1399 This may also be a cons cell where the behavior for `C-a' and
1400 `C-e' is set separately."
1401 :group 'org-edit-structure
1402 :type '(choice
1403 (const :tag "off" nil)
1404 (const :tag "on: after stars/bullet and before tags first" t)
1405 (const :tag "reversed: true line boundary first" reversed)
1406 (cons :tag "Set C-a and C-e separately"
1407 (choice :tag "Special C-a"
1408 (const :tag "off" nil)
1409 (const :tag "on: after stars/bullet first" t)
1410 (const :tag "reversed: before stars/bullet first" reversed))
1411 (choice :tag "Special C-e"
1412 (const :tag "off" nil)
1413 (const :tag "on: before tags first" t)
1414 (const :tag "reversed: after tags first" reversed)))))
1415 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1417 (defcustom org-special-ctrl-k nil
1418 "Non-nil means `C-k' will behave specially in headlines.
1419 When nil, `C-k' will call the default `kill-line' command.
1420 When t, the following will happen while the cursor is in the headline:
1422 - When the cursor is at the beginning of a headline, kill the entire
1423 line and possible the folded subtree below the line.
1424 - When in the middle of the headline text, kill the headline up to the tags.
1425 - When after the headline text, kill the tags."
1426 :group 'org-edit-structure
1427 :type 'boolean)
1429 (defcustom org-ctrl-k-protect-subtree nil
1430 "Non-nil means, do not delete a hidden subtree with C-k.
1431 When set to the symbol `error', simply throw an error when C-k is
1432 used to kill (part-of) a headline that has hidden text behind it.
1433 Any other non-nil value will result in a query to the user, if it is
1434 OK to kill that hidden subtree. When nil, kill without remorse."
1435 :group 'org-edit-structure
1436 :version "24.1"
1437 :type '(choice
1438 (const :tag "Do not protect hidden subtrees" nil)
1439 (const :tag "Protect hidden subtrees with a security query" t)
1440 (const :tag "Never kill a hidden subtree with C-k" error)))
1442 (defcustom org-special-ctrl-o t
1443 "Non-nil means, make `C-o' insert a row in tables."
1444 :group 'org-edit-structure
1445 :type 'boolean)
1447 (defcustom org-catch-invisible-edits nil
1448 "Check if in invisible region before inserting or deleting a character.
1449 Valid values are:
1451 nil Do not check, so just do invisible edits.
1452 error Throw an error and do nothing.
1453 show Make point visible, and do the requested edit.
1454 show-and-error Make point visible, then throw an error and abort the edit.
1455 smart Make point visible, and do insertion/deletion if it is
1456 adjacent to visible text and the change feels predictable.
1457 Never delete a previously invisible character or add in the
1458 middle or right after an invisible region. Basically, this
1459 allows insertion and backward-delete right before ellipses.
1460 FIXME: maybe in this case we should not even show?"
1461 :group 'org-edit-structure
1462 :version "24.1"
1463 :type '(choice
1464 (const :tag "Do not check" nil)
1465 (const :tag "Throw error when trying to edit" error)
1466 (const :tag "Unhide, but do not do the edit" show-and-error)
1467 (const :tag "Show invisible part and do the edit" show)
1468 (const :tag "Be smart and do the right thing" smart)))
1470 (defcustom org-yank-folded-subtrees t
1471 "Non-nil means when yanking subtrees, fold them.
1472 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1473 it starts with a heading and all other headings in it are either children
1474 or siblings, then fold all the subtrees. However, do this only if no
1475 text after the yank would be swallowed into a folded tree by this action."
1476 :group 'org-edit-structure
1477 :type 'boolean)
1479 (defcustom org-yank-adjusted-subtrees nil
1480 "Non-nil means when yanking subtrees, adjust the level.
1481 With this setting, `org-paste-subtree' is used to insert the subtree, see
1482 this function for details."
1483 :group 'org-edit-structure
1484 :type 'boolean)
1486 (defcustom org-M-RET-may-split-line '((default . t))
1487 "Non-nil means M-RET will split the line at the cursor position.
1488 When nil, it will go to the end of the line before making a
1489 new line.
1490 You may also set this option in a different way for different
1491 contexts. Valid contexts are:
1493 headline when creating a new headline
1494 item when creating a new item
1495 table in a table field
1496 default the value to be used for all contexts not explicitly
1497 customized"
1498 :group 'org-structure
1499 :group 'org-table
1500 :type '(choice
1501 (const :tag "Always" t)
1502 (const :tag "Never" nil)
1503 (repeat :greedy t :tag "Individual contexts"
1504 (cons
1505 (choice :tag "Context"
1506 (const headline)
1507 (const item)
1508 (const table)
1509 (const default))
1510 (boolean)))))
1513 (defcustom org-insert-heading-respect-content nil
1514 "Non-nil means insert new headings after the current subtree.
1515 When nil, the new heading is created directly after the current line.
1516 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1517 this variable on for the duration of the command."
1518 :group 'org-structure
1519 :type 'boolean)
1521 (defcustom org-blank-before-new-entry '((heading . auto)
1522 (plain-list-item . auto))
1523 "Should `org-insert-heading' leave a blank line before new heading/item?
1524 The value is an alist, with `heading' and `plain-list-item' as CAR,
1525 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1526 which case Org will look at the surrounding headings/items and try to
1527 make an intelligent decision whether to insert a blank line or not.
1529 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1530 the setting here is ignored and no empty line is inserted to avoid breaking
1531 the list structure."
1532 :group 'org-edit-structure
1533 :type '(list
1534 (cons (const heading)
1535 (choice (const :tag "Never" nil)
1536 (const :tag "Always" t)
1537 (const :tag "Auto" auto)))
1538 (cons (const plain-list-item)
1539 (choice (const :tag "Never" nil)
1540 (const :tag "Always" t)
1541 (const :tag "Auto" auto)))))
1543 (defcustom org-insert-heading-hook nil
1544 "Hook being run after inserting a new heading."
1545 :group 'org-edit-structure
1546 :type 'hook)
1548 (defcustom org-enable-fixed-width-editor t
1549 "Non-nil means lines starting with \":\" are treated as fixed-width.
1550 This currently only means they are never auto-wrapped.
1551 When nil, such lines will be treated like ordinary lines."
1552 :group 'org-edit-structure
1553 :type 'boolean)
1555 (defcustom org-goto-auto-isearch t
1556 "Non-nil means typing characters in `org-goto' starts incremental search.
1557 When nil, you can use these keybindings to navigate the buffer:
1559 q Quit the org-goto interface
1560 n Go to the next visible heading
1561 p Go to the previous visible heading
1562 f Go one heading forward on same level
1563 b Go one heading backward on same level
1564 u Go one heading up"
1565 :group 'org-edit-structure
1566 :type 'boolean)
1568 (defgroup org-sparse-trees nil
1569 "Options concerning sparse trees in Org-mode."
1570 :tag "Org Sparse Trees"
1571 :group 'org-structure)
1573 (defcustom org-highlight-sparse-tree-matches t
1574 "Non-nil means highlight all matches that define a sparse tree.
1575 The highlights will automatically disappear the next time the buffer is
1576 changed by an edit command."
1577 :group 'org-sparse-trees
1578 :type 'boolean)
1580 (defcustom org-remove-highlights-with-change t
1581 "Non-nil means any change to the buffer will remove temporary highlights.
1582 Such highlights are created by `org-occur' and `org-clock-display'.
1583 When nil, `C-c C-c needs to be used to get rid of the highlights.
1584 The highlights created by `org-preview-latex-fragment' always need
1585 `C-c C-c' to be removed."
1586 :group 'org-sparse-trees
1587 :group 'org-time
1588 :type 'boolean)
1591 (defcustom org-occur-hook '(org-first-headline-recenter)
1592 "Hook that is run after `org-occur' has constructed a sparse tree.
1593 This can be used to recenter the window to show as much of the structure
1594 as possible."
1595 :group 'org-sparse-trees
1596 :type 'hook)
1598 (defgroup org-imenu-and-speedbar nil
1599 "Options concerning imenu and speedbar in Org-mode."
1600 :tag "Org Imenu and Speedbar"
1601 :group 'org-structure)
1603 (defcustom org-imenu-depth 2
1604 "The maximum level for Imenu access to Org-mode headlines.
1605 This also applied for speedbar access."
1606 :group 'org-imenu-and-speedbar
1607 :type 'integer)
1609 (defgroup org-table nil
1610 "Options concerning tables in Org-mode."
1611 :tag "Org Table"
1612 :group 'org)
1614 (defcustom org-enable-table-editor 'optimized
1615 "Non-nil means lines starting with \"|\" are handled by the table editor.
1616 When nil, such lines will be treated like ordinary lines.
1618 When equal to the symbol `optimized', the table editor will be optimized to
1619 do the following:
1620 - Automatic overwrite mode in front of whitespace in table fields.
1621 This makes the structure of the table stay in tact as long as the edited
1622 field does not exceed the column width.
1623 - Minimize the number of realigns. Normally, the table is aligned each time
1624 TAB or RET are pressed to move to another field. With optimization this
1625 happens only if changes to a field might have changed the column width.
1626 Optimization requires replacing the functions `self-insert-command',
1627 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1628 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1629 very good at guessing when a re-align will be necessary, but you can always
1630 force one with \\[org-ctrl-c-ctrl-c].
1632 If you would like to use the optimized version in Org-mode, but the
1633 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1635 This variable can be used to turn on and off the table editor during a session,
1636 but in order to toggle optimization, a restart is required.
1638 See also the variable `org-table-auto-blank-field'."
1639 :group 'org-table
1640 :type '(choice
1641 (const :tag "off" nil)
1642 (const :tag "on" t)
1643 (const :tag "on, optimized" optimized)))
1645 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1646 (version<= emacs-version "24.1"))
1647 "Non-nil means cluster self-insert commands for undo when possible.
1648 If this is set, then, like in the Emacs command loop, 20 consecutive
1649 characters will be undone together.
1650 This is configurable, because there is some impact on typing performance."
1651 :group 'org-table
1652 :type 'boolean)
1654 (defcustom org-table-tab-recognizes-table.el t
1655 "Non-nil means TAB will automatically notice a table.el table.
1656 When it sees such a table, it moves point into it and - if necessary -
1657 calls `table-recognize-table'."
1658 :group 'org-table-editing
1659 :type 'boolean)
1661 (defgroup org-link nil
1662 "Options concerning links in Org-mode."
1663 :tag "Org Link"
1664 :group 'org)
1666 (defvar org-link-abbrev-alist-local nil
1667 "Buffer-local version of `org-link-abbrev-alist', which see.
1668 The value of this is taken from the #+LINK lines.")
1669 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1671 (defcustom org-link-abbrev-alist nil
1672 "Alist of link abbreviations.
1673 The car of each element is a string, to be replaced at the start of a link.
1674 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1675 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1677 [[linkkey:tag][description]]
1679 The 'linkkey' must be a word word, starting with a letter, followed
1680 by letters, numbers, '-' or '_'.
1682 If REPLACE is a string, the tag will simply be appended to create the link.
1683 If the string contains \"%s\", the tag will be inserted there. If the string
1684 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1685 at that point (see the function `url-hexify-string'). If the string contains
1686 the specifier \"%(my-function)\", then the custom function `my-function' will
1687 be invoked: this function takes the tag as its only argument and must return
1688 a string.
1690 REPLACE may also be a function that will be called with the tag as the
1691 only argument to create the link, which should be returned as a string.
1693 See the manual for examples."
1694 :group 'org-link
1695 :type '(repeat
1696 (cons
1697 (string :tag "Protocol")
1698 (choice
1699 (string :tag "Format")
1700 (function)))))
1702 (defcustom org-descriptive-links t
1703 "Non-nil means Org will display descriptive links.
1704 E.g. [[http://orgmode.org][Org website]] will be displayed as
1705 \"Org Website\", hiding the link itself and just displaying its
1706 description. When set to `nil', Org will display the full links
1707 literally.
1709 You can interactively set the value of this variable by calling
1710 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1711 :group 'org-link
1712 :type 'boolean)
1714 (defcustom org-link-file-path-type 'adaptive
1715 "How the path name in file links should be stored.
1716 Valid values are:
1718 relative Relative to the current directory, i.e. the directory of the file
1719 into which the link is being inserted.
1720 absolute Absolute path, if possible with ~ for home directory.
1721 noabbrev Absolute path, no abbreviation of home directory.
1722 adaptive Use relative path for files in the current directory and sub-
1723 directories of it. For other files, use an absolute path."
1724 :group 'org-link
1725 :type '(choice
1726 (const relative)
1727 (const absolute)
1728 (const noabbrev)
1729 (const adaptive)))
1731 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1732 "Types of links that should be activated in Org-mode files.
1733 This is a list of symbols, each leading to the activation of a certain link
1734 type. In principle, it does not hurt to turn on most link types - there may
1735 be a small gain when turning off unused link types. The types are:
1737 bracket The recommended [[link][description]] or [[link]] links with hiding.
1738 angle Links in angular brackets that may contain whitespace like
1739 <bbdb:Carsten Dominik>.
1740 plain Plain links in normal text, no whitespace, like http://google.com.
1741 radio Text that is matched by a radio target, see manual for details.
1742 tag Tag settings in a headline (link to tag search).
1743 date Time stamps (link to calendar).
1744 footnote Footnote labels.
1746 Changing this variable requires a restart of Emacs to become effective."
1747 :group 'org-link
1748 :type '(set :greedy t
1749 (const :tag "Double bracket links" bracket)
1750 (const :tag "Angular bracket links" angle)
1751 (const :tag "Plain text links" plain)
1752 (const :tag "Radio target matches" radio)
1753 (const :tag "Tags" tag)
1754 (const :tag "Timestamps" date)
1755 (const :tag "Footnotes" footnote)))
1757 (defcustom org-make-link-description-function nil
1758 "Function to use for generating link descriptions from links.
1759 When nil, the link location will be used. This function must take
1760 two parameters: the first one is the link, the second one is the
1761 description generated by `org-insert-link'. The function should
1762 return the description to use."
1763 :group 'org-link
1764 :type '(choice (const nil) (function)))
1766 (defgroup org-link-store nil
1767 "Options concerning storing links in Org-mode."
1768 :tag "Org Store Link"
1769 :group 'org-link)
1771 (defcustom org-url-hexify-p t
1772 "When non-nil, hexify URL when creating a link."
1773 :type 'boolean
1774 :version "24.3"
1775 :group 'org-link-store)
1777 (defcustom org-email-link-description-format "Email %c: %.30s"
1778 "Format of the description part of a link to an email or usenet message.
1779 The following %-escapes will be replaced by corresponding information:
1781 %F full \"From\" field
1782 %f name, taken from \"From\" field, address if no name
1783 %T full \"To\" field
1784 %t first name in \"To\" field, address if no name
1785 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1786 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1787 %s subject
1788 %d date
1789 %m message-id.
1791 You may use normal field width specification between the % and the letter.
1792 This is for example useful to limit the length of the subject.
1794 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1795 :group 'org-link-store
1796 :type 'string)
1798 (defcustom org-from-is-user-regexp
1799 (let (r1 r2)
1800 (when (and user-mail-address (not (string= user-mail-address "")))
1801 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1802 (when (and user-full-name (not (string= user-full-name "")))
1803 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1804 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1805 "Regexp matched against the \"From:\" header of an email or usenet message.
1806 It should match if the message is from the user him/herself."
1807 :group 'org-link-store
1808 :type 'regexp)
1810 (defcustom org-context-in-file-links t
1811 "Non-nil means file links from `org-store-link' contain context.
1812 A search string will be added to the file name with :: as separator and
1813 used to find the context when the link is activated by the command
1814 `org-open-at-point'. When this option is t, the entire active region
1815 will be placed in the search string of the file link. If set to a
1816 positive integer, only the first n lines of context will be stored.
1818 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1819 negates this setting for the duration of the command."
1820 :group 'org-link-store
1821 :type '(choice boolean integer))
1823 (defcustom org-keep-stored-link-after-insertion nil
1824 "Non-nil means keep link in list for entire session.
1826 The command `org-store-link' adds a link pointing to the current
1827 location to an internal list. These links accumulate during a session.
1828 The command `org-insert-link' can be used to insert links into any
1829 Org-mode file (offering completion for all stored links). When this
1830 option is nil, every link which has been inserted once using \\[org-insert-link]
1831 will be removed from the list, to make completing the unused links
1832 more efficient."
1833 :group 'org-link-store
1834 :type 'boolean)
1836 (defgroup org-link-follow nil
1837 "Options concerning following links in Org-mode."
1838 :tag "Org Follow Link"
1839 :group 'org-link)
1841 (defcustom org-link-translation-function nil
1842 "Function to translate links with different syntax to Org syntax.
1843 This can be used to translate links created for example by the Planner
1844 or emacs-wiki packages to Org syntax.
1845 The function must accept two parameters, a TYPE containing the link
1846 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1847 which is everything after the link protocol. It should return a cons
1848 with possibly modified values of type and path.
1849 Org contains a function for this, so if you set this variable to
1850 `org-translate-link-from-planner', you should be able follow many
1851 links created by planner."
1852 :group 'org-link-follow
1853 :type '(choice (const nil) (function)))
1855 (defcustom org-follow-link-hook nil
1856 "Hook that is run after a link has been followed."
1857 :group 'org-link-follow
1858 :type 'hook)
1860 (defcustom org-tab-follows-link nil
1861 "Non-nil means on links TAB will follow the link.
1862 Needs to be set before org.el is loaded.
1863 This really should not be used, it does not make sense, and the
1864 implementation is bad."
1865 :group 'org-link-follow
1866 :type 'boolean)
1868 (defcustom org-return-follows-link nil
1869 "Non-nil means on links RET will follow the link.
1870 In tables, the special behavior of RET has precedence."
1871 :group 'org-link-follow
1872 :type 'boolean)
1874 (defcustom org-mouse-1-follows-link
1875 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1876 "Non-nil means mouse-1 on a link will follow the link.
1877 A longer mouse click will still set point. Does not work on XEmacs.
1878 Needs to be set before org.el is loaded."
1879 :group 'org-link-follow
1880 :version "24.4"
1881 :package-version '(Org . "8.3")
1882 :type '(choice
1883 (const :tag "A double click follows the link" double)
1884 (const :tag "Unconditionally follow the link with mouse-1" t)
1885 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1887 (defcustom org-mark-ring-length 4
1888 "Number of different positions to be recorded in the ring.
1889 Changing this requires a restart of Emacs to work correctly."
1890 :group 'org-link-follow
1891 :type 'integer)
1893 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1894 "Non-nil means internal links in Org files must exactly match a headline.
1895 When nil, the link search tries to match a phrase with all words
1896 in the search text."
1897 :group 'org-link-follow
1898 :version "24.1"
1899 :type '(choice
1900 (const :tag "Use fuzzy text search" nil)
1901 (const :tag "Match only exact headline" t)
1902 (const :tag "Match exact headline or query to create it"
1903 query-to-create)))
1905 (defcustom org-link-frame-setup
1906 '((vm . vm-visit-folder-other-frame)
1907 (vm-imap . vm-visit-imap-folder-other-frame)
1908 (gnus . org-gnus-no-new-news)
1909 (file . find-file-other-window)
1910 (wl . wl-other-frame))
1911 "Setup the frame configuration for following links.
1912 When following a link with Emacs, it may often be useful to display
1913 this link in another window or frame. This variable can be used to
1914 set this up for the different types of links.
1915 For VM, use any of
1916 `vm-visit-folder'
1917 `vm-visit-folder-other-window'
1918 `vm-visit-folder-other-frame'
1919 For Gnus, use any of
1920 `gnus'
1921 `gnus-other-frame'
1922 `org-gnus-no-new-news'
1923 For FILE, use any of
1924 `find-file'
1925 `find-file-other-window'
1926 `find-file-other-frame'
1927 For Wanderlust use any of
1928 `wl'
1929 `wl-other-frame'
1930 For the calendar, use the variable `calendar-setup'.
1931 For BBDB, it is currently only possible to display the matches in
1932 another window."
1933 :group 'org-link-follow
1934 :type '(list
1935 (cons (const vm)
1936 (choice
1937 (const vm-visit-folder)
1938 (const vm-visit-folder-other-window)
1939 (const vm-visit-folder-other-frame)))
1940 (cons (const vm-imap)
1941 (choice
1942 (const vm-visit-imap-folder)
1943 (const vm-visit-imap-folder-other-window)
1944 (const vm-visit-imap-folder-other-frame)))
1945 (cons (const gnus)
1946 (choice
1947 (const gnus)
1948 (const gnus-other-frame)
1949 (const org-gnus-no-new-news)))
1950 (cons (const file)
1951 (choice
1952 (const find-file)
1953 (const find-file-other-window)
1954 (const find-file-other-frame)))
1955 (cons (const wl)
1956 (choice
1957 (const wl)
1958 (const wl-other-frame)))))
1960 (defcustom org-display-internal-link-with-indirect-buffer nil
1961 "Non-nil means use indirect buffer to display infile links.
1962 Activating internal links (from one location in a file to another location
1963 in the same file) normally just jumps to the location. When the link is
1964 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1965 is displayed in
1966 another window. When this option is set, the other window actually displays
1967 an indirect buffer clone of the current buffer, to avoid any visibility
1968 changes to the current buffer."
1969 :group 'org-link-follow
1970 :type 'boolean)
1972 (defcustom org-open-non-existing-files nil
1973 "Non-nil means `org-open-file' will open non-existing files.
1974 When nil, an error will be generated.
1975 This variable applies only to external applications because they
1976 might choke on non-existing files. If the link is to a file that
1977 will be opened in Emacs, the variable is ignored."
1978 :group 'org-link-follow
1979 :type 'boolean)
1981 (defcustom org-open-directory-means-index-dot-org nil
1982 "Non-nil means a link to a directory really means to index.org.
1983 When nil, following a directory link will run dired or open a finder/explorer
1984 window on that directory."
1985 :group 'org-link-follow
1986 :type 'boolean)
1988 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1989 "Function and arguments to call for following mailto links.
1990 This is a list with the first element being a Lisp function, and the
1991 remaining elements being arguments to the function. In string arguments,
1992 %a will be replaced by the address, and %s will be replaced by the subject
1993 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1994 :group 'org-link-follow
1995 :type '(choice
1996 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1997 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1998 (const :tag "message-mail" (message-mail "%a" "%s"))
1999 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
2001 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2002 "Non-nil means ask for confirmation before executing shell links.
2003 Shell links can be dangerous: just think about a link
2005 [[shell:rm -rf ~/*][Google Search]]
2007 This link would show up in your Org-mode document as \"Google Search\",
2008 but really it would remove your entire home directory.
2009 Therefore we advise against setting this variable to nil.
2010 Just change it to `y-or-n-p' if you want to confirm with a
2011 single keystroke rather than having to type \"yes\"."
2012 :group 'org-link-follow
2013 :type '(choice
2014 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2015 (const :tag "with y-or-n (faster)" y-or-n-p)
2016 (const :tag "no confirmation (dangerous)" nil)))
2017 (put 'org-confirm-shell-link-function
2018 'safe-local-variable
2019 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2021 (defcustom org-confirm-shell-link-not-regexp ""
2022 "A regexp to skip confirmation for shell links."
2023 :group 'org-link-follow
2024 :version "24.1"
2025 :type 'regexp)
2027 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2028 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2029 Elisp links can be dangerous: just think about a link
2031 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2033 This link would show up in your Org-mode document as \"Google Search\",
2034 but really it would remove your entire home directory.
2035 Therefore we advise against setting this variable to nil.
2036 Just change it to `y-or-n-p' if you want to confirm with a
2037 single keystroke rather than having to type \"yes\"."
2038 :group 'org-link-follow
2039 :type '(choice
2040 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2041 (const :tag "with y-or-n (faster)" y-or-n-p)
2042 (const :tag "no confirmation (dangerous)" nil)))
2043 (put 'org-confirm-shell-link-function
2044 'safe-local-variable
2045 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2047 (defcustom org-confirm-elisp-link-not-regexp ""
2048 "A regexp to skip confirmation for Elisp links."
2049 :group 'org-link-follow
2050 :version "24.1"
2051 :type 'regexp)
2053 (defconst org-file-apps-defaults-gnu
2054 '((remote . emacs)
2055 (system . mailcap)
2056 (t . mailcap))
2057 "Default file applications on a UNIX or GNU/Linux system.
2058 See `org-file-apps'.")
2060 (defconst org-file-apps-defaults-macosx
2061 '((remote . emacs)
2062 (t . "open %s")
2063 (system . "open %s")
2064 ("ps.gz" . "gv %s")
2065 ("eps.gz" . "gv %s")
2066 ("dvi" . "xdvi %s")
2067 ("fig" . "xfig %s"))
2068 "Default file applications on a MacOS X system.
2069 The system \"open\" is known as a default, but we use X11 applications
2070 for some files for which the OS does not have a good default.
2071 See `org-file-apps'.")
2073 (defconst org-file-apps-defaults-windowsnt
2074 (list
2075 '(remote . emacs)
2076 (cons t
2077 (list (if (featurep 'xemacs)
2078 'mswindows-shell-execute
2079 'w32-shell-execute)
2080 "open" 'file))
2081 (cons 'system
2082 (list (if (featurep 'xemacs)
2083 'mswindows-shell-execute
2084 'w32-shell-execute)
2085 "open" 'file)))
2086 "Default file applications on a Windows NT system.
2087 The system \"open\" is used for most files.
2088 See `org-file-apps'.")
2090 (defcustom org-file-apps
2091 '((auto-mode . emacs)
2092 ("\\.mm\\'" . default)
2093 ("\\.x?html?\\'" . default)
2094 ("\\.pdf\\'" . default))
2095 "External applications for opening `file:path' items in a document.
2096 Org-mode uses system defaults for different file types, but
2097 you can use this variable to set the application for a given file
2098 extension. The entries in this list are cons cells where the car identifies
2099 files and the cdr the corresponding command. Possible values for the
2100 file identifier are
2101 \"string\" A string as a file identifier can be interpreted in different
2102 ways, depending on its contents:
2104 - Alphanumeric characters only:
2105 Match links with this file extension.
2106 Example: (\"pdf\" . \"evince %s\")
2107 to open PDFs with evince.
2109 - Regular expression: Match links where the
2110 filename matches the regexp. If you want to
2111 use groups here, use shy groups.
2113 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2114 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2115 to open *.html and *.xhtml with firefox.
2117 - Regular expression which contains (non-shy) groups:
2118 Match links where the whole link, including \"::\", and
2119 anything after that, matches the regexp.
2120 In a custom command string, %1, %2, etc. are replaced with
2121 the parts of the link that were matched by the groups.
2122 For backwards compatibility, if a command string is given
2123 that does not use any of the group matches, this case is
2124 handled identically to the second one (i.e. match against
2125 file name only).
2126 In a custom lisp form, you can access the group matches with
2127 (match-string n link).
2129 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2130 to open [[file:document.pdf::5]] with evince at page 5.
2132 `directory' Matches a directory
2133 `remote' Matches a remote file, accessible through tramp or efs.
2134 Remote files most likely should be visited through Emacs
2135 because external applications cannot handle such paths.
2136 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2137 so all files Emacs knows how to handle. Using this with
2138 command `emacs' will open most files in Emacs. Beware that this
2139 will also open html files inside Emacs, unless you add
2140 (\"html\" . default) to the list as well.
2141 t Default for files not matched by any of the other options.
2142 `system' The system command to open files, like `open' on Windows
2143 and Mac OS X, and mailcap under GNU/Linux. This is the command
2144 that will be selected if you call `C-c C-o' with a double
2145 \\[universal-argument] \\[universal-argument] prefix.
2147 Possible values for the command are:
2148 `emacs' The file will be visited by the current Emacs process.
2149 `default' Use the default application for this file type, which is the
2150 association for t in the list, most likely in the system-specific
2151 part.
2152 This can be used to overrule an unwanted setting in the
2153 system-specific variable.
2154 `system' Use the system command for opening files, like \"open\".
2155 This command is specified by the entry whose car is `system'.
2156 Most likely, the system-specific version of this variable
2157 does define this command, but you can overrule/replace it
2158 here.
2159 string A command to be executed by a shell; %s will be replaced
2160 by the path to the file.
2161 sexp A Lisp form which will be evaluated. The file path will
2162 be available in the Lisp variable `file'.
2163 For more examples, see the system specific constants
2164 `org-file-apps-defaults-macosx'
2165 `org-file-apps-defaults-windowsnt'
2166 `org-file-apps-defaults-gnu'."
2167 :group 'org-link-follow
2168 :type '(repeat
2169 (cons (choice :value ""
2170 (string :tag "Extension")
2171 (const :tag "System command to open files" system)
2172 (const :tag "Default for unrecognized files" t)
2173 (const :tag "Remote file" remote)
2174 (const :tag "Links to a directory" directory)
2175 (const :tag "Any files that have Emacs modes"
2176 auto-mode))
2177 (choice :value ""
2178 (const :tag "Visit with Emacs" emacs)
2179 (const :tag "Use default" default)
2180 (const :tag "Use the system command" system)
2181 (string :tag "Command")
2182 (sexp :tag "Lisp form")))))
2184 (defcustom org-doi-server-url "http://dx.doi.org/"
2185 "The URL of the DOI server."
2186 :type 'string
2187 :version "24.3"
2188 :group 'org-link-follow)
2190 (defgroup org-refile nil
2191 "Options concerning refiling entries in Org-mode."
2192 :tag "Org Refile"
2193 :group 'org)
2195 (defcustom org-directory "~/org"
2196 "Directory with org files.
2197 This is just a default location to look for Org files. There is no need
2198 at all to put your files into this directory. It is only used in the
2199 following situations:
2201 1. When a capture template specifies a target file that is not an
2202 absolute path. The path will then be interpreted relative to
2203 `org-directory'
2204 2. When a capture note is filed away in an interactive way (when exiting the
2205 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2206 with `org-directory' as the default path."
2207 :group 'org-refile
2208 :group 'org-capture
2209 :type 'directory)
2211 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2212 "Default target for storing notes.
2213 Used as a fall back file for org-capture.el, for templates that
2214 do not specify a target file."
2215 :group 'org-refile
2216 :group 'org-capture
2217 :type '(choice
2218 (const :tag "Default from remember-data-file" nil)
2219 file))
2221 (defcustom org-goto-interface 'outline
2222 "The default interface to be used for `org-goto'.
2223 Allowed values are:
2224 outline The interface shows an outline of the relevant file
2225 and the correct heading is found by moving through
2226 the outline or by searching with incremental search.
2227 outline-path-completion Headlines in the current buffer are offered via
2228 completion. This is the interface also used by
2229 the refile command."
2230 :group 'org-refile
2231 :type '(choice
2232 (const :tag "Outline" outline)
2233 (const :tag "Outline-path-completion" outline-path-completion)))
2235 (defcustom org-goto-max-level 5
2236 "Maximum target level when running `org-goto' with refile interface."
2237 :group 'org-refile
2238 :type 'integer)
2240 (defcustom org-reverse-note-order nil
2241 "Non-nil means store new notes at the beginning of a file or entry.
2242 When nil, new notes will be filed to the end of a file or entry.
2243 This can also be a list with cons cells of regular expressions that
2244 are matched against file names, and values."
2245 :group 'org-capture
2246 :group 'org-refile
2247 :type '(choice
2248 (const :tag "Reverse always" t)
2249 (const :tag "Reverse never" nil)
2250 (repeat :tag "By file name regexp"
2251 (cons regexp boolean))))
2253 (defcustom org-log-refile nil
2254 "Information to record when a task is refiled.
2256 Possible values are:
2258 nil Don't add anything
2259 time Add a time stamp to the task
2260 note Prompt for a note and add it with template `org-log-note-headings'
2262 This option can also be set with on a per-file-basis with
2264 #+STARTUP: nologrefile
2265 #+STARTUP: logrefile
2266 #+STARTUP: lognoterefile
2268 You can have local logging settings for a subtree by setting the LOGGING
2269 property to one or more of these keywords.
2271 When bulk-refiling from the agenda, the value `note' is forbidden and
2272 will temporarily be changed to `time'."
2273 :group 'org-refile
2274 :group 'org-progress
2275 :version "24.1"
2276 :type '(choice
2277 (const :tag "No logging" nil)
2278 (const :tag "Record timestamp" time)
2279 (const :tag "Record timestamp with note." note)))
2281 (defcustom org-refile-targets nil
2282 "Targets for refiling entries with \\[org-refile].
2283 This is a list of cons cells. Each cell contains:
2284 - a specification of the files to be considered, either a list of files,
2285 or a symbol whose function or variable value will be used to retrieve
2286 a file name or a list of file names. If you use `org-agenda-files' for
2287 that, all agenda files will be scanned for targets. Nil means consider
2288 headings in the current buffer.
2289 - A specification of how to find candidate refile targets. This may be
2290 any of:
2291 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2292 This tag has to be present in all target headlines, inheritance will
2293 not be considered.
2294 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2295 todo keyword.
2296 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2297 headlines that are refiling targets.
2298 - a cons cell (:level . N). Any headline of level N is considered a target.
2299 Note that, when `org-odd-levels-only' is set, level corresponds to
2300 order in hierarchy, not to the number of stars.
2301 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2302 Note that, when `org-odd-levels-only' is set, level corresponds to
2303 order in hierarchy, not to the number of stars.
2305 Each element of this list generates a set of possible targets.
2306 The union of these sets is presented (with completion) to
2307 the user by `org-refile'.
2309 You can set the variable `org-refile-target-verify-function' to a function
2310 to verify each headline found by the simple criteria above.
2312 When this variable is nil, all top-level headlines in the current buffer
2313 are used, equivalent to the value `((nil . (:level . 1))'."
2314 :group 'org-refile
2315 :type '(repeat
2316 (cons
2317 (choice :value org-agenda-files
2318 (const :tag "All agenda files" org-agenda-files)
2319 (const :tag "Current buffer" nil)
2320 (function) (variable) (file))
2321 (choice :tag "Identify target headline by"
2322 (cons :tag "Specific tag" (const :value :tag) (string))
2323 (cons :tag "TODO keyword" (const :value :todo) (string))
2324 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2325 (cons :tag "Level number" (const :value :level) (integer))
2326 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2328 (defcustom org-refile-target-verify-function nil
2329 "Function to verify if the headline at point should be a refile target.
2330 The function will be called without arguments, with point at the
2331 beginning of the headline. It should return t and leave point
2332 where it is if the headline is a valid target for refiling.
2334 If the target should not be selected, the function must return nil.
2335 In addition to this, it may move point to a place from where the search
2336 should be continued. For example, the function may decide that the entire
2337 subtree of the current entry should be excluded and move point to the end
2338 of the subtree."
2339 :group 'org-refile
2340 :type '(choice
2341 (const nil)
2342 (function)))
2344 (defcustom org-refile-use-cache nil
2345 "Non-nil means cache refile targets to speed up the process.
2346 The cache for a particular file will be updated automatically when
2347 the buffer has been killed, or when any of the marker used for flagging
2348 refile targets no longer points at a live buffer.
2349 If you have added new entries to a buffer that might themselves be targets,
2350 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2351 find that easier, `C-u C-u C-u C-c C-w'."
2352 :group 'org-refile
2353 :version "24.1"
2354 :type 'boolean)
2356 (defcustom org-refile-use-outline-path nil
2357 "Non-nil means provide refile targets as paths.
2358 So a level 3 headline will be available as level1/level2/level3.
2360 When the value is `file', also include the file name (without directory)
2361 into the path. In this case, you can also stop the completion after
2362 the file name, to get entries inserted as top level in the file.
2364 When `full-file-path', include the full file path."
2365 :group 'org-refile
2366 :type '(choice
2367 (const :tag "Not" nil)
2368 (const :tag "Yes" t)
2369 (const :tag "Start with file name" file)
2370 (const :tag "Start with full file path" full-file-path)))
2372 (defcustom org-outline-path-complete-in-steps t
2373 "Non-nil means complete the outline path in hierarchical steps.
2374 When Org-mode uses the refile interface to select an outline path
2375 \(see variable `org-refile-use-outline-path'), the completion of
2376 the path can be done is a single go, or if can be done in steps down
2377 the headline hierarchy. Going in steps is probably the best if you
2378 do not use a special completion package like `ido' or `icicles'.
2379 However, when using these packages, going in one step can be very
2380 fast, while still showing the whole path to the entry."
2381 :group 'org-refile
2382 :type 'boolean)
2384 (defcustom org-refile-allow-creating-parent-nodes nil
2385 "Non-nil means allow to create new nodes as refile targets.
2386 New nodes are then created by adding \"/new node name\" to the completion
2387 of an existing node. When the value of this variable is `confirm',
2388 new node creation must be confirmed by the user (recommended).
2389 When nil, the completion must match an existing entry.
2391 Note that, if the new heading is not seen by the criteria
2392 listed in `org-refile-targets', multiple instances of the same
2393 heading would be created by trying again to file under the new
2394 heading."
2395 :group 'org-refile
2396 :type '(choice
2397 (const :tag "Never" nil)
2398 (const :tag "Always" t)
2399 (const :tag "Prompt for confirmation" confirm)))
2401 (defcustom org-refile-active-region-within-subtree nil
2402 "Non-nil means also refile active region within a subtree.
2404 By default `org-refile' doesn't allow refiling regions if they
2405 don't contain a set of subtrees, but it might be convenient to
2406 do so sometimes: in that case, the first line of the region is
2407 converted to a headline before refiling."
2408 :group 'org-refile
2409 :version "24.1"
2410 :type 'boolean)
2412 (defgroup org-todo nil
2413 "Options concerning TODO items in Org-mode."
2414 :tag "Org TODO"
2415 :group 'org)
2417 (defgroup org-progress nil
2418 "Options concerning Progress logging in Org-mode."
2419 :tag "Org Progress"
2420 :group 'org-time)
2422 (defvar org-todo-interpretation-widgets
2423 '((:tag "Sequence (cycling hits every state)" sequence)
2424 (:tag "Type (cycling directly to DONE)" type))
2425 "The available interpretation symbols for customizing `org-todo-keywords'.
2426 Interested libraries should add to this list.")
2428 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2429 "List of TODO entry keyword sequences and their interpretation.
2430 \\<org-mode-map>This is a list of sequences.
2432 Each sequence starts with a symbol, either `sequence' or `type',
2433 indicating if the keywords should be interpreted as a sequence of
2434 action steps, or as different types of TODO items. The first
2435 keywords are states requiring action - these states will select a headline
2436 for inclusion into the global TODO list Org-mode produces. If one of
2437 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2438 signify that no further action is necessary. If \"|\" is not found,
2439 the last keyword is treated as the only DONE state of the sequence.
2441 The command \\[org-todo] cycles an entry through these states, and one
2442 additional state where no keyword is present. For details about this
2443 cycling, see the manual.
2445 TODO keywords and interpretation can also be set on a per-file basis with
2446 the special #+SEQ_TODO and #+TYP_TODO lines.
2448 Each keyword can optionally specify a character for fast state selection
2449 \(in combination with the variable `org-use-fast-todo-selection')
2450 and specifiers for state change logging, using the same syntax that
2451 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2452 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2453 indicates to record a time stamp each time this state is selected.
2455 Each keyword may also specify if a timestamp or a note should be
2456 recorded when entering or leaving the state, by adding additional
2457 characters in the parenthesis after the keyword. This looks like this:
2458 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2459 record only the time of the state change. With X and Y being either
2460 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2461 Y when leaving the state if and only if the *target* state does not
2462 define X. You may omit any of the fast-selection key or X or /Y,
2463 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2465 For backward compatibility, this variable may also be just a list
2466 of keywords. In this case the interpretation (sequence or type) will be
2467 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2468 :group 'org-todo
2469 :group 'org-keywords
2470 :type '(choice
2471 (repeat :tag "Old syntax, just keywords"
2472 (string :tag "Keyword"))
2473 (repeat :tag "New syntax"
2474 (cons
2475 (choice
2476 :tag "Interpretation"
2477 ;;Quick and dirty way to see
2478 ;;`org-todo-interpretations'. This takes the
2479 ;;place of item arguments
2480 :convert-widget
2481 (lambda (widget)
2482 (widget-put widget
2483 :args (mapcar
2484 #'(lambda (x)
2485 (widget-convert
2486 (cons 'const x)))
2487 org-todo-interpretation-widgets))
2488 widget))
2489 (repeat
2490 (string :tag "Keyword"))))))
2492 (defvar org-todo-keywords-1 nil
2493 "All TODO and DONE keywords active in a buffer.")
2494 (make-variable-buffer-local 'org-todo-keywords-1)
2495 (defvar org-todo-keywords-for-agenda nil)
2496 (defvar org-done-keywords-for-agenda nil)
2497 (defvar org-todo-keyword-alist-for-agenda nil)
2498 (defvar org-tag-alist-for-agenda nil
2499 "Alist of all tags from all agenda files.")
2500 (defvar org-tag-groups-alist-for-agenda nil
2501 "Alist of all groups tags from all current agenda files.")
2502 (defvar org-tag-groups-alist nil)
2503 (make-variable-buffer-local 'org-tag-groups-alist)
2504 (defvar org-agenda-contributing-files nil)
2505 (defvar org-not-done-keywords nil)
2506 (make-variable-buffer-local 'org-not-done-keywords)
2507 (defvar org-done-keywords nil)
2508 (make-variable-buffer-local 'org-done-keywords)
2509 (defvar org-todo-heads nil)
2510 (make-variable-buffer-local 'org-todo-heads)
2511 (defvar org-todo-sets nil)
2512 (make-variable-buffer-local 'org-todo-sets)
2513 (defvar org-todo-log-states nil)
2514 (make-variable-buffer-local 'org-todo-log-states)
2515 (defvar org-todo-kwd-alist nil)
2516 (make-variable-buffer-local 'org-todo-kwd-alist)
2517 (defvar org-todo-key-alist nil)
2518 (make-variable-buffer-local 'org-todo-key-alist)
2519 (defvar org-todo-key-trigger nil)
2520 (make-variable-buffer-local 'org-todo-key-trigger)
2522 (defcustom org-todo-interpretation 'sequence
2523 "Controls how TODO keywords are interpreted.
2524 This variable is in principle obsolete and is only used for
2525 backward compatibility, if the interpretation of todo keywords is
2526 not given already in `org-todo-keywords'. See that variable for
2527 more information."
2528 :group 'org-todo
2529 :group 'org-keywords
2530 :type '(choice (const sequence)
2531 (const type)))
2533 (defcustom org-use-fast-todo-selection t
2534 "Non-nil means use the fast todo selection scheme with C-c C-t.
2535 This variable describes if and under what circumstances the cycling
2536 mechanism for TODO keywords will be replaced by a single-key, direct
2537 selection scheme.
2539 When nil, fast selection is never used.
2541 When the symbol `prefix', it will be used when `org-todo' is called
2542 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2543 `C-u t' in an agenda buffer.
2545 When t, fast selection is used by default. In this case, the prefix
2546 argument forces cycling instead.
2548 In all cases, the special interface is only used if access keys have
2549 actually been assigned by the user, i.e. if keywords in the configuration
2550 are followed by a letter in parenthesis, like TODO(t)."
2551 :group 'org-todo
2552 :type '(choice
2553 (const :tag "Never" nil)
2554 (const :tag "By default" t)
2555 (const :tag "Only with C-u C-c C-t" prefix)))
2557 (defcustom org-provide-todo-statistics t
2558 "Non-nil means update todo statistics after insert and toggle.
2559 ALL-HEADLINES means update todo statistics by including headlines
2560 with no TODO keyword as well, counting them as not done.
2561 A list of TODO keywords means the same, but skip keywords that are
2562 not in this list.
2563 When set to a list of two lists, the first list contains keywords
2564 to consider as TODO keywords, the second list contains keywords
2565 to consider as DONE keywords.
2567 When this is set, todo statistics is updated in the parent of the
2568 current entry each time a todo state is changed."
2569 :group 'org-todo
2570 :type '(choice
2571 (const :tag "Yes, only for TODO entries" t)
2572 (const :tag "Yes, including all entries" all-headlines)
2573 (repeat :tag "Yes, for TODOs in this list"
2574 (string :tag "TODO keyword"))
2575 (list :tag "Yes, for TODOs and DONEs in these lists"
2576 (repeat (string :tag "TODO keyword"))
2577 (repeat (string :tag "DONE keyword")))
2578 (other :tag "No TODO statistics" nil)))
2580 (defcustom org-hierarchical-todo-statistics t
2581 "Non-nil means TODO statistics covers just direct children.
2582 When nil, all entries in the subtree are considered.
2583 This has only an effect if `org-provide-todo-statistics' is set.
2584 To set this to nil for only a single subtree, use a COOKIE_DATA
2585 property and include the word \"recursive\" into the value."
2586 :group 'org-todo
2587 :type 'boolean)
2589 (defcustom org-after-todo-state-change-hook nil
2590 "Hook which is run after the state of a TODO item was changed.
2591 The new state (a string with a TODO keyword, or nil) is available in the
2592 Lisp variable `org-state'."
2593 :group 'org-todo
2594 :type 'hook)
2596 (defvar org-blocker-hook nil
2597 "Hook for functions that are allowed to block a state change.
2599 Functions in this hook should not modify the buffer.
2600 Each function gets as its single argument a property list,
2601 see `org-trigger-hook' for more information about this list.
2603 If any of the functions in this hook returns nil, the state change
2604 is blocked.")
2606 (defvar org-trigger-hook nil
2607 "Hook for functions that are triggered by a state change.
2609 Each function gets as its single argument a property list with at
2610 least the following elements:
2612 (:type type-of-change :position pos-at-entry-start
2613 :from old-state :to new-state)
2615 Depending on the type, more properties may be present.
2617 This mechanism is currently implemented for:
2619 TODO state changes
2620 ------------------
2621 :type todo-state-change
2622 :from previous state (keyword as a string), or nil, or a symbol
2623 'todo' or 'done', to indicate the general type of state.
2624 :to new state, like in :from")
2626 (defcustom org-enforce-todo-dependencies nil
2627 "Non-nil means undone TODO entries will block switching the parent to DONE.
2628 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2629 be blocked if any prior sibling is not yet done.
2630 Finally, if the parent is blocked because of ordered siblings of its own,
2631 the child will also be blocked."
2632 :set (lambda (var val)
2633 (set var val)
2634 (if val
2635 (add-hook 'org-blocker-hook
2636 'org-block-todo-from-children-or-siblings-or-parent)
2637 (remove-hook 'org-blocker-hook
2638 'org-block-todo-from-children-or-siblings-or-parent)))
2639 :group 'org-todo
2640 :type 'boolean)
2642 (defcustom org-enforce-todo-checkbox-dependencies nil
2643 "Non-nil means unchecked boxes will block switching the parent to DONE.
2644 When this is nil, checkboxes have no influence on switching TODO states.
2645 When non-nil, you first need to check off all check boxes before the TODO
2646 entry can be switched to DONE.
2647 This variable needs to be set before org.el is loaded, and you need to
2648 restart Emacs after a change to make the change effective. The only way
2649 to change is while Emacs is running is through the customize interface."
2650 :set (lambda (var val)
2651 (set var val)
2652 (if val
2653 (add-hook 'org-blocker-hook
2654 'org-block-todo-from-checkboxes)
2655 (remove-hook 'org-blocker-hook
2656 'org-block-todo-from-checkboxes)))
2657 :group 'org-todo
2658 :type 'boolean)
2660 (defcustom org-treat-insert-todo-heading-as-state-change nil
2661 "Non-nil means inserting a TODO heading is treated as state change.
2662 So when the command \\[org-insert-todo-heading] is used, state change
2663 logging will apply if appropriate. When nil, the new TODO item will
2664 be inserted directly, and no logging will take place."
2665 :group 'org-todo
2666 :type 'boolean)
2668 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2669 "Non-nil means switching TODO states with S-cursor counts as state change.
2670 This is the default behavior. However, setting this to nil allows a
2671 convenient way to select a TODO state and bypass any logging associated
2672 with that."
2673 :group 'org-todo
2674 :type 'boolean)
2676 (defcustom org-todo-state-tags-triggers nil
2677 "Tag changes that should be triggered by TODO state changes.
2678 This is a list. Each entry is
2680 (state-change (tag . flag) .......)
2682 State-change can be a string with a state, and empty string to indicate the
2683 state that has no TODO keyword, or it can be one of the symbols `todo'
2684 or `done', meaning any not-done or done state, respectively."
2685 :group 'org-todo
2686 :group 'org-tags
2687 :type '(repeat
2688 (cons (choice :tag "When changing to"
2689 (const :tag "Not-done state" todo)
2690 (const :tag "Done state" done)
2691 (string :tag "State"))
2692 (repeat
2693 (cons :tag "Tag action"
2694 (string :tag "Tag")
2695 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2697 (defcustom org-log-done nil
2698 "Information to record when a task moves to the DONE state.
2700 Possible values are:
2702 nil Don't add anything, just change the keyword
2703 time Add a time stamp to the task
2704 note Prompt for a note and add it with template `org-log-note-headings'
2706 This option can also be set with on a per-file-basis with
2708 #+STARTUP: nologdone
2709 #+STARTUP: logdone
2710 #+STARTUP: lognotedone
2712 You can have local logging settings for a subtree by setting the LOGGING
2713 property to one or more of these keywords."
2714 :group 'org-todo
2715 :group 'org-progress
2716 :type '(choice
2717 (const :tag "No logging" nil)
2718 (const :tag "Record CLOSED timestamp" time)
2719 (const :tag "Record CLOSED timestamp with note." note)))
2721 ;; Normalize old uses of org-log-done.
2722 (cond
2723 ((eq org-log-done t) (setq org-log-done 'time))
2724 ((and (listp org-log-done) (memq 'done org-log-done))
2725 (setq org-log-done 'note)))
2727 (defcustom org-log-reschedule nil
2728 "Information to record when the scheduling date of a tasks is modified.
2730 Possible values are:
2732 nil Don't add anything, just change the date
2733 time Add a time stamp to the task
2734 note Prompt for a note and add it with template `org-log-note-headings'
2736 This option can also be set with on a per-file-basis with
2738 #+STARTUP: nologreschedule
2739 #+STARTUP: logreschedule
2740 #+STARTUP: lognotereschedule"
2741 :group 'org-todo
2742 :group 'org-progress
2743 :type '(choice
2744 (const :tag "No logging" nil)
2745 (const :tag "Record timestamp" time)
2746 (const :tag "Record timestamp with note." note)))
2748 (defcustom org-log-redeadline nil
2749 "Information to record when the deadline date of a tasks is modified.
2751 Possible values are:
2753 nil Don't add anything, just change the date
2754 time Add a time stamp to the task
2755 note Prompt for a note and add it with template `org-log-note-headings'
2757 This option can also be set with on a per-file-basis with
2759 #+STARTUP: nologredeadline
2760 #+STARTUP: logredeadline
2761 #+STARTUP: lognoteredeadline
2763 You can have local logging settings for a subtree by setting the LOGGING
2764 property to one or more of these keywords."
2765 :group 'org-todo
2766 :group 'org-progress
2767 :type '(choice
2768 (const :tag "No logging" nil)
2769 (const :tag "Record timestamp" time)
2770 (const :tag "Record timestamp with note." note)))
2772 (defcustom org-log-note-clock-out nil
2773 "Non-nil means record a note when clocking out of an item.
2774 This can also be configured on a per-file basis by adding one of
2775 the following lines anywhere in the buffer:
2777 #+STARTUP: lognoteclock-out
2778 #+STARTUP: nolognoteclock-out"
2779 :group 'org-todo
2780 :group 'org-progress
2781 :type 'boolean)
2783 (defcustom org-log-done-with-time t
2784 "Non-nil means the CLOSED time stamp will contain date and time.
2785 When nil, only the date will be recorded."
2786 :group 'org-progress
2787 :type 'boolean)
2789 (defcustom org-log-note-headings
2790 '((done . "CLOSING NOTE %t")
2791 (state . "State %-12s from %-12S %t")
2792 (note . "Note taken on %t")
2793 (reschedule . "Rescheduled from %S on %t")
2794 (delschedule . "Not scheduled, was %S on %t")
2795 (redeadline . "New deadline from %S on %t")
2796 (deldeadline . "Removed deadline, was %S on %t")
2797 (refile . "Refiled on %t")
2798 (clock-out . ""))
2799 "Headings for notes added to entries.
2800 The value is an alist, with the car being a symbol indicating the note
2801 context, and the cdr is the heading to be used. The heading may also be the
2802 empty string.
2803 %t in the heading will be replaced by a time stamp.
2804 %T will be an active time stamp instead the default inactive one
2805 %d will be replaced by a short-format time stamp.
2806 %D will be replaced by an active short-format time stamp.
2807 %s will be replaced by the new TODO state, in double quotes.
2808 %S will be replaced by the old TODO state, in double quotes.
2809 %u will be replaced by the user name.
2810 %U will be replaced by the full user name.
2812 In fact, it is not a good idea to change the `state' entry, because
2813 agenda log mode depends on the format of these entries."
2814 :group 'org-todo
2815 :group 'org-progress
2816 :type '(list :greedy t
2817 (cons (const :tag "Heading when closing an item" done) string)
2818 (cons (const :tag
2819 "Heading when changing todo state (todo sequence only)"
2820 state) string)
2821 (cons (const :tag "Heading when just taking a note" note) string)
2822 (cons (const :tag "Heading when rescheduling" reschedule) string)
2823 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2824 (cons (const :tag "Heading when changing deadline" redeadline) string)
2825 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2826 (cons (const :tag "Heading when refiling" refile) string)
2827 (cons (const :tag "Heading when clocking out" clock-out) string)))
2829 (unless (assq 'note org-log-note-headings)
2830 (push '(note . "%t") org-log-note-headings))
2832 (defcustom org-log-into-drawer nil
2833 "Non-nil means insert state change notes and time stamps into a drawer.
2834 When nil, state changes notes will be inserted after the headline and
2835 any scheduling and clock lines, but not inside a drawer.
2837 The value of this variable should be the name of the drawer to use.
2838 LOGBOOK is proposed as the default drawer for this purpose, you can
2839 also set this to a string to define the drawer of your choice.
2841 A value of t is also allowed, representing \"LOGBOOK\".
2843 A value of t or nil can also be set with on a per-file-basis with
2845 #+STARTUP: logdrawer
2846 #+STARTUP: nologdrawer
2848 If this variable is set, `org-log-state-notes-insert-after-drawers'
2849 will be ignored.
2851 You can set the property LOG_INTO_DRAWER to overrule this setting for
2852 a subtree."
2853 :group 'org-todo
2854 :group 'org-progress
2855 :type '(choice
2856 (const :tag "Not into a drawer" nil)
2857 (const :tag "LOGBOOK" t)
2858 (string :tag "Other")))
2860 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2862 (defun org-log-into-drawer ()
2863 "Return the value of `org-log-into-drawer', but let properties overrule.
2864 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2865 used instead of the default value."
2866 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2867 (cond
2868 ((not p) org-log-into-drawer)
2869 ((equal p "nil") nil)
2870 ((equal p "t") "LOGBOOK")
2871 (t p))))
2873 (defcustom org-log-state-notes-insert-after-drawers nil
2874 "Non-nil means insert state change notes after any drawers in entry.
2875 Only the drawers that *immediately* follow the headline and the
2876 deadline/scheduled line are skipped.
2877 When nil, insert notes right after the heading and perhaps the line
2878 with deadline/scheduling if present.
2880 This variable will have no effect if `org-log-into-drawer' is
2881 set."
2882 :group 'org-todo
2883 :group 'org-progress
2884 :type 'boolean)
2886 (defcustom org-log-states-order-reversed t
2887 "Non-nil means the latest state note will be directly after heading.
2888 When nil, the state change notes will be ordered according to time.
2890 This option can also be set with on a per-file-basis with
2892 #+STARTUP: logstatesreversed
2893 #+STARTUP: nologstatesreversed"
2894 :group 'org-todo
2895 :group 'org-progress
2896 :type 'boolean)
2898 (defcustom org-todo-repeat-to-state nil
2899 "The TODO state to which a repeater should return the repeating task.
2900 By default this is the first task in a TODO sequence, or the previous state
2901 in a TODO_TYP set. But you can specify another task here.
2902 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2903 :group 'org-todo
2904 :version "24.1"
2905 :type '(choice (const :tag "Head of sequence" nil)
2906 (string :tag "Specific state")))
2908 (defcustom org-log-repeat 'time
2909 "Non-nil means record moving through the DONE state when triggering repeat.
2910 An auto-repeating task is immediately switched back to TODO when
2911 marked DONE. If you are not logging state changes (by adding \"@\"
2912 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2913 record a closing note, there will be no record of the task moving
2914 through DONE. This variable forces taking a note anyway.
2916 nil Don't force a record
2917 time Record a time stamp
2918 note Prompt for a note and add it with template `org-log-note-headings'
2920 This option can also be set with on a per-file-basis with
2922 #+STARTUP: nologrepeat
2923 #+STARTUP: logrepeat
2924 #+STARTUP: lognoterepeat
2926 You can have local logging settings for a subtree by setting the LOGGING
2927 property to one or more of these keywords."
2928 :group 'org-todo
2929 :group 'org-progress
2930 :type '(choice
2931 (const :tag "Don't force a record" nil)
2932 (const :tag "Force recording the DONE state" time)
2933 (const :tag "Force recording a note with the DONE state" note)))
2936 (defgroup org-priorities nil
2937 "Priorities in Org-mode."
2938 :tag "Org Priorities"
2939 :group 'org-todo)
2941 (defcustom org-enable-priority-commands t
2942 "Non-nil means priority commands are active.
2943 When nil, these commands will be disabled, so that you never accidentally
2944 set a priority."
2945 :group 'org-priorities
2946 :type 'boolean)
2948 (defcustom org-highest-priority ?A
2949 "The highest priority of TODO items. A character like ?A, ?B etc.
2950 Must have a smaller ASCII number than `org-lowest-priority'."
2951 :group 'org-priorities
2952 :type 'character)
2954 (defcustom org-lowest-priority ?C
2955 "The lowest priority of TODO items. A character like ?A, ?B etc.
2956 Must have a larger ASCII number than `org-highest-priority'."
2957 :group 'org-priorities
2958 :type 'character)
2960 (defcustom org-default-priority ?B
2961 "The default priority of TODO items.
2962 This is the priority an item gets if no explicit priority is given.
2963 When starting to cycle on an empty priority the first step in the cycle
2964 depends on `org-priority-start-cycle-with-default'. The resulting first
2965 step priority must not exceed the range from `org-highest-priority' to
2966 `org-lowest-priority' which means that `org-default-priority' has to be
2967 in this range exclusive or inclusive the range boundaries. Else the
2968 first step refuses to set the default and the second will fall back
2969 to (depending on the command used) the highest or lowest priority."
2970 :group 'org-priorities
2971 :type 'character)
2973 (defcustom org-priority-start-cycle-with-default t
2974 "Non-nil means start with default priority when starting to cycle.
2975 When this is nil, the first step in the cycle will be (depending on the
2976 command used) one higher or lower than the default priority.
2977 See also `org-default-priority'."
2978 :group 'org-priorities
2979 :type 'boolean)
2981 (defcustom org-get-priority-function nil
2982 "Function to extract the priority from a string.
2983 The string is normally the headline. If this is nil Org computes the
2984 priority from the priority cookie like [#A] in the headline. It returns
2985 an integer, increasing by 1000 for each priority level.
2986 The user can set a different function here, which should take a string
2987 as an argument and return the numeric priority."
2988 :group 'org-priorities
2989 :version "24.1"
2990 :type '(choice
2991 (const nil)
2992 (function)))
2994 (defgroup org-time nil
2995 "Options concerning time stamps and deadlines in Org-mode."
2996 :tag "Org Time"
2997 :group 'org)
2999 (defcustom org-insert-labeled-timestamps-at-point nil
3000 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
3001 When nil, these labeled time stamps are forces into the second line of an
3002 entry, just after the headline. When scheduling from the global TODO list,
3003 the time stamp will always be forced into the second line."
3004 :group 'org-time
3005 :type 'boolean)
3007 (defcustom org-time-stamp-rounding-minutes '(0 5)
3008 "Number of minutes to round time stamps to.
3009 These are two values, the first applies when first creating a time stamp.
3010 The second applies when changing it with the commands `S-up' and `S-down'.
3011 When changing the time stamp, this means that it will change in steps
3012 of N minutes, as given by the second value.
3014 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3015 numbers should be factors of 60, so for example 5, 10, 15.
3017 When this is larger than 1, you can still force an exact time stamp by using
3018 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3019 and by using a prefix arg to `S-up/down' to specify the exact number
3020 of minutes to shift."
3021 :group 'org-time
3022 :get #'(lambda (var) ; Make sure both elements are there
3023 (if (integerp (default-value var))
3024 (list (default-value var) 5)
3025 (default-value var)))
3026 :type '(list
3027 (integer :tag "when inserting times")
3028 (integer :tag "when modifying times")))
3030 ;; Normalize old customizations of this variable.
3031 (when (integerp org-time-stamp-rounding-minutes)
3032 (setq org-time-stamp-rounding-minutes
3033 (list org-time-stamp-rounding-minutes
3034 org-time-stamp-rounding-minutes)))
3036 (defcustom org-display-custom-times nil
3037 "Non-nil means overlay custom formats over all time stamps.
3038 The formats are defined through the variable `org-time-stamp-custom-formats'.
3039 To turn this on on a per-file basis, insert anywhere in the file:
3040 #+STARTUP: customtime"
3041 :group 'org-time
3042 :set 'set-default
3043 :type 'sexp)
3044 (make-variable-buffer-local 'org-display-custom-times)
3046 (defcustom org-time-stamp-custom-formats
3047 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3048 "Custom formats for time stamps. See `format-time-string' for the syntax.
3049 These are overlaid over the default ISO format if the variable
3050 `org-display-custom-times' is set. Time like %H:%M should be at the
3051 end of the second format. The custom formats are also honored by export
3052 commands, if custom time display is turned on at the time of export."
3053 :group 'org-time
3054 :type 'sexp)
3056 (defun org-time-stamp-format (&optional long inactive)
3057 "Get the right format for a time string."
3058 (let ((f (if long (cdr org-time-stamp-formats)
3059 (car org-time-stamp-formats))))
3060 (if inactive
3061 (concat "[" (substring f 1 -1) "]")
3062 f)))
3064 (defcustom org-time-clocksum-format
3065 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3066 "The format string used when creating CLOCKSUM lines.
3067 This is also used when Org mode generates a time duration.
3069 The value can be a single format string containing two
3070 %-sequences, which will be filled with the number of hours and
3071 minutes in that order.
3073 Alternatively, the value can be a plist associating any of the
3074 keys :years, :months, :weeks, :days, :hours or :minutes with
3075 format strings. The time duration is formatted using only the
3076 time components that are needed and concatenating the results.
3077 If a time unit in absent, it falls back to the next smallest
3078 unit.
3080 The keys :require-years, :require-months, :require-days,
3081 :require-weeks, :require-hours, :require-minutes are also
3082 meaningful. A non-nil value for these keys indicates that the
3083 corresponding time component should always be included, even if
3084 its value is 0.
3087 For example,
3089 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3090 :require-minutes t)
3092 means durations longer than a day will be expressed in days,
3093 hours and minutes, and durations less than a day will always be
3094 expressed in hours and minutes (even for durations less than an
3095 hour).
3097 The value
3099 \(:days \"%dd\" :minutes \"%dm\")
3101 means durations longer than a day will be expressed in days and
3102 minutes, and durations less than a day will be expressed entirely
3103 in minutes (even for durations longer than an hour)."
3104 :group 'org-time
3105 :group 'org-clock
3106 :version "24.4"
3107 :package-version '(Org . "8.0")
3108 :type '(choice (string :tag "Format string")
3109 (set :tag "Plist"
3110 (group :inline t (const :tag "Years" :years)
3111 (string :tag "Format string"))
3112 (group :inline t
3113 (const :tag "Always show years" :require-years)
3114 (const t))
3115 (group :inline t (const :tag "Months" :months)
3116 (string :tag "Format string"))
3117 (group :inline t
3118 (const :tag "Always show months" :require-months)
3119 (const t))
3120 (group :inline t (const :tag "Weeks" :weeks)
3121 (string :tag "Format string"))
3122 (group :inline t
3123 (const :tag "Always show weeks" :require-weeks)
3124 (const t))
3125 (group :inline t (const :tag "Days" :days)
3126 (string :tag "Format string"))
3127 (group :inline t
3128 (const :tag "Always show days" :require-days)
3129 (const t))
3130 (group :inline t (const :tag "Hours" :hours)
3131 (string :tag "Format string"))
3132 (group :inline t
3133 (const :tag "Always show hours" :require-hours)
3134 (const t))
3135 (group :inline t (const :tag "Minutes" :minutes)
3136 (string :tag "Format string"))
3137 (group :inline t
3138 (const :tag "Always show minutes" :require-minutes)
3139 (const t)))))
3141 (defcustom org-time-clocksum-use-fractional nil
3142 "When non-nil, \\[org-clock-display] uses fractional times.
3143 See `org-time-clocksum-format' for more on time clock formats."
3144 :group 'org-time
3145 :group 'org-clock
3146 :version "24.3"
3147 :type 'boolean)
3149 (defcustom org-time-clocksum-use-effort-durations nil
3150 "When non-nil, \\[org-clock-display] uses effort durations.
3151 E.g. by default, one day is considered to be a 8 hours effort,
3152 so a task that has been clocked for 16 hours will be displayed
3153 as during 2 days in the clock display or in the clocktable.
3155 See `org-effort-durations' on how to set effort durations
3156 and `org-time-clocksum-format' for more on time clock formats."
3157 :group 'org-time
3158 :group 'org-clock
3159 :version "24.4"
3160 :package-version '(Org . "8.0")
3161 :type 'boolean)
3163 (defcustom org-time-clocksum-fractional-format "%.2f"
3164 "The format string used when creating CLOCKSUM lines,
3165 or when Org mode generates a time duration, if
3166 `org-time-clocksum-use-fractional' is enabled.
3168 The value can be a single format string containing one
3169 %-sequence, which will be filled with the number of hours as
3170 a float.
3172 Alternatively, the value can be a plist associating any of the
3173 keys :years, :months, :weeks, :days, :hours or :minutes with
3174 a format string. The time duration is formatted using the
3175 largest time unit which gives a non-zero integer part. If all
3176 specified formats have zero integer part, the smallest time unit
3177 is used."
3178 :group 'org-time
3179 :type '(choice (string :tag "Format string")
3180 (set (group :inline t (const :tag "Years" :years)
3181 (string :tag "Format string"))
3182 (group :inline t (const :tag "Months" :months)
3183 (string :tag "Format string"))
3184 (group :inline t (const :tag "Weeks" :weeks)
3185 (string :tag "Format string"))
3186 (group :inline t (const :tag "Days" :days)
3187 (string :tag "Format string"))
3188 (group :inline t (const :tag "Hours" :hours)
3189 (string :tag "Format string"))
3190 (group :inline t (const :tag "Minutes" :minutes)
3191 (string :tag "Format string")))))
3193 (defcustom org-deadline-warning-days 14
3194 "Number of days before expiration during which a deadline becomes active.
3195 This variable governs the display in sparse trees and in the agenda.
3196 When 0 or negative, it means use this number (the absolute value of it)
3197 even if a deadline has a different individual lead time specified.
3199 Custom commands can set this variable in the options section."
3200 :group 'org-time
3201 :group 'org-agenda-daily/weekly
3202 :type 'integer)
3204 (defcustom org-scheduled-delay-days 0
3205 "Number of days before a scheduled item becomes active.
3206 This variable governs the display in sparse trees and in the agenda.
3207 The default value (i.e. 0) means: don't delay scheduled item.
3208 When negative, it means use this number (the absolute value of it)
3209 even if a scheduled item has a different individual delay time
3210 specified.
3212 Custom commands can set this variable in the options section."
3213 :group 'org-time
3214 :group 'org-agenda-daily/weekly
3215 :version "24.4"
3216 :package-version '(Org . "8.0")
3217 :type 'integer)
3219 (defcustom org-read-date-prefer-future t
3220 "Non-nil means assume future for incomplete date input from user.
3221 This affects the following situations:
3222 1. The user gives a month but not a year.
3223 For example, if it is April and you enter \"feb 2\", this will be read
3224 as Feb 2, *next* year. \"May 5\", however, will be this year.
3225 2. The user gives a day, but no month.
3226 For example, if today is the 15th, and you enter \"3\", Org-mode will
3227 read this as the third of *next* month. However, if you enter \"17\",
3228 it will be considered as *this* month.
3230 If you set this variable to the symbol `time', then also the following
3231 will work:
3233 3. If the user gives a time.
3234 If the time is before now, it will be interpreted as tomorrow.
3236 Currently none of this works for ISO week specifications.
3238 When this option is nil, the current day, month and year will always be
3239 used as defaults.
3241 See also `org-agenda-jump-prefer-future'."
3242 :group 'org-time
3243 :type '(choice
3244 (const :tag "Never" nil)
3245 (const :tag "Check month and day" t)
3246 (const :tag "Check month, day, and time" time)))
3248 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3249 "Should the agenda jump command prefer the future for incomplete dates?
3250 The default is to do the same as configured in `org-read-date-prefer-future'.
3251 But you can also set a deviating value here.
3252 This may t or nil, or the symbol `org-read-date-prefer-future'."
3253 :group 'org-agenda
3254 :group 'org-time
3255 :version "24.1"
3256 :type '(choice
3257 (const :tag "Use org-read-date-prefer-future"
3258 org-read-date-prefer-future)
3259 (const :tag "Never" nil)
3260 (const :tag "Always" t)))
3262 (defcustom org-read-date-force-compatible-dates t
3263 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3265 Depending on the system Emacs is running on, certain dates cannot
3266 be represented with the type used internally to represent time.
3267 Dates between 1970-1-1 and 2038-1-1 can always be represented
3268 correctly. Some systems allow for earlier dates, some for later,
3269 some for both. One way to find out it to insert any date into an
3270 Org buffer, putting the cursor on the year and hitting S-up and
3271 S-down to test the range.
3273 When this variable is set to t, the date/time prompt will not let
3274 you specify dates outside the 1970-2037 range, so it is certain that
3275 these dates will work in whatever version of Emacs you are
3276 running, and also that you can move a file from one Emacs implementation
3277 to another. WHenever Org is forcing the year for you, it will display
3278 a message and beep.
3280 When this variable is nil, Org will check if the date is
3281 representable in the specific Emacs implementation you are using.
3282 If not, it will force a year, usually the current year, and beep
3283 to remind you. Currently this setting is not recommended because
3284 the likelihood that you will open your Org files in an Emacs that
3285 has limited date range is not negligible.
3287 A workaround for this problem is to use diary sexp dates for time
3288 stamps outside of this range."
3289 :group 'org-time
3290 :version "24.1"
3291 :type 'boolean)
3293 (defcustom org-read-date-display-live t
3294 "Non-nil means display current interpretation of date prompt live.
3295 This display will be in an overlay, in the minibuffer."
3296 :group 'org-time
3297 :type 'boolean)
3299 (defcustom org-read-date-popup-calendar t
3300 "Non-nil means pop up a calendar when prompting for a date.
3301 In the calendar, the date can be selected with mouse-1. However, the
3302 minibuffer will also be active, and you can simply enter the date as well.
3303 When nil, only the minibuffer will be available."
3304 :group 'org-time
3305 :type 'boolean)
3306 (org-defvaralias 'org-popup-calendar-for-date-prompt
3307 'org-read-date-popup-calendar)
3309 (make-obsolete-variable
3310 'org-read-date-minibuffer-setup-hook
3311 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3312 (defcustom org-read-date-minibuffer-setup-hook nil
3313 "Hook to be used to set up keys for the date/time interface.
3314 Add key definitions to `minibuffer-local-map', which will be a
3315 temporary copy.
3317 WARNING: This option is obsolete, you should use
3318 `org-read-date-minibuffer-local-map' to set up keys."
3319 :group 'org-time
3320 :type 'hook)
3322 (defcustom org-extend-today-until 0
3323 "The hour when your day really ends. Must be an integer.
3324 This has influence for the following applications:
3325 - When switching the agenda to \"today\". It it is still earlier than
3326 the time given here, the day recognized as TODAY is actually yesterday.
3327 - When a date is read from the user and it is still before the time given
3328 here, the current date and time will be assumed to be yesterday, 23:59.
3329 Also, timestamps inserted in capture templates follow this rule.
3331 IMPORTANT: This is a feature whose implementation is and likely will
3332 remain incomplete. Really, it is only here because past midnight seems to
3333 be the favorite working time of John Wiegley :-)"
3334 :group 'org-time
3335 :type 'integer)
3337 (defcustom org-use-effective-time nil
3338 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3339 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3340 \"effective time\" of any timestamps between midnight and 8am will be
3341 23:59 of the previous day."
3342 :group 'org-time
3343 :version "24.1"
3344 :type 'boolean)
3346 (defcustom org-use-last-clock-out-time-as-effective-time nil
3347 "When non-nil, use the last clock out time for `org-todo'.
3348 Note that this option has precedence over the combined use of
3349 `org-use-effective-time' and `org-extend-today-until'."
3350 :group 'org-time
3351 :version "24.4"
3352 :package-version '(Org . "8.0")
3353 :type 'boolean)
3355 (defcustom org-edit-timestamp-down-means-later nil
3356 "Non-nil means S-down will increase the time in a time stamp.
3357 When nil, S-up will increase."
3358 :group 'org-time
3359 :type 'boolean)
3361 (defcustom org-calendar-follow-timestamp-change t
3362 "Non-nil means make the calendar window follow timestamp changes.
3363 When a timestamp is modified and the calendar window is visible, it will be
3364 moved to the new date."
3365 :group 'org-time
3366 :type 'boolean)
3368 (defgroup org-tags nil
3369 "Options concerning tags in Org-mode."
3370 :tag "Org Tags"
3371 :group 'org)
3373 (defcustom org-tag-alist nil
3374 "List of tags allowed in Org-mode files.
3375 When this list is nil, Org-mode will base TAG input on what is already in the
3376 buffer.
3377 The value of this variable is an alist, the car of each entry must be a
3378 keyword as a string, the cdr may be a character that is used to select
3379 that tag through the fast-tag-selection interface.
3380 See the manual for details."
3381 :group 'org-tags
3382 :type '(repeat
3383 (choice
3384 (cons (string :tag "Tag name")
3385 (character :tag "Access char"))
3386 (list :tag "Start radio group"
3387 (const :startgroup)
3388 (option (string :tag "Group description")))
3389 (list :tag "Group tags delimiter"
3390 (const :grouptags))
3391 (list :tag "End radio group"
3392 (const :endgroup)
3393 (option (string :tag "Group description")))
3394 (const :tag "New line" (:newline)))))
3396 (defcustom org-tag-persistent-alist nil
3397 "List of tags that will always appear in all Org-mode files.
3398 This is in addition to any in buffer settings or customizations
3399 of `org-tag-alist'.
3400 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3401 The value of this variable is an alist, the car of each entry must be a
3402 keyword as a string, the cdr may be a character that is used to select
3403 that tag through the fast-tag-selection interface.
3404 See the manual for details.
3405 To disable these tags on a per-file basis, insert anywhere in the file:
3406 #+STARTUP: noptag"
3407 :group 'org-tags
3408 :type '(repeat
3409 (choice
3410 (cons (string :tag "Tag name")
3411 (character :tag "Access char"))
3412 (const :tag "Start radio group" (:startgroup))
3413 (const :tag "Group tags delimiter" (:grouptags))
3414 (const :tag "End radio group" (:endgroup))
3415 (const :tag "New line" (:newline)))))
3417 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3418 "If non-nil, always offer completion for all tags of all agenda files.
3419 Instead of customizing this variable directly, you might want to
3420 set it locally for capture buffers, because there no list of
3421 tags in that file can be created dynamically (there are none).
3423 (add-hook 'org-capture-mode-hook
3424 (lambda ()
3425 (set (make-local-variable
3426 'org-complete-tags-always-offer-all-agenda-tags)
3427 t)))"
3428 :group 'org-tags
3429 :version "24.1"
3430 :type 'boolean)
3432 (defvar org-file-tags nil
3433 "List of tags that can be inherited by all entries in the file.
3434 The tags will be inherited if the variable `org-use-tag-inheritance'
3435 says they should be.
3436 This variable is populated from #+FILETAGS lines.")
3438 (defcustom org-use-fast-tag-selection 'auto
3439 "Non-nil means use fast tag selection scheme.
3440 This is a special interface to select and deselect tags with single keys.
3441 When nil, fast selection is never used.
3442 When the symbol `auto', fast selection is used if and only if selection
3443 characters for tags have been configured, either through the variable
3444 `org-tag-alist' or through a #+TAGS line in the buffer.
3445 When t, fast selection is always used and selection keys are assigned
3446 automatically if necessary."
3447 :group 'org-tags
3448 :type '(choice
3449 (const :tag "Always" t)
3450 (const :tag "Never" nil)
3451 (const :tag "When selection characters are configured" auto)))
3453 (defcustom org-fast-tag-selection-single-key nil
3454 "Non-nil means fast tag selection exits after first change.
3455 When nil, you have to press RET to exit it.
3456 During fast tag selection, you can toggle this flag with `C-c'.
3457 This variable can also have the value `expert'. In this case, the window
3458 displaying the tags menu is not even shown, until you press C-c again."
3459 :group 'org-tags
3460 :type '(choice
3461 (const :tag "No" nil)
3462 (const :tag "Yes" t)
3463 (const :tag "Expert" expert)))
3465 (defvar org-fast-tag-selection-include-todo nil
3466 "Non-nil means fast tags selection interface will also offer TODO states.
3467 This is an undocumented feature, you should not rely on it.")
3469 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3470 "The column to which tags should be indented in a headline.
3471 If this number is positive, it specifies the column. If it is negative,
3472 it means that the tags should be flushright to that column. For example,
3473 -80 works well for a normal 80 character screen.
3474 When 0, place tags directly after headline text, with only one space in
3475 between."
3476 :group 'org-tags
3477 :type 'integer)
3479 (defcustom org-auto-align-tags t
3480 "Non-nil keeps tags aligned when modifying headlines.
3481 Some operations (i.e. demoting) change the length of a headline and
3482 therefore shift the tags around. With this option turned on, after
3483 each such operation the tags are again aligned to `org-tags-column'."
3484 :group 'org-tags
3485 :type 'boolean)
3487 (defcustom org-use-tag-inheritance t
3488 "Non-nil means tags in levels apply also for sublevels.
3489 When nil, only the tags directly given in a specific line apply there.
3490 This may also be a list of tags that should be inherited, or a regexp that
3491 matches tags that should be inherited. Additional control is possible
3492 with the variable `org-tags-exclude-from-inheritance' which gives an
3493 explicit list of tags to be excluded from inheritance, even if the value of
3494 `org-use-tag-inheritance' would select it for inheritance.
3496 If this option is t, a match early-on in a tree can lead to a large
3497 number of matches in the subtree when constructing the agenda or creating
3498 a sparse tree. If you only want to see the first match in a tree during
3499 a search, check out the variable `org-tags-match-list-sublevels'."
3500 :group 'org-tags
3501 :type '(choice
3502 (const :tag "Not" nil)
3503 (const :tag "Always" t)
3504 (repeat :tag "Specific tags" (string :tag "Tag"))
3505 (regexp :tag "Tags matched by regexp")))
3507 (defcustom org-tags-exclude-from-inheritance nil
3508 "List of tags that should never be inherited.
3509 This is a way to exclude a few tags from inheritance. For way to do
3510 the opposite, to actively allow inheritance for selected tags,
3511 see the variable `org-use-tag-inheritance'."
3512 :group 'org-tags
3513 :type '(repeat (string :tag "Tag")))
3515 (defun org-tag-inherit-p (tag)
3516 "Check if TAG is one that should be inherited."
3517 (cond
3518 ((member tag org-tags-exclude-from-inheritance) nil)
3519 ((eq org-use-tag-inheritance t) t)
3520 ((not org-use-tag-inheritance) nil)
3521 ((stringp org-use-tag-inheritance)
3522 (string-match org-use-tag-inheritance tag))
3523 ((listp org-use-tag-inheritance)
3524 (member tag org-use-tag-inheritance))
3525 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3527 (defcustom org-tags-match-list-sublevels t
3528 "Non-nil means list also sublevels of headlines matching a search.
3529 This variable applies to tags/property searches, and also to stuck
3530 projects because this search is based on a tags match as well.
3532 When set to the symbol `indented', sublevels are indented with
3533 leading dots.
3535 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3536 the sublevels of a headline matching a tag search often also match
3537 the same search. Listing all of them can create very long lists.
3538 Setting this variable to nil causes subtrees of a match to be skipped.
3540 This variable is semi-obsolete and probably should always be true. It
3541 is better to limit inheritance to certain tags using the variables
3542 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3543 :group 'org-tags
3544 :type '(choice
3545 (const :tag "No, don't list them" nil)
3546 (const :tag "Yes, do list them" t)
3547 (const :tag "List them, indented with leading dots" indented)))
3549 (defcustom org-tags-sort-function nil
3550 "When set, tags are sorted using this function as a comparator."
3551 :group 'org-tags
3552 :type '(choice
3553 (const :tag "No sorting" nil)
3554 (const :tag "Alphabetical" string<)
3555 (const :tag "Reverse alphabetical" string>)
3556 (function :tag "Custom function" nil)))
3558 (defvar org-tags-history nil
3559 "History of minibuffer reads for tags.")
3560 (defvar org-last-tags-completion-table nil
3561 "The last used completion table for tags.")
3562 (defvar org-after-tags-change-hook nil
3563 "Hook that is run after the tags in a line have changed.")
3565 (defgroup org-properties nil
3566 "Options concerning properties in Org-mode."
3567 :tag "Org Properties"
3568 :group 'org)
3570 (defcustom org-property-format "%-10s %s"
3571 "How property key/value pairs should be formatted by `indent-line'.
3572 When `indent-line' hits a property definition, it will format the line
3573 according to this format, mainly to make sure that the values are
3574 lined-up with respect to each other."
3575 :group 'org-properties
3576 :type 'string)
3578 (defcustom org-properties-postprocess-alist nil
3579 "Alist of properties and functions to adjust inserted values.
3580 Elements of this alist must be of the form
3582 ([string] [function])
3584 where [string] must be a property name and [function] must be a
3585 lambda expression: this lambda expression must take one argument,
3586 the value to adjust, and return the new value as a string.
3588 For example, this element will allow the property \"Remaining\"
3589 to be updated wrt the relation between the \"Effort\" property
3590 and the clock summary:
3592 ((\"Remaining\" (lambda(value)
3593 (let ((clocksum (org-clock-sum-current-item))
3594 (effort (org-duration-string-to-minutes
3595 (org-entry-get (point) \"Effort\"))))
3596 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3597 :group 'org-properties
3598 :version "24.1"
3599 :type '(alist :key-type (string :tag "Property")
3600 :value-type (function :tag "Function")))
3602 (defcustom org-use-property-inheritance nil
3603 "Non-nil means properties apply also for sublevels.
3605 This setting is chiefly used during property searches. Turning it on can
3606 cause significant overhead when doing a search, which is why it is not
3607 on by default.
3609 When nil, only the properties directly given in the current entry count.
3610 When t, every property is inherited. The value may also be a list of
3611 properties that should have inheritance, or a regular expression matching
3612 properties that should be inherited.
3614 However, note that some special properties use inheritance under special
3615 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3616 and the properties ending in \"_ALL\" when they are used as descriptor
3617 for valid values of a property.
3619 Note for programmers:
3620 When querying an entry with `org-entry-get', you can control if inheritance
3621 should be used. By default, `org-entry-get' looks only at the local
3622 properties. You can request inheritance by setting the inherit argument
3623 to t (to force inheritance) or to `selective' (to respect the setting
3624 in this variable)."
3625 :group 'org-properties
3626 :type '(choice
3627 (const :tag "Not" nil)
3628 (const :tag "Always" t)
3629 (repeat :tag "Specific properties" (string :tag "Property"))
3630 (regexp :tag "Properties matched by regexp")))
3632 (defun org-property-inherit-p (property)
3633 "Check if PROPERTY is one that should be inherited."
3634 (cond
3635 ((eq org-use-property-inheritance t) t)
3636 ((not org-use-property-inheritance) nil)
3637 ((stringp org-use-property-inheritance)
3638 (string-match org-use-property-inheritance property))
3639 ((listp org-use-property-inheritance)
3640 (member property org-use-property-inheritance))
3641 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3643 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3644 "The default column format, if no other format has been defined.
3645 This variable can be set on the per-file basis by inserting a line
3647 #+COLUMNS: %25ITEM ....."
3648 :group 'org-properties
3649 :type 'string)
3651 (defcustom org-columns-ellipses ".."
3652 "The ellipses to be used when a field in column view is truncated.
3653 When this is the empty string, as many characters as possible are shown,
3654 but then there will be no visual indication that the field has been truncated.
3655 When this is a string of length N, the last N characters of a truncated
3656 field are replaced by this string. If the column is narrower than the
3657 ellipses string, only part of the ellipses string will be shown."
3658 :group 'org-properties
3659 :type 'string)
3661 (defcustom org-columns-modify-value-for-display-function nil
3662 "Function that modifies values for display in column view.
3663 For example, it can be used to cut out a certain part from a time stamp.
3664 The function must take 2 arguments:
3666 column-title The title of the column (*not* the property name)
3667 value The value that should be modified.
3669 The function should return the value that should be displayed,
3670 or nil if the normal value should be used."
3671 :group 'org-properties
3672 :type '(choice (const nil) (function)))
3674 (defconst org-global-properties-fixed
3675 '(("VISIBILITY_ALL" . "folded children content all")
3676 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3677 "List of property/value pairs that can be inherited by any entry.
3679 These are fixed values, for the preset properties. The user variable
3680 that can be used to add to this list is `org-global-properties'.
3682 The entries in this list are cons cells where the car is a property
3683 name and cdr is a string with the value. If the value represents
3684 multiple items like an \"_ALL\" property, separate the items by
3685 spaces.")
3687 (defcustom org-global-properties nil
3688 "List of property/value pairs that can be inherited by any entry.
3690 This list will be combined with the constant `org-global-properties-fixed'.
3692 The entries in this list are cons cells where the car is a property
3693 name and cdr is a string with the value.
3695 You can set buffer-local values for the same purpose in the variable
3696 `org-file-properties' this by adding lines like
3698 #+PROPERTY: NAME VALUE"
3699 :group 'org-properties
3700 :type '(repeat
3701 (cons (string :tag "Property")
3702 (string :tag "Value"))))
3704 (defvar org-file-properties nil
3705 "List of property/value pairs that can be inherited by any entry.
3706 Valid for the current buffer.
3707 This variable is populated from #+PROPERTY lines.")
3708 (make-variable-buffer-local 'org-file-properties)
3710 (defgroup org-agenda nil
3711 "Options concerning agenda views in Org-mode."
3712 :tag "Org Agenda"
3713 :group 'org)
3715 (defvar org-category nil
3716 "Variable used by org files to set a category for agenda display.
3717 Such files should use a file variable to set it, for example
3719 # -*- mode: org; org-category: \"ELisp\"
3721 or contain a special line
3723 #+CATEGORY: ELisp
3725 If the file does not specify a category, then file's base name
3726 is used instead.")
3727 (make-variable-buffer-local 'org-category)
3728 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3730 (defcustom org-agenda-files nil
3731 "The files to be used for agenda display.
3732 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3733 \\[org-remove-file]. You can also use customize to edit the list.
3735 If an entry is a directory, all files in that directory that are matched by
3736 `org-agenda-file-regexp' will be part of the file list.
3738 If the value of the variable is not a list but a single file name, then
3739 the list of agenda files is actually stored and maintained in that file, one
3740 agenda file per line. In this file paths can be given relative to
3741 `org-directory'. Tilde expansion and environment variable substitution
3742 are also made."
3743 :group 'org-agenda
3744 :type '(choice
3745 (repeat :tag "List of files and directories" file)
3746 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3748 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3749 "Regular expression to match files for `org-agenda-files'.
3750 If any element in the list in that variable contains a directory instead
3751 of a normal file, all files in that directory that are matched by this
3752 regular expression will be included."
3753 :group 'org-agenda
3754 :type 'regexp)
3756 (defcustom org-agenda-text-search-extra-files nil
3757 "List of extra files to be searched by text search commands.
3758 These files will be searched in addition to the agenda files by the
3759 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3760 Note that these files will only be searched for text search commands,
3761 not for the other agenda views like todo lists, tag searches or the weekly
3762 agenda. This variable is intended to list notes and possibly archive files
3763 that should also be searched by these two commands.
3764 In fact, if the first element in the list is the symbol `agenda-archives',
3765 then all archive files of all agenda files will be added to the search
3766 scope."
3767 :group 'org-agenda
3768 :type '(set :greedy t
3769 (const :tag "Agenda Archives" agenda-archives)
3770 (repeat :inline t (file))))
3772 (org-defvaralias 'org-agenda-multi-occur-extra-files
3773 'org-agenda-text-search-extra-files)
3775 (defcustom org-agenda-skip-unavailable-files nil
3776 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3777 A nil value means to remove them, after a query, from the list."
3778 :group 'org-agenda
3779 :type 'boolean)
3781 (defcustom org-calendar-to-agenda-key [?c]
3782 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3783 The command `org-calendar-goto-agenda' will be bound to this key. The
3784 default is the character `c' because then `c' can be used to switch back and
3785 forth between agenda and calendar."
3786 :group 'org-agenda
3787 :type 'sexp)
3789 (defcustom org-calendar-insert-diary-entry-key [?i]
3790 "The key to be installed in `calendar-mode-map' for adding diary entries.
3791 This option is irrelevant until `org-agenda-diary-file' has been configured
3792 to point to an Org-mode file. When that is the case, the command
3793 `org-agenda-diary-entry' will be bound to the key given here, by default
3794 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3795 if you want to continue doing this, you need to change this to a different
3796 key."
3797 :group 'org-agenda
3798 :type 'sexp)
3800 (defcustom org-agenda-diary-file 'diary-file
3801 "File to which to add new entries with the `i' key in agenda and calendar.
3802 When this is the symbol `diary-file', the functionality in the Emacs
3803 calendar will be used to add entries to the `diary-file'. But when this
3804 points to a file, `org-agenda-diary-entry' will be used instead."
3805 :group 'org-agenda
3806 :type '(choice
3807 (const :tag "The standard Emacs diary file" diary-file)
3808 (file :tag "Special Org file diary entries")))
3810 (eval-after-load "calendar"
3811 '(progn
3812 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3813 'org-calendar-goto-agenda)
3814 (add-hook 'calendar-mode-hook
3815 (lambda ()
3816 (unless (eq org-agenda-diary-file 'diary-file)
3817 (define-key calendar-mode-map
3818 org-calendar-insert-diary-entry-key
3819 'org-agenda-diary-entry))))))
3821 (defgroup org-latex nil
3822 "Options for embedding LaTeX code into Org-mode."
3823 :tag "Org LaTeX"
3824 :group 'org)
3826 (defcustom org-format-latex-options
3827 '(:foreground default :background default :scale 1.0
3828 :html-foreground "Black" :html-background "Transparent"
3829 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3830 "Options for creating images from LaTeX fragments.
3831 This is a property list with the following properties:
3832 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3833 `default' means use the foreground of the default face.
3834 `auto' means use the foreground from the text face.
3835 :background the background color, or \"Transparent\".
3836 `default' means use the background of the default face.
3837 `auto' means use the background from the text face.
3838 :scale a scaling factor for the size of the images, to get more pixels
3839 :html-foreground, :html-background, :html-scale
3840 the same numbers for HTML export.
3841 :matchers a list indicating which matchers should be used to
3842 find LaTeX fragments. Valid members of this list are:
3843 \"begin\" find environments
3844 \"$1\" find single characters surrounded by $.$
3845 \"$\" find math expressions surrounded by $...$
3846 \"$$\" find math expressions surrounded by $$....$$
3847 \"\\(\" find math expressions surrounded by \\(...\\)
3848 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3849 :group 'org-latex
3850 :type 'plist)
3852 (defcustom org-format-latex-signal-error t
3853 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3854 When nil, just push out a message."
3855 :group 'org-latex
3856 :version "24.1"
3857 :type 'boolean)
3859 (defcustom org-latex-to-mathml-jar-file nil
3860 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3861 Use this to specify additional executable file say a jar file.
3863 When using MathToWeb as the converter, specify the full-path to
3864 your mathtoweb.jar file."
3865 :group 'org-latex
3866 :version "24.1"
3867 :type '(choice
3868 (const :tag "None" nil)
3869 (file :tag "JAR file" :must-match t)))
3871 (defcustom org-latex-to-mathml-convert-command nil
3872 "Command to convert LaTeX fragments to MathML.
3873 Replace format-specifiers in the command as noted below and use
3874 `shell-command' to convert LaTeX to MathML.
3875 %j: Executable file in fully expanded form as specified by
3876 `org-latex-to-mathml-jar-file'.
3877 %I: Input LaTeX file in fully expanded form
3878 %o: Output MathML file
3879 This command is used by `org-create-math-formula'.
3881 When using MathToWeb as the converter, set this to
3882 \"java -jar %j -unicode -force -df %o %I\"."
3883 :group 'org-latex
3884 :version "24.1"
3885 :type '(choice
3886 (const :tag "None" nil)
3887 (string :tag "\nShell command")))
3889 (defcustom org-latex-create-formula-image-program 'dvipng
3890 "Program to convert LaTeX fragments with.
3892 dvipng Process the LaTeX fragments to dvi file, then convert
3893 dvi files to png files using dvipng.
3894 This will also include processing of non-math environments.
3895 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3896 to convert pdf files to png files"
3897 :group 'org-latex
3898 :version "24.1"
3899 :type '(choice
3900 (const :tag "dvipng" dvipng)
3901 (const :tag "imagemagick" imagemagick)))
3903 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3904 "Path to store latex preview images.
3905 A relative path here creates many directories relative to the
3906 processed org files paths. An absolute path puts all preview
3907 images at the same place."
3908 :group 'org-latex
3909 :version "24.3"
3910 :type 'string)
3912 (defun org-format-latex-mathml-available-p ()
3913 "Return t if `org-latex-to-mathml-convert-command' is usable."
3914 (save-match-data
3915 (when (and (boundp 'org-latex-to-mathml-convert-command)
3916 org-latex-to-mathml-convert-command)
3917 (let ((executable (car (split-string
3918 org-latex-to-mathml-convert-command))))
3919 (when (executable-find executable)
3920 (if (string-match
3921 "%j" org-latex-to-mathml-convert-command)
3922 (file-readable-p org-latex-to-mathml-jar-file)
3923 t))))))
3925 (defcustom org-format-latex-header "\\documentclass{article}
3926 \\usepackage[usenames]{color}
3927 \[PACKAGES]
3928 \[DEFAULT-PACKAGES]
3929 \\pagestyle{empty} % do not remove
3930 % The settings below are copied from fullpage.sty
3931 \\setlength{\\textwidth}{\\paperwidth}
3932 \\addtolength{\\textwidth}{-3cm}
3933 \\setlength{\\oddsidemargin}{1.5cm}
3934 \\addtolength{\\oddsidemargin}{-2.54cm}
3935 \\setlength{\\evensidemargin}{\\oddsidemargin}
3936 \\setlength{\\textheight}{\\paperheight}
3937 \\addtolength{\\textheight}{-\\headheight}
3938 \\addtolength{\\textheight}{-\\headsep}
3939 \\addtolength{\\textheight}{-\\footskip}
3940 \\addtolength{\\textheight}{-3cm}
3941 \\setlength{\\topmargin}{1.5cm}
3942 \\addtolength{\\topmargin}{-2.54cm}"
3943 "The document header used for processing LaTeX fragments.
3944 It is imperative that this header make sure that no page number
3945 appears on the page. The package defined in the variables
3946 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3947 will either replace the placeholder \"[PACKAGES]\" in this
3948 header, or they will be appended."
3949 :group 'org-latex
3950 :type 'string)
3952 (defun org-set-packages-alist (var val)
3953 "Set the packages alist and make sure it has 3 elements per entry."
3954 (set var (mapcar (lambda (x)
3955 (if (and (consp x) (= (length x) 2))
3956 (list (car x) (nth 1 x) t)
3958 val)))
3960 (defun org-get-packages-alist (var)
3961 "Get the packages alist and make sure it has 3 elements per entry."
3962 (mapcar (lambda (x)
3963 (if (and (consp x) (= (length x) 2))
3964 (list (car x) (nth 1 x) t)
3966 (default-value var)))
3968 (defcustom org-latex-default-packages-alist
3969 '(("AUTO" "inputenc" t)
3970 ("T1" "fontenc" t)
3971 ("" "fixltx2e" nil)
3972 ("" "graphicx" t)
3973 ("" "longtable" nil)
3974 ("" "float" nil)
3975 ("" "wrapfig" nil)
3976 ("" "rotating" nil)
3977 ("normalem" "ulem" t)
3978 ("" "amsmath" t)
3979 ("" "textcomp" t)
3980 ("" "marvosym" t)
3981 ("" "wasysym" t)
3982 ("" "amssymb" t)
3983 ("" "hyperref" nil)
3984 "\\tolerance=1000")
3985 "Alist of default packages to be inserted in the header.
3987 Change this only if one of the packages here causes an
3988 incompatibility with another package you are using.
3990 The packages in this list are needed by one part or another of
3991 Org mode to function properly:
3993 - inputenc, fontenc: for basic font and character selection
3994 - fixltx2e: Important patches of LaTeX itself
3995 - graphicx: for including images
3996 - longtable: For multipage tables
3997 - float, wrapfig: for figure placement
3998 - rotating: for sideways figures and tables
3999 - ulem: for underline and strike-through
4000 - amsmath: for subscript and superscript and math environments
4001 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4002 for interpreting the entities in `org-entities'. You can skip
4003 some of these packages if you don't use any of their symbols.
4004 - hyperref: for cross references
4006 Therefore you should not modify this variable unless you know
4007 what you are doing. The one reason to change it anyway is that
4008 you might be loading some other package that conflicts with one
4009 of the default packages. Each cell is of the format
4010 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
4011 the package also needs to be included when compiling LaTeX
4012 snippets into images for inclusion into non-LaTeX output."
4013 :group 'org-latex
4014 :group 'org-export-latex
4015 :set 'org-set-packages-alist
4016 :get 'org-get-packages-alist
4017 :version "24.1"
4018 :type '(repeat
4019 (choice
4020 (list :tag "options/package pair"
4021 (string :tag "options")
4022 (string :tag "package")
4023 (boolean :tag "Snippet"))
4024 (string :tag "A line of LaTeX"))))
4026 (defcustom org-latex-packages-alist nil
4027 "Alist of packages to be inserted in every LaTeX header.
4029 These will be inserted after `org-latex-default-packages-alist'.
4030 Each cell is of the format:
4032 \(\"options\" \"package\" snippet-flag)
4034 SNIPPET-FLAG, when t, indicates that this package is also needed
4035 when turning LaTeX snippets into images for inclusion into
4036 non-LaTeX output.
4038 Make sure that you only list packages here which:
4040 - you want in every file
4041 - do not conflict with the setup in `org-format-latex-header'.
4042 - do not conflict with the default packages in
4043 `org-latex-default-packages-alist'."
4044 :group 'org-latex
4045 :group 'org-export-latex
4046 :set 'org-set-packages-alist
4047 :get 'org-get-packages-alist
4048 :type '(repeat
4049 (choice
4050 (list :tag "options/package pair"
4051 (string :tag "options")
4052 (string :tag "package")
4053 (boolean :tag "Snippet"))
4054 (string :tag "A line of LaTeX"))))
4056 (defgroup org-appearance nil
4057 "Settings for Org-mode appearance."
4058 :tag "Org Appearance"
4059 :group 'org)
4061 (defcustom org-level-color-stars-only nil
4062 "Non-nil means fontify only the stars in each headline.
4063 When nil, the entire headline is fontified.
4064 Changing it requires restart of `font-lock-mode' to become effective
4065 also in regions already fontified."
4066 :group 'org-appearance
4067 :type 'boolean)
4069 (defcustom org-hide-leading-stars nil
4070 "Non-nil means hide the first N-1 stars in a headline.
4071 This works by using the face `org-hide' for these stars. This
4072 face is white for a light background, and black for a dark
4073 background. You may have to customize the face `org-hide' to
4074 make this work.
4075 Changing it requires restart of `font-lock-mode' to become effective
4076 also in regions already fontified.
4077 You may also set this on a per-file basis by adding one of the following
4078 lines to the buffer:
4080 #+STARTUP: hidestars
4081 #+STARTUP: showstars"
4082 :group 'org-appearance
4083 :type 'boolean)
4085 (defcustom org-hidden-keywords nil
4086 "List of symbols corresponding to keywords to be hidden the org buffer.
4087 For example, a value '(title) for this list will make the document's title
4088 appear in the buffer without the initial #+TITLE: keyword."
4089 :group 'org-appearance
4090 :version "24.1"
4091 :type '(set (const :tag "#+AUTHOR" author)
4092 (const :tag "#+DATE" date)
4093 (const :tag "#+EMAIL" email)
4094 (const :tag "#+TITLE" title)))
4096 (defcustom org-custom-properties nil
4097 "List of properties (as strings) with a special meaning.
4098 The default use of these custom properties is to let the user
4099 hide them with `org-toggle-custom-properties-visibility'."
4100 :group 'org-properties
4101 :group 'org-appearance
4102 :version "24.3"
4103 :type '(repeat (string :tag "Property Name")))
4105 (defcustom org-fontify-done-headline nil
4106 "Non-nil means change the face of a headline if it is marked DONE.
4107 Normally, only the TODO/DONE keyword indicates the state of a headline.
4108 When this is non-nil, the headline after the keyword is set to the
4109 `org-headline-done' as an additional indication."
4110 :group 'org-appearance
4111 :type 'boolean)
4113 (defcustom org-fontify-emphasized-text t
4114 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4115 Changing this variable requires a restart of Emacs to take effect."
4116 :group 'org-appearance
4117 :type 'boolean)
4119 (defcustom org-fontify-whole-heading-line nil
4120 "Non-nil means fontify the whole line for headings.
4121 This is useful when setting a background color for the
4122 org-level-* faces."
4123 :group 'org-appearance
4124 :type 'boolean)
4126 (defcustom org-highlight-latex-and-related nil
4127 "Non-nil means highlight LaTeX related syntax in the buffer.
4128 When non nil, the value should be a list containing any of the
4129 following symbols:
4130 `latex' Highlight LaTeX snippets and environments.
4131 `script' Highlight subscript and superscript.
4132 `entities' Highlight entities."
4133 :group 'org-appearance
4134 :version "24.4"
4135 :package-version '(Org . "8.0")
4136 :type '(choice
4137 (const :tag "No highlighting" nil)
4138 (set :greedy t :tag "Highlight"
4139 (const :tag "LaTeX snippets and environments" latex)
4140 (const :tag "Subscript and superscript" script)
4141 (const :tag "Entities" entities))))
4143 (defcustom org-hide-emphasis-markers nil
4144 "Non-nil mean font-lock should hide the emphasis marker characters."
4145 :group 'org-appearance
4146 :type 'boolean)
4148 (defcustom org-hide-macro-markers nil
4149 "Non-nil mean font-lock should hide the brackets marking macro calls."
4150 :group 'org-appearance
4151 :type 'boolean)
4153 (defcustom org-pretty-entities nil
4154 "Non-nil means show entities as UTF8 characters.
4155 When nil, the \\name form remains in the buffer."
4156 :group 'org-appearance
4157 :version "24.1"
4158 :type 'boolean)
4160 (defcustom org-pretty-entities-include-sub-superscripts t
4161 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4162 :group 'org-appearance
4163 :version "24.1"
4164 :type 'boolean)
4166 (defvar org-emph-re nil
4167 "Regular expression for matching emphasis.
4168 After a match, the match groups contain these elements:
4169 0 The match of the full regular expression, including the characters
4170 before and after the proper match
4171 1 The character before the proper match, or empty at beginning of line
4172 2 The proper match, including the leading and trailing markers
4173 3 The leading marker like * or /, indicating the type of highlighting
4174 4 The text between the emphasis markers, not including the markers
4175 5 The character after the match, empty at the end of a line")
4176 (defvar org-verbatim-re nil
4177 "Regular expression for matching verbatim text.")
4178 (defvar org-emphasis-regexp-components) ; defined just below
4179 (defvar org-emphasis-alist) ; defined just below
4180 (defun org-set-emph-re (var val)
4181 "Set variable and compute the emphasis regular expression."
4182 (set var val)
4183 (when (and (boundp 'org-emphasis-alist)
4184 (boundp 'org-emphasis-regexp-components)
4185 org-emphasis-alist org-emphasis-regexp-components)
4186 (let* ((e org-emphasis-regexp-components)
4187 (pre (car e))
4188 (post (nth 1 e))
4189 (border (nth 2 e))
4190 (body (nth 3 e))
4191 (nl (nth 4 e))
4192 (body1 (concat body "*?"))
4193 (markers (mapconcat 'car org-emphasis-alist ""))
4194 (vmarkers (mapconcat
4195 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4196 org-emphasis-alist "")))
4197 ;; make sure special characters appear at the right position in the class
4198 (if (string-match "\\^" markers)
4199 (setq markers (concat (replace-match "" t t markers) "^")))
4200 (if (string-match "-" markers)
4201 (setq markers (concat (replace-match "" t t markers) "-")))
4202 (if (string-match "\\^" vmarkers)
4203 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4204 (if (string-match "-" vmarkers)
4205 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4206 (if (> nl 0)
4207 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4208 (int-to-string nl) "\\}")))
4209 ;; Make the regexp
4210 (setq org-emph-re
4211 (concat "\\([" pre "]\\|^\\)"
4212 "\\("
4213 "\\([" markers "]\\)"
4214 "\\("
4215 "[^" border "]\\|"
4216 "[^" border "]"
4217 body1
4218 "[^" border "]"
4219 "\\)"
4220 "\\3\\)"
4221 "\\([" post "]\\|$\\)"))
4222 (setq org-verbatim-re
4223 (concat "\\([" pre "]\\|^\\)"
4224 "\\("
4225 "\\([" vmarkers "]\\)"
4226 "\\("
4227 "[^" border "]\\|"
4228 "[^" border "]"
4229 body1
4230 "[^" border "]"
4231 "\\)"
4232 "\\3\\)"
4233 "\\([" post "]\\|$\\)")))))
4235 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4236 ;; set this option proved cumbersome. See this message/thread:
4237 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4238 (defvar org-emphasis-regexp-components
4239 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4240 "Components used to build the regular expression for emphasis.
4241 This is a list with five entries. Terminology: In an emphasis string
4242 like \" *strong word* \", we call the initial space PREMATCH, the final
4243 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4244 and \"trong wor\" is the body. The different components in this variable
4245 specify what is allowed/forbidden in each part:
4247 pre Chars allowed as prematch. Beginning of line will be allowed too.
4248 post Chars allowed as postmatch. End of line will be allowed too.
4249 border The chars *forbidden* as border characters.
4250 body-regexp A regexp like \".\" to match a body character. Don't use
4251 non-shy groups here, and don't allow newline here.
4252 newline The maximum number of newlines allowed in an emphasis exp.
4254 You need to reload Org or to restart Emacs after customizing this.")
4256 (defcustom org-emphasis-alist
4257 `(("*" bold)
4258 ("/" italic)
4259 ("_" underline)
4260 ("=" org-code verbatim)
4261 ("~" org-verbatim verbatim)
4262 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4263 "Alist of characters and faces to emphasize text.
4264 Text starting and ending with a special character will be emphasized,
4265 for example *bold*, _underlined_ and /italic/. This variable sets the
4266 marker characters and the face to be used by font-lock for highlighting
4267 in Org-mode Emacs buffers.
4269 You need to reload Org or to restart Emacs after customizing this."
4270 :group 'org-appearance
4271 :set 'org-set-emph-re
4272 :version "24.4"
4273 :package-version '(Org . "8.0")
4274 :type '(repeat
4275 (list
4276 (string :tag "Marker character")
4277 (choice
4278 (face :tag "Font-lock-face")
4279 (plist :tag "Face property list"))
4280 (option (const verbatim)))))
4282 (defvar org-protecting-blocks
4283 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4284 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4285 This is needed for font-lock setup.")
4287 ;;; Miscellaneous options
4289 (defgroup org-completion nil
4290 "Completion in Org-mode."
4291 :tag "Org Completion"
4292 :group 'org)
4294 (defcustom org-completion-use-ido nil
4295 "Non-nil means use ido completion wherever possible.
4296 Note that `ido-mode' must be active for this variable to be relevant.
4297 If you decide to turn this variable on, you might well want to turn off
4298 `org-outline-path-complete-in-steps'.
4299 See also `org-completion-use-iswitchb'."
4300 :group 'org-completion
4301 :type 'boolean)
4303 (defcustom org-completion-use-iswitchb nil
4304 "Non-nil means use iswitchb completion wherever possible.
4305 Note that `iswitchb-mode' must be active for this variable to be relevant.
4306 If you decide to turn this variable on, you might well want to turn off
4307 `org-outline-path-complete-in-steps'.
4308 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4309 :group 'org-completion
4310 :type 'boolean)
4312 (defcustom org-completion-fallback-command 'hippie-expand
4313 "The expansion command called by \\[pcomplete] in normal context.
4314 Normal means, no org-mode-specific context."
4315 :group 'org-completion
4316 :type 'function)
4318 ;;; Functions and variables from their packages
4319 ;; Declared here to avoid compiler warnings
4321 ;; XEmacs only
4322 (defvar outline-mode-menu-heading)
4323 (defvar outline-mode-menu-show)
4324 (defvar outline-mode-menu-hide)
4325 (defvar zmacs-regions) ; XEmacs regions
4327 ;; Emacs only
4328 (defvar mark-active)
4330 ;; Various packages
4331 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4332 (declare-function calendar-forward-day "cal-move" (arg))
4333 (declare-function calendar-goto-date "cal-move" (date))
4334 (declare-function calendar-goto-today "cal-move" ())
4335 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4336 (defvar calc-embedded-close-formula)
4337 (defvar calc-embedded-open-formula)
4338 (declare-function cdlatex-tab "ext:cdlatex" ())
4339 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4340 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4341 (defvar font-lock-unfontify-region-function)
4342 (declare-function iswitchb-read-buffer "iswitchb"
4343 (prompt &optional default require-match start matches-set))
4344 (defvar iswitchb-temp-buflist)
4345 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4346 (defvar org-agenda-tags-todo-honor-ignore-options)
4347 (declare-function org-agenda-skip "org-agenda" ())
4348 (declare-function
4349 org-agenda-format-item "org-agenda"
4350 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4351 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4352 (declare-function org-agenda-change-all-lines "org-agenda"
4353 (newhead hdmarker &optional fixface just-this))
4354 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4355 (declare-function org-agenda-maybe-redo "org-agenda" ())
4356 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4357 (beg end))
4358 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4359 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4360 "org-agenda" (&optional end))
4361 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4362 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4363 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4364 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4365 (declare-function org-indent-mode "org-indent" (&optional arg))
4366 (declare-function parse-time-string "parse-time" (string))
4367 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4368 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4369 (defvar remember-data-file)
4370 (defvar texmathp-why)
4371 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4372 (declare-function table--at-cell-p "table" (position &optional object at-column))
4374 ;;;###autoload
4375 (defun turn-on-orgtbl ()
4376 "Unconditionally turn on `orgtbl-mode'."
4377 (require 'org-table)
4378 (orgtbl-mode 1))
4380 (defun org-at-table-p (&optional table-type)
4381 "Return t if the cursor is inside an org-type table.
4382 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4383 (if org-enable-table-editor
4384 (save-excursion
4385 (beginning-of-line 1)
4386 (looking-at (if table-type org-table-any-line-regexp
4387 org-table-line-regexp)))
4388 nil))
4389 (defsubst org-table-p () (org-at-table-p))
4391 (defun org-at-table.el-p ()
4392 "Return t if and only if we are at a table.el table."
4393 (and (org-at-table-p 'any)
4394 (save-excursion
4395 (goto-char (org-table-begin 'any))
4396 (looking-at org-table1-hline-regexp))))
4398 (defun org-table-recognize-table.el ()
4399 "If there is a table.el table nearby, recognize it and move into it."
4400 (if org-table-tab-recognizes-table.el
4401 (if (org-at-table.el-p)
4402 (progn
4403 (beginning-of-line 1)
4404 (if (looking-at org-table-dataline-regexp)
4406 (if (looking-at org-table1-hline-regexp)
4407 (progn
4408 (beginning-of-line 2)
4409 (if (looking-at org-table-any-border-regexp)
4410 (beginning-of-line -1)))))
4411 (if (re-search-forward "|" (org-table-end t) t)
4412 (progn
4413 (require 'table)
4414 (if (table--at-cell-p (point))
4416 (message "recognizing table.el table...")
4417 (table-recognize-table)
4418 (message "recognizing table.el table...done")))
4419 (error "This should not happen"))
4421 nil)
4422 nil))
4424 (defun org-at-table-hline-p ()
4425 "Return t if the cursor is inside a hline in a table."
4426 (if org-enable-table-editor
4427 (save-excursion
4428 (beginning-of-line 1)
4429 (looking-at org-table-hline-regexp))
4430 nil))
4432 (defun org-table-map-tables (function &optional quietly)
4433 "Apply FUNCTION to the start of all tables in the buffer."
4434 (save-excursion
4435 (save-restriction
4436 (widen)
4437 (goto-char (point-min))
4438 (while (re-search-forward org-table-any-line-regexp nil t)
4439 (unless quietly
4440 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4441 (beginning-of-line 1)
4442 (when (and (looking-at org-table-line-regexp)
4443 ;; Exclude tables in src/example/verbatim/clocktable blocks
4444 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4445 (save-excursion (funcall function))
4446 (or (looking-at org-table-line-regexp)
4447 (forward-char 1)))
4448 (re-search-forward org-table-any-border-regexp nil 1))))
4449 (unless quietly (message "Mapping tables: done")))
4451 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4452 (declare-function org-clock-update-mode-line "org-clock" ())
4453 (declare-function org-resolve-clocks "org-clock"
4454 (&optional also-non-dangling-p prompt last-valid))
4456 (defun org-at-TBLFM-p (&optional pos)
4457 "Return t when point (or POS) is in #+TBLFM line."
4458 (save-excursion
4459 (let ((pos pos)))
4460 (goto-char (or pos (point)))
4461 (beginning-of-line 1)
4462 (looking-at org-TBLFM-regexp)))
4464 (defvar org-clock-start-time)
4465 (defvar org-clock-marker (make-marker)
4466 "Marker recording the last clock-in.")
4467 (defvar org-clock-hd-marker (make-marker)
4468 "Marker recording the last clock-in, but the headline position.")
4469 (defvar org-clock-heading ""
4470 "The heading of the current clock entry.")
4471 (defun org-clock-is-active ()
4472 "Return the buffer where the clock is currently running.
4473 Return nil if no clock is running."
4474 (marker-buffer org-clock-marker))
4476 (defun org-check-running-clock ()
4477 "Check if the current buffer contains the running clock.
4478 If yes, offer to stop it and to save the buffer with the changes."
4479 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4480 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4481 (buffer-name))))
4482 (org-clock-out)
4483 (when (y-or-n-p "Save changed buffer?")
4484 (save-buffer))))
4486 (defun org-clocktable-try-shift (dir n)
4487 "Check if this line starts a clock table, if yes, shift the time block."
4488 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4489 (org-clocktable-shift dir n)))
4491 ;;;###autoload
4492 (defun org-clock-persistence-insinuate ()
4493 "Set up hooks for clock persistence."
4494 (require 'org-clock)
4495 (add-hook 'org-mode-hook 'org-clock-load)
4496 (add-hook 'kill-emacs-hook 'org-clock-save))
4498 (defgroup org-archive nil
4499 "Options concerning archiving in Org-mode."
4500 :tag "Org Archive"
4501 :group 'org-structure)
4503 (defcustom org-archive-location "%s_archive::"
4504 "The location where subtrees should be archived.
4506 The value of this variable is a string, consisting of two parts,
4507 separated by a double-colon. The first part is a filename and
4508 the second part is a headline.
4510 When the filename is omitted, archiving happens in the same file.
4511 %s in the filename will be replaced by the current file
4512 name (without the directory part). Archiving to a different file
4513 is useful to keep archived entries from contributing to the
4514 Org-mode Agenda.
4516 The archived entries will be filed as subtrees of the specified
4517 headline. When the headline is omitted, the subtrees are simply
4518 filed away at the end of the file, as top-level entries. Also in
4519 the heading you can use %s to represent the file name, this can be
4520 useful when using the same archive for a number of different files.
4522 Here are a few examples:
4523 \"%s_archive::\"
4524 If the current file is Projects.org, archive in file
4525 Projects.org_archive, as top-level trees. This is the default.
4527 \"::* Archived Tasks\"
4528 Archive in the current file, under the top-level headline
4529 \"* Archived Tasks\".
4531 \"~/org/archive.org::\"
4532 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4534 \"~/org/archive.org::* From %s\"
4535 Archive in file ~/org/archive.org (absolute path), under headlines
4536 \"From FILENAME\" where file name is the current file name.
4538 \"~/org/datetree.org::datetree/* Finished Tasks\"
4539 The \"datetree/\" string is special, signifying to archive
4540 items to the datetree. Items are placed in either the CLOSED
4541 date of the item, or the current date if there is no CLOSED date.
4542 The heading will be a subentry to the current date. There doesn't
4543 need to be a heading, but there always needs to be a slash after
4544 datetree. For example, to store archived items directly in the
4545 datetree, use \"~/org/datetree.org::datetree/\".
4547 \"basement::** Finished Tasks\"
4548 Archive in file ./basement (relative path), as level 3 trees
4549 below the level 2 heading \"** Finished Tasks\".
4551 You may set this option on a per-file basis by adding to the buffer a
4552 line like
4554 #+ARCHIVE: basement::** Finished Tasks
4556 You may also define it locally for a subtree by setting an ARCHIVE property
4557 in the entry. If such a property is found in an entry, or anywhere up
4558 the hierarchy, it will be used."
4559 :group 'org-archive
4560 :type 'string)
4562 (defcustom org-agenda-skip-archived-trees t
4563 "Non-nil means the agenda will skip any items located in archived trees.
4564 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4565 variable is no longer recommended, you should leave it at the value t.
4566 Instead, use the key `v' to cycle the archives-mode in the agenda."
4567 :group 'org-archive
4568 :group 'org-agenda-skip
4569 :type 'boolean)
4571 (defcustom org-columns-skip-archived-trees t
4572 "Non-nil means ignore archived trees when creating column view."
4573 :group 'org-archive
4574 :group 'org-properties
4575 :type 'boolean)
4577 (defcustom org-cycle-open-archived-trees nil
4578 "Non-nil means `org-cycle' will open archived trees.
4579 An archived tree is a tree marked with the tag ARCHIVE.
4580 When nil, archived trees will stay folded. You can still open them with
4581 normal outline commands like `show-all', but not with the cycling commands."
4582 :group 'org-archive
4583 :group 'org-cycle
4584 :type 'boolean)
4586 (defcustom org-sparse-tree-open-archived-trees nil
4587 "Non-nil means sparse tree construction shows matches in archived trees.
4588 When nil, matches in these trees are highlighted, but the trees are kept in
4589 collapsed state."
4590 :group 'org-archive
4591 :group 'org-sparse-trees
4592 :type 'boolean)
4594 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4595 "The default date type when building a sparse tree.
4596 When this is nil, a date is a scheduled or a deadline timestamp.
4597 Otherwise, these types are allowed:
4599 all: all timestamps
4600 active: only active timestamps (<...>)
4601 inactive: only inactive timestamps (<...)
4602 scheduled: only scheduled timestamps
4603 deadline: only deadline timestamps"
4604 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4605 (const :tag "All timestamps" all)
4606 (const :tag "Only active timestamps" active)
4607 (const :tag "Only inactive timestamps" inactive)
4608 (const :tag "Only scheduled timestamps" scheduled)
4609 (const :tag "Only deadline timestamps" deadline)
4610 (const :tag "Only closed timestamps" closed))
4611 :version "24.3"
4612 :group 'org-sparse-trees)
4614 (defun org-cycle-hide-archived-subtrees (state)
4615 "Re-hide all archived subtrees after a visibility state change."
4616 (when (and (not org-cycle-open-archived-trees)
4617 (not (memq state '(overview folded))))
4618 (save-excursion
4619 (let* ((globalp (memq state '(contents all)))
4620 (beg (if globalp (point-min) (point)))
4621 (end (if globalp (point-max) (org-end-of-subtree t))))
4622 (org-hide-archived-subtrees beg end)
4623 (goto-char beg)
4624 (if (looking-at (concat ".*:" org-archive-tag ":"))
4625 (message "%s" (substitute-command-keys
4626 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4628 (defun org-force-cycle-archived ()
4629 "Cycle subtree even if it is archived."
4630 (interactive)
4631 (setq this-command 'org-cycle)
4632 (let ((org-cycle-open-archived-trees t))
4633 (call-interactively 'org-cycle)))
4635 (defun org-hide-archived-subtrees (beg end)
4636 "Re-hide all archived subtrees after a visibility state change."
4637 (save-excursion
4638 (let* ((re (concat ":" org-archive-tag ":")))
4639 (goto-char beg)
4640 (while (re-search-forward re end t)
4641 (when (org-at-heading-p)
4642 (org-flag-subtree t)
4643 (org-end-of-subtree t))))))
4645 (declare-function outline-end-of-heading "outline" ())
4646 (declare-function outline-flag-region "outline" (from to flag))
4647 (defun org-flag-subtree (flag)
4648 (save-excursion
4649 (org-back-to-heading t)
4650 (outline-end-of-heading)
4651 (outline-flag-region (point)
4652 (progn (org-end-of-subtree t) (point))
4653 flag)))
4655 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4657 ;; Declare Column View Code
4659 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4660 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4661 (declare-function org-columns-compute "org-colview" (property))
4663 ;; Declare ID code
4665 (declare-function org-id-store-link "org-id")
4666 (declare-function org-id-locations-load "org-id")
4667 (declare-function org-id-locations-save "org-id")
4668 (defvar org-id-track-globally)
4670 ;;; Variables for pre-computed regular expressions, all buffer local
4672 (defvar org-todo-regexp nil
4673 "Matches any of the TODO state keywords.")
4674 (make-variable-buffer-local 'org-todo-regexp)
4675 (defvar org-not-done-regexp nil
4676 "Matches any of the TODO state keywords except the last one.")
4677 (make-variable-buffer-local 'org-not-done-regexp)
4678 (defvar org-not-done-heading-regexp nil
4679 "Matches a TODO headline that is not done.")
4680 (make-variable-buffer-local 'org-not-done-regexp)
4681 (defvar org-todo-line-regexp nil
4682 "Matches a headline and puts TODO state into group 2 if present.")
4683 (make-variable-buffer-local 'org-todo-line-regexp)
4684 (defvar org-complex-heading-regexp nil
4685 "Matches a headline and puts everything into groups:
4686 group 1: the stars
4687 group 2: The todo keyword, maybe
4688 group 3: Priority cookie
4689 group 4: True headline
4690 group 5: Tags")
4691 (make-variable-buffer-local 'org-complex-heading-regexp)
4692 (defvar org-complex-heading-regexp-format nil
4693 "Printf format to make regexp to match an exact headline.
4694 This regexp will match the headline of any node which has the
4695 exact headline text that is put into the format, but may have any
4696 TODO state, priority and tags.")
4697 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4698 (defvar org-todo-line-tags-regexp nil
4699 "Matches a headline and puts TODO state into group 2 if present.
4700 Also put tags into group 4 if tags are present.")
4701 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4702 (defvar org-ds-keyword-length 12
4703 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4704 (make-variable-buffer-local 'org-ds-keyword-length)
4705 (defvar org-deadline-regexp nil
4706 "Matches the DEADLINE keyword.")
4707 (make-variable-buffer-local 'org-deadline-regexp)
4708 (defvar org-deadline-time-regexp nil
4709 "Matches the DEADLINE keyword together with a time stamp.")
4710 (make-variable-buffer-local 'org-deadline-time-regexp)
4711 (defvar org-deadline-time-hour-regexp nil
4712 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4713 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4714 (defvar org-deadline-line-regexp nil
4715 "Matches the DEADLINE keyword and the rest of the line.")
4716 (make-variable-buffer-local 'org-deadline-line-regexp)
4717 (defvar org-scheduled-regexp nil
4718 "Matches the SCHEDULED keyword.")
4719 (make-variable-buffer-local 'org-scheduled-regexp)
4720 (defvar org-scheduled-time-regexp nil
4721 "Matches the SCHEDULED keyword together with a time stamp.")
4722 (make-variable-buffer-local 'org-scheduled-time-regexp)
4723 (defvar org-scheduled-time-hour-regexp nil
4724 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4725 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4726 (defvar org-closed-time-regexp nil
4727 "Matches the CLOSED keyword together with a time stamp.")
4728 (make-variable-buffer-local 'org-closed-time-regexp)
4730 (defvar org-keyword-time-regexp nil
4731 "Matches any of the 4 keywords, together with the time stamp.")
4732 (make-variable-buffer-local 'org-keyword-time-regexp)
4733 (defvar org-keyword-time-not-clock-regexp nil
4734 "Matches any of the 3 keywords, together with the time stamp.")
4735 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4736 (defvar org-maybe-keyword-time-regexp nil
4737 "Matches a timestamp, possibly preceded by a keyword.")
4738 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4739 (defvar org-all-time-keywords nil
4740 "List of time keywords.")
4741 (make-variable-buffer-local 'org-all-time-keywords)
4743 (defconst org-plain-time-of-day-regexp
4744 (concat
4745 "\\(\\<[012]?[0-9]"
4746 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4747 "\\(--?"
4748 "\\(\\<[012]?[0-9]"
4749 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4750 "\\)?")
4751 "Regular expression to match a plain time or time range.
4752 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4753 groups carry important information:
4754 0 the full match
4755 1 the first time, range or not
4756 8 the second time, if it is a range.")
4758 (defconst org-plain-time-extension-regexp
4759 (concat
4760 "\\(\\<[012]?[0-9]"
4761 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4762 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4763 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4764 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4765 groups carry important information:
4766 0 the full match
4767 7 hours of duration
4768 9 minutes of duration")
4770 (defconst org-stamp-time-of-day-regexp
4771 (concat
4772 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4773 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4774 "\\(--?"
4775 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4776 "Regular expression to match a timestamp time or time range.
4777 After a match, the following groups carry important information:
4778 0 the full match
4779 1 date plus weekday, for back referencing to make sure both times are on the same day
4780 2 the first time, range or not
4781 4 the second time, if it is a range.")
4783 (defconst org-startup-options
4784 '(("fold" org-startup-folded t)
4785 ("overview" org-startup-folded t)
4786 ("nofold" org-startup-folded nil)
4787 ("showall" org-startup-folded nil)
4788 ("showeverything" org-startup-folded showeverything)
4789 ("content" org-startup-folded content)
4790 ("indent" org-startup-indented t)
4791 ("noindent" org-startup-indented nil)
4792 ("hidestars" org-hide-leading-stars t)
4793 ("showstars" org-hide-leading-stars nil)
4794 ("odd" org-odd-levels-only t)
4795 ("oddeven" org-odd-levels-only nil)
4796 ("align" org-startup-align-all-tables t)
4797 ("noalign" org-startup-align-all-tables nil)
4798 ("inlineimages" org-startup-with-inline-images t)
4799 ("noinlineimages" org-startup-with-inline-images nil)
4800 ("latexpreview" org-startup-with-latex-preview t)
4801 ("nolatexpreview" org-startup-with-latex-preview nil)
4802 ("customtime" org-display-custom-times t)
4803 ("logdone" org-log-done time)
4804 ("lognotedone" org-log-done note)
4805 ("nologdone" org-log-done nil)
4806 ("lognoteclock-out" org-log-note-clock-out t)
4807 ("nolognoteclock-out" org-log-note-clock-out nil)
4808 ("logrepeat" org-log-repeat state)
4809 ("lognoterepeat" org-log-repeat note)
4810 ("logdrawer" org-log-into-drawer t)
4811 ("nologdrawer" org-log-into-drawer nil)
4812 ("logstatesreversed" org-log-states-order-reversed t)
4813 ("nologstatesreversed" org-log-states-order-reversed nil)
4814 ("nologrepeat" org-log-repeat nil)
4815 ("logreschedule" org-log-reschedule time)
4816 ("lognotereschedule" org-log-reschedule note)
4817 ("nologreschedule" org-log-reschedule nil)
4818 ("logredeadline" org-log-redeadline time)
4819 ("lognoteredeadline" org-log-redeadline note)
4820 ("nologredeadline" org-log-redeadline nil)
4821 ("logrefile" org-log-refile time)
4822 ("lognoterefile" org-log-refile note)
4823 ("nologrefile" org-log-refile nil)
4824 ("fninline" org-footnote-define-inline t)
4825 ("nofninline" org-footnote-define-inline nil)
4826 ("fnlocal" org-footnote-section nil)
4827 ("fnauto" org-footnote-auto-label t)
4828 ("fnprompt" org-footnote-auto-label nil)
4829 ("fnconfirm" org-footnote-auto-label confirm)
4830 ("fnplain" org-footnote-auto-label plain)
4831 ("fnadjust" org-footnote-auto-adjust t)
4832 ("nofnadjust" org-footnote-auto-adjust nil)
4833 ("constcgs" constants-unit-system cgs)
4834 ("constSI" constants-unit-system SI)
4835 ("noptag" org-tag-persistent-alist nil)
4836 ("hideblocks" org-hide-block-startup t)
4837 ("nohideblocks" org-hide-block-startup nil)
4838 ("beamer" org-startup-with-beamer-mode t)
4839 ("entitiespretty" org-pretty-entities t)
4840 ("entitiesplain" org-pretty-entities nil))
4841 "Variable associated with STARTUP options for org-mode.
4842 Each element is a list of three items: the startup options (as written
4843 in the #+STARTUP line), the corresponding variable, and the value to set
4844 this variable to if the option is found. An optional forth element PUSH
4845 means to push this value onto the list in the variable.")
4847 (defun org-update-property-plist (key val props)
4848 "Update PROPS with KEY and VAL."
4849 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4850 (key (if appending (substring key 0 (- (length key) 1)) key))
4851 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4852 (previous (cdr (assoc key props))))
4853 (if appending
4854 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4855 (cons (cons key val) remainder))))
4857 (defcustom org-group-tags t
4858 "When non-nil (the default), use group tags.
4859 This can be turned on/off through `org-toggle-tags-groups'."
4860 :group 'org-tags
4861 :group 'org-startup
4862 :type 'boolean)
4864 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4866 (defun org-toggle-tags-groups ()
4867 "Toggle support for group tags.
4868 Support for group tags is controlled by the option
4869 `org-group-tags', which is non-nil by default."
4870 (interactive)
4871 (setq org-group-tags (not org-group-tags))
4872 (cond ((and (derived-mode-p 'org-agenda-mode)
4873 org-group-tags)
4874 (org-agenda-redo))
4875 ((derived-mode-p 'org-mode)
4876 (let ((org-inhibit-startup t)) (org-mode))))
4877 (message "Groups tags support has been turned %s"
4878 (if org-group-tags "on" "off")))
4880 (defun org-set-regexps-and-options-for-tags ()
4881 "Precompute variables used for tags."
4882 (when (derived-mode-p 'org-mode)
4883 (org-set-local 'org-file-tags nil)
4884 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4885 (splitre "[ \t]+")
4886 (start 0)
4887 tags ftags key value)
4888 (save-excursion
4889 (save-restriction
4890 (widen)
4891 (goto-char (point-min))
4892 (while (re-search-forward re nil t)
4893 (setq key (upcase (org-match-string-no-properties 1))
4894 value (org-match-string-no-properties 2))
4895 (if (stringp value) (setq value (org-trim value)))
4896 (cond
4897 ((equal key "TAGS")
4898 (setq tags (append tags (if tags '("\\n") nil)
4899 (org-split-string value splitre))))
4900 ((equal key "FILETAGS")
4901 (when (string-match "\\S-" value)
4902 (setq ftags
4903 (append
4904 ftags
4905 (apply 'append
4906 (mapcar (lambda (x) (org-split-string x ":"))
4907 (org-split-string value)))))))))))
4908 ;; Process the file tags.
4909 (and ftags (org-set-local 'org-file-tags
4910 (mapcar 'org-add-prop-inherited ftags)))
4911 (org-set-local 'org-tag-groups-alist nil)
4912 ;; Process the tags.
4913 (when (and (not tags) org-tag-alist)
4914 (setq tags
4915 (mapcar
4916 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4917 ((eq (car tg) :endgroup) "}")
4918 ((eq (car tg) :grouptags) ":")
4919 ((eq (car tg) :newline) "\n")
4920 (t (concat (car tg)
4921 (if (characterp (cdr tg))
4922 (format "(%s)" (char-to-string (cdr tg))) "")))))
4923 org-tag-alist)))
4924 (let (e tgs g)
4925 (while (setq e (pop tags))
4926 (cond
4927 ((equal e "{")
4928 (progn (push '(:startgroup) tgs)
4929 (when (equal (nth 1 tags) ":")
4930 (push (list (replace-regexp-in-string
4931 "(.+)$" "" (nth 0 tags)))
4932 org-tag-groups-alist)
4933 (setq g 0))))
4934 ((equal e ":") (push '(:grouptags) tgs))
4935 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4936 ((equal e "\\n") (push '(:newline) tgs))
4937 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4938 (push (cons (match-string 1 e)
4939 (string-to-char (match-string 2 e))) tgs)
4940 (if (and g (> g 0))
4941 (setcar org-tag-groups-alist
4942 (append (car org-tag-groups-alist)
4943 (list (match-string 1 e)))))
4944 (if g (setq g (1+ g))))
4945 (t (push (list e) tgs)
4946 (if (and g (> g 0))
4947 (setcar org-tag-groups-alist
4948 (append (car org-tag-groups-alist) (list e))))
4949 (if g (setq g (1+ g))))))
4950 (org-set-local 'org-tag-alist nil)
4951 (while (setq e (pop tgs))
4952 (or (and (stringp (car e))
4953 (assoc (car e) org-tag-alist))
4954 (push e org-tag-alist)))
4955 ;; Return a list with tag variables
4956 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4958 (defvar org-ota nil)
4959 (defun org-set-regexps-and-options ()
4960 "Precompute regular expressions used in the current buffer."
4961 (when (derived-mode-p 'org-mode)
4962 (org-set-local 'org-todo-kwd-alist nil)
4963 (org-set-local 'org-todo-key-alist nil)
4964 (org-set-local 'org-todo-key-trigger nil)
4965 (org-set-local 'org-todo-keywords-1 nil)
4966 (org-set-local 'org-done-keywords nil)
4967 (org-set-local 'org-todo-heads nil)
4968 (org-set-local 'org-todo-sets nil)
4969 (org-set-local 'org-todo-log-states nil)
4970 (org-set-local 'org-file-properties nil)
4971 (let ((re (org-make-options-regexp
4972 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4973 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4974 "SETUPFILE" "OPTIONS")
4975 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4976 (splitre "[ \t]+")
4977 (scripts org-use-sub-superscripts)
4978 kwds kws0 kwsa key log value cat arch const links hw dws
4979 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4980 (start 0))
4981 (save-excursion
4982 (save-restriction
4983 (widen)
4984 (goto-char (point-min))
4985 (while
4986 (or (and
4987 ext-setup-or-nil
4988 (not org-ota)
4989 (let (ret)
4990 (with-temp-buffer
4991 (insert ext-setup-or-nil)
4992 (let ((major-mode 'org-mode) org-ota)
4993 (setq ret (save-match-data
4994 (org-set-regexps-and-options-for-tags)))))
4995 ;; Append setupfile tags to existing tags
4996 (setq org-ota t)
4997 (setq org-file-tags
4998 (delq nil (append org-file-tags (nth 0 ret)))
4999 org-tag-alist
5000 (delq nil (append org-tag-alist (nth 1 ret)))
5001 org-tag-groups-alist
5002 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
5003 (and ext-setup-or-nil
5004 (string-match re ext-setup-or-nil start)
5005 (setq start (match-end 0)))
5006 (and (setq ext-setup-or-nil nil start 0)
5007 (re-search-forward re nil t)))
5008 (setq key (upcase (match-string 1 ext-setup-or-nil))
5009 value (org-match-string-no-properties 2 ext-setup-or-nil))
5010 (if (stringp value) (setq value (org-trim value)))
5011 (cond
5012 ((equal key "CATEGORY")
5013 (setq cat value))
5014 ((member key '("SEQ_TODO" "TODO"))
5015 (push (cons 'sequence (org-split-string value splitre)) kwds))
5016 ((equal key "TYP_TODO")
5017 (push (cons 'type (org-split-string value splitre)) kwds))
5018 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
5019 ;; general TODO-like setup
5020 (push (cons (intern (downcase (match-string 1 key)))
5021 (org-split-string value splitre)) kwds))
5022 ((equal key "COLUMNS")
5023 (org-set-local 'org-columns-default-format value))
5024 ((equal key "LINK")
5025 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5026 (push (cons (match-string 1 value)
5027 (org-trim (match-string 2 value)))
5028 links)))
5029 ((equal key "PRIORITIES")
5030 (setq prio (org-split-string value " +")))
5031 ((equal key "PROPERTY")
5032 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5033 (setq props (org-update-property-plist (match-string 1 value)
5034 (match-string 2 value)
5035 props))))
5036 ((equal key "CONSTANTS")
5037 (org-table-set-constants))
5038 ((equal key "STARTUP")
5039 (let ((opts (org-split-string value splitre))
5040 l var val)
5041 (while (setq l (pop opts))
5042 (when (setq l (assoc l org-startup-options))
5043 (setq var (nth 1 l) val (nth 2 l))
5044 (if (not (nth 3 l))
5045 (set (make-local-variable var) val)
5046 (if (not (listp (symbol-value var)))
5047 (set (make-local-variable var) nil))
5048 (set (make-local-variable var) (symbol-value var))
5049 (add-to-list var val))))))
5050 ((equal key "ARCHIVE")
5051 (setq arch value)
5052 (remove-text-properties 0 (length arch)
5053 '(face t fontified t) arch))
5054 ((equal key "OPTIONS")
5055 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5056 (setq scripts (read (match-string 2 value)))))
5057 ((and (equal key "SETUPFILE")
5058 ;; Prevent checking in Gnus messages
5059 (not buffer-read-only))
5060 (setq setup-contents (org-file-contents
5061 (expand-file-name
5062 (org-remove-double-quotes value))
5063 'noerror))
5064 (if (not ext-setup-or-nil)
5065 (setq ext-setup-or-nil setup-contents start 0)
5066 (setq ext-setup-or-nil
5067 (concat (substring ext-setup-or-nil 0 start)
5068 "\n" setup-contents "\n"
5069 (substring ext-setup-or-nil start)))))))
5070 ;; search for property blocks
5071 (goto-char (point-min))
5072 (while (re-search-forward org-block-regexp nil t)
5073 (when (equal "PROPERTY" (upcase (match-string 1)))
5074 (setq value (replace-regexp-in-string
5075 "[\n\r]" " " (match-string 4)))
5076 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5077 (setq props (org-update-property-plist (match-string 1 value)
5078 (match-string 2 value)
5079 props)))))))
5080 (org-set-local 'org-use-sub-superscripts scripts)
5081 (when cat
5082 (org-set-local 'org-category (intern cat))
5083 (push (cons "CATEGORY" cat) props))
5084 (when prio
5085 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5086 (setq prio (mapcar 'string-to-char prio))
5087 (org-set-local 'org-highest-priority (nth 0 prio))
5088 (org-set-local 'org-lowest-priority (nth 1 prio))
5089 (org-set-local 'org-default-priority (nth 2 prio)))
5090 (and props (org-set-local 'org-file-properties (nreverse props)))
5091 (and arch (org-set-local 'org-archive-location arch))
5092 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5093 ;; Process the TODO keywords
5094 (unless kwds
5095 ;; Use the global values as if they had been given locally.
5096 (setq kwds (default-value 'org-todo-keywords))
5097 (if (stringp (car kwds))
5098 (setq kwds (list (cons org-todo-interpretation
5099 (default-value 'org-todo-keywords)))))
5100 (setq kwds (reverse kwds)))
5101 (setq kwds (nreverse kwds))
5102 (let (inter kws kw)
5103 (while (setq kws (pop kwds))
5104 (let ((kws (or
5105 (run-hook-with-args-until-success
5106 'org-todo-setup-filter-hook kws)
5107 kws)))
5108 (setq inter (pop kws) sep (member "|" kws)
5109 kws0 (delete "|" (copy-sequence kws))
5110 kwsa nil
5111 kws1 (mapcar
5112 (lambda (x)
5113 ;; 1 2
5114 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5115 (progn
5116 (setq kw (match-string 1 x)
5117 key (and (match-end 2) (match-string 2 x))
5118 log (org-extract-log-state-settings x))
5119 (push (cons kw (and key (string-to-char key))) kwsa)
5120 (and log (push log org-todo-log-states))
5122 (error "Invalid TODO keyword %s" x)))
5123 kws0)
5124 kwsa (if kwsa (append '((:startgroup))
5125 (nreverse kwsa)
5126 '((:endgroup))))
5127 hw (car kws1)
5128 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5129 tail (list inter hw (car dws) (org-last dws))))
5130 (add-to-list 'org-todo-heads hw 'append)
5131 (push kws1 org-todo-sets)
5132 (setq org-done-keywords (append org-done-keywords dws nil))
5133 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5134 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5135 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5136 (setq org-todo-sets (nreverse org-todo-sets)
5137 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5138 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5139 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5140 ;; Compute the regular expressions and other local variables.
5141 ;; Using `org-outline-regexp-bol' would complicate them much,
5142 ;; because of the fixed white space at the end of that string.
5143 (if (not org-done-keywords)
5144 (setq org-done-keywords (and org-todo-keywords-1
5145 (list (org-last org-todo-keywords-1)))))
5146 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5147 (length org-scheduled-string)
5148 (length org-clock-string)
5149 (length org-closed-string)))
5150 org-not-done-keywords
5151 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5152 org-todo-regexp
5153 (concat "\\("
5154 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5155 "\\)")
5156 org-not-done-regexp
5157 (concat "\\("
5158 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5159 "\\)")
5160 org-not-done-heading-regexp
5161 (format org-heading-keyword-regexp-format org-not-done-regexp)
5162 org-todo-line-regexp
5163 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5164 org-complex-heading-regexp
5165 (concat "^\\(\\*+\\)"
5166 "\\(?: +" org-todo-regexp "\\)?"
5167 "\\(?: +\\(\\[#.\\]\\)\\)?"
5168 "\\(?: +\\(.*?\\)\\)??"
5169 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5170 "[ \t]*$")
5171 org-complex-heading-regexp-format
5172 (concat "^\\(\\*+\\)"
5173 "\\(?: +" org-todo-regexp "\\)?"
5174 "\\(?: +\\(\\[#.\\]\\)\\)?"
5175 "\\(?: +"
5176 ;; Stats cookies can be stuck to body.
5177 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5178 "\\(%s\\)"
5179 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5180 "\\)"
5181 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5182 "[ \t]*$")
5183 org-todo-line-tags-regexp
5184 (concat "^\\(\\*+\\)"
5185 "\\(?: +" org-todo-regexp "\\)?"
5186 "\\(?: +\\(.*?\\)\\)??"
5187 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5188 "[ \t]*$")
5189 org-deadline-regexp (concat "\\<" org-deadline-string)
5190 org-deadline-time-regexp
5191 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5192 org-deadline-time-hour-regexp
5193 (concat "\\<" org-deadline-string
5194 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5195 org-deadline-line-regexp
5196 (concat "\\<\\(" org-deadline-string "\\).*")
5197 org-scheduled-regexp
5198 (concat "\\<" org-scheduled-string)
5199 org-scheduled-time-regexp
5200 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5201 org-scheduled-time-hour-regexp
5202 (concat "\\<" org-scheduled-string
5203 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5204 org-closed-time-regexp
5205 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5206 org-keyword-time-regexp
5207 (concat "\\<\\(" org-scheduled-string
5208 "\\|" org-deadline-string
5209 "\\|" org-closed-string
5210 "\\|" org-clock-string "\\)"
5211 " *[[<]\\([^]>]+\\)[]>]")
5212 org-keyword-time-not-clock-regexp
5213 (concat "\\<\\(" org-scheduled-string
5214 "\\|" org-deadline-string
5215 "\\|" org-closed-string
5216 "\\)"
5217 " *[[<]\\([^]>]+\\)[]>]")
5218 org-maybe-keyword-time-regexp
5219 (concat "\\(\\<\\(" org-scheduled-string
5220 "\\|" org-deadline-string
5221 "\\|" org-closed-string
5222 "\\|" org-clock-string "\\)\\)?"
5223 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5224 org-all-time-keywords
5225 (mapcar (lambda (w) (substring w 0 -1))
5226 (list org-scheduled-string org-deadline-string
5227 org-clock-string org-closed-string)))
5228 (setq org-ota nil)
5229 (org-compute-latex-and-related-regexp))))
5231 (defun org-file-contents (file &optional noerror)
5232 "Return the contents of FILE, as a string."
5233 (if (and file (file-readable-p file))
5234 (with-temp-buffer
5235 (insert-file-contents file)
5236 (buffer-string))
5237 (funcall (if noerror #'message #'error)
5238 "Cannot read file \"%s\"%s"
5239 file
5240 (let ((from (buffer-file-name (buffer-base-buffer))))
5241 (if from (concat " (referenced in file \"" from "\")") "")))))
5243 (defun org-extract-log-state-settings (x)
5244 "Extract the log state setting from a TODO keyword string.
5245 This will extract info from a string like \"WAIT(w@/!)\"."
5246 (let (kw key log1 log2)
5247 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5248 (setq kw (match-string 1 x)
5249 key (and (match-end 2) (match-string 2 x))
5250 log1 (and (match-end 3) (match-string 3 x))
5251 log2 (and (match-end 4) (match-string 4 x)))
5252 (and (or log1 log2)
5253 (list kw
5254 (and log1 (if (equal log1 "!") 'time 'note))
5255 (and log2 (if (equal log2 "!") 'time 'note)))))))
5257 (defun org-remove-keyword-keys (list)
5258 "Remove a pair of parenthesis at the end of each string in LIST."
5259 (mapcar (lambda (x)
5260 (if (string-match "(.*)$" x)
5261 (substring x 0 (match-beginning 0))
5263 list))
5265 (defun org-assign-fast-keys (alist)
5266 "Assign fast keys to a keyword-key alist.
5267 Respect keys that are already there."
5268 (let (new e (alt ?0))
5269 (while (setq e (pop alist))
5270 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5271 (cdr e)) ;; Key already assigned.
5272 (push e new)
5273 (let ((clist (string-to-list (downcase (car e))))
5274 (used (append new alist)))
5275 (when (= (car clist) ?@)
5276 (pop clist))
5277 (while (and clist (rassoc (car clist) used))
5278 (pop clist))
5279 (unless clist
5280 (while (rassoc alt used)
5281 (incf alt)))
5282 (push (cons (car e) (or (car clist) alt)) new))))
5283 (nreverse new)))
5285 ;;; Some variables used in various places
5287 (defvar org-window-configuration nil
5288 "Used in various places to store a window configuration.")
5289 (defvar org-selected-window nil
5290 "Used in various places to store a window configuration.")
5291 (defvar org-finish-function nil
5292 "Function to be called when `C-c C-c' is used.
5293 This is for getting out of special buffers like capture.")
5296 ;; FIXME: Occasionally check by commenting these, to make sure
5297 ;; no other functions uses these, forgetting to let-bind them.
5298 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5299 (defvar org-last-state)
5300 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5302 ;; Defined somewhere in this file, but used before definition.
5303 (defvar org-entities) ;; defined in org-entities.el
5304 (defvar org-struct-menu)
5305 (defvar org-org-menu)
5306 (defvar org-tbl-menu)
5308 ;;;; Define the Org-mode
5310 ;; We use a before-change function to check if a table might need
5311 ;; an update.
5312 (defvar org-table-may-need-update t
5313 "Indicates that a table might need an update.
5314 This variable is set by `org-before-change-function'.
5315 `org-table-align' sets it back to nil.")
5316 (defun org-before-change-function (beg end)
5317 "Every change indicates that a table might need an update."
5318 (setq org-table-may-need-update t))
5319 (defvar org-mode-map)
5320 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5321 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5322 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5323 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5324 (defvar org-table-buffer-is-an nil)
5326 (defvar bidi-paragraph-direction)
5327 (defvar buffer-face-mode-face)
5329 (require 'outline)
5330 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5331 (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"))
5332 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5334 ;; Other stuff we need.
5335 (require 'time-date)
5336 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5337 (require 'easymenu)
5338 (require 'overlay)
5340 ;; (require 'org-macs) moved higher up in the file before it is first used
5341 (require 'org-entities)
5342 ;; (require 'org-compat) moved higher up in the file before it is first used
5343 (require 'org-faces)
5344 (require 'org-list)
5345 (require 'org-pcomplete)
5346 (require 'org-src)
5347 (require 'org-footnote)
5348 (require 'org-macro)
5350 ;; babel
5351 (require 'ob)
5353 ;;;###autoload
5354 (define-derived-mode org-mode outline-mode "Org"
5355 "Outline-based notes management and organizer, alias
5356 \"Carsten's outline-mode for keeping track of everything.\"
5358 Org-mode develops organizational tasks around a NOTES file which
5359 contains information about projects as plain text. Org-mode is
5360 implemented on top of outline-mode, which is ideal to keep the content
5361 of large files well structured. It supports ToDo items, deadlines and
5362 time stamps, which magically appear in the diary listing of the Emacs
5363 calendar. Tables are easily created with a built-in table editor.
5364 Plain text URL-like links connect to websites, emails (VM), Usenet
5365 messages (Gnus), BBDB entries, and any files related to the project.
5366 For printing and sharing of notes, an Org-mode file (or a part of it)
5367 can be exported as a structured ASCII or HTML file.
5369 The following commands are available:
5371 \\{org-mode-map}"
5373 ;; Get rid of Outline menus, they are not needed
5374 ;; Need to do this here because define-derived-mode sets up
5375 ;; the keymap so late. Still, it is a waste to call this each time
5376 ;; we switch another buffer into org-mode.
5377 (if (featurep 'xemacs)
5378 (when (boundp 'outline-mode-menu-heading)
5379 ;; Assume this is Greg's port, it uses easymenu
5380 (easy-menu-remove outline-mode-menu-heading)
5381 (easy-menu-remove outline-mode-menu-show)
5382 (easy-menu-remove outline-mode-menu-hide))
5383 (define-key org-mode-map [menu-bar headings] 'undefined)
5384 (define-key org-mode-map [menu-bar hide] 'undefined)
5385 (define-key org-mode-map [menu-bar show] 'undefined))
5387 (org-load-modules-maybe)
5388 (easy-menu-add org-org-menu)
5389 (easy-menu-add org-tbl-menu)
5390 (org-install-agenda-files-menu)
5391 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5392 (add-to-invisibility-spec '(org-cwidth))
5393 (add-to-invisibility-spec '(org-hide-block . t))
5394 (when (featurep 'xemacs)
5395 (org-set-local 'line-move-ignore-invisible t))
5396 (org-set-local 'outline-regexp org-outline-regexp)
5397 (org-set-local 'outline-level 'org-outline-level)
5398 (setq bidi-paragraph-direction 'left-to-right)
5399 (when (and org-ellipsis
5400 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5401 (fboundp 'make-glyph-code))
5402 (unless org-display-table
5403 (setq org-display-table (make-display-table)))
5404 (set-display-table-slot
5405 org-display-table 4
5406 (vconcat (mapcar
5407 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5408 org-ellipsis)))
5409 (if (stringp org-ellipsis) org-ellipsis "..."))))
5410 (setq buffer-display-table org-display-table))
5411 (org-set-regexps-and-options-for-tags)
5412 (org-set-regexps-and-options)
5413 (org-set-font-lock-defaults)
5414 (when (and org-tag-faces (not org-tags-special-faces-re))
5415 ;; tag faces set outside customize.... force initialization.
5416 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5417 ;; Calc embedded
5418 (org-set-local 'calc-embedded-open-mode "# ")
5419 ;; Modify a few syntax entries
5420 (modify-syntax-entry ?@ "w")
5421 (modify-syntax-entry ?\" "\"")
5422 (if org-startup-truncated (setq truncate-lines t))
5423 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5424 (org-set-local 'font-lock-unfontify-region-function
5425 'org-unfontify-region)
5426 ;; Activate before-change-function
5427 (org-set-local 'org-table-may-need-update t)
5428 (org-add-hook 'before-change-functions 'org-before-change-function nil
5429 'local)
5430 ;; Check for running clock before killing a buffer
5431 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5432 ;; Initialize macros templates.
5433 (org-macro-initialize-templates)
5434 ;; Initialize radio targets.
5435 (org-update-radio-target-regexp)
5436 ;; Indentation.
5437 (org-set-local 'indent-line-function 'org-indent-line)
5438 (org-set-local 'indent-region-function 'org-indent-region)
5439 ;; Filling and auto-filling.
5440 (org-setup-filling)
5441 ;; Comments.
5442 (org-setup-comments-handling)
5443 ;; Initialize cache.
5444 (org-element-cache-reset)
5445 ;; Beginning/end of defun
5446 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5447 (org-set-local 'end-of-defun-function 'org-forward-element)
5448 ;; Next error for sparse trees
5449 (org-set-local 'next-error-function 'org-occur-next-match)
5450 ;; Make sure dependence stuff works reliably, even for users who set it
5451 ;; too late :-(
5452 (if org-enforce-todo-dependencies
5453 (add-hook 'org-blocker-hook
5454 'org-block-todo-from-children-or-siblings-or-parent)
5455 (remove-hook 'org-blocker-hook
5456 'org-block-todo-from-children-or-siblings-or-parent))
5457 (if org-enforce-todo-checkbox-dependencies
5458 (add-hook 'org-blocker-hook
5459 'org-block-todo-from-checkboxes)
5460 (remove-hook 'org-blocker-hook
5461 'org-block-todo-from-checkboxes))
5463 ;; Align options lines
5464 (org-set-local
5465 'align-mode-rules-list
5466 '((org-in-buffer-settings
5467 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5468 (modes . '(org-mode)))))
5470 ;; Imenu
5471 (org-set-local 'imenu-create-index-function
5472 'org-imenu-get-tree)
5474 ;; Make isearch reveal context
5475 (if (or (featurep 'xemacs)
5476 (not (boundp 'outline-isearch-open-invisible-function)))
5477 ;; Emacs 21 and XEmacs make use of the hook
5478 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5479 ;; Emacs 22 deals with this through a special variable
5480 (org-set-local 'outline-isearch-open-invisible-function
5481 (lambda (&rest ignore) (org-show-context 'isearch)))
5482 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5484 ;; Setup the pcomplete hooks
5485 (set (make-local-variable 'pcomplete-command-completion-function)
5486 'org-pcomplete-initial)
5487 (set (make-local-variable 'pcomplete-command-name-function)
5488 'org-command-at-point)
5489 (set (make-local-variable 'pcomplete-default-completion-function)
5490 'ignore)
5491 (set (make-local-variable 'pcomplete-parse-arguments-function)
5492 'org-parse-arguments)
5493 (set (make-local-variable 'pcomplete-termination-string) "")
5494 (when (>= emacs-major-version 23)
5495 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5497 ;; If empty file that did not turn on org-mode automatically, make it to.
5498 (if (and org-insert-mode-line-in-empty-file
5499 (org-called-interactively-p 'any)
5500 (= (point-min) (point-max)))
5501 (insert "# -*- mode: org -*-\n\n"))
5502 (unless org-inhibit-startup
5503 (org-unmodified
5504 (and org-startup-with-beamer-mode (org-beamer-mode))
5505 (when org-startup-align-all-tables
5506 (org-table-map-tables 'org-table-align 'quietly))
5507 (when org-startup-with-inline-images
5508 (org-display-inline-images))
5509 (when org-startup-with-latex-preview
5510 (org-preview-latex-fragment))
5511 (unless org-inhibit-startup-visibility-stuff
5512 (org-set-startup-visibility))))
5513 ;; Try to set org-hide correctly
5514 (set-face-foreground 'org-hide (org-find-invisible-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" "news"
5589 "shell" "elisp" "doi" "message" "help"))
5590 (defvar org-link-types-re nil
5591 "Matches a link that has a url-like prefix like \"http:\"")
5592 (defvar org-link-re-with-space nil
5593 "Matches a link with spaces, optional angular brackets around it.")
5594 (defvar org-link-re-with-space2 nil
5595 "Matches a link with spaces, optional angular brackets around it.")
5596 (defvar org-link-re-with-space3 nil
5597 "Matches a link with spaces, only for internal part in bracket links.")
5598 (defvar org-angle-link-re nil
5599 "Matches link with angular brackets, spaces are allowed.")
5600 (defvar org-plain-link-re nil
5601 "Matches plain link, without spaces.")
5602 (defvar org-bracket-link-regexp nil
5603 "Matches a link in double brackets.")
5604 (defvar org-bracket-link-analytic-regexp nil
5605 "Regular expression used to analyze links.
5606 Here is what the match groups contain after a match:
5607 1: http:
5608 2: http
5609 3: path
5610 4: [desc]
5611 5: desc")
5612 (defvar org-bracket-link-analytic-regexp++ nil
5613 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5614 (defvar org-any-link-re nil
5615 "Regular expression matching any link.")
5617 (defconst org-match-sexp-depth 3
5618 "Number of stacked braces for sub/superscript matching.")
5620 (defun org-create-multibrace-regexp (left right n)
5621 "Create a regular expression which will match a balanced sexp.
5622 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5623 as single character strings.
5624 The regexp returned will match the entire expression including the
5625 delimiters. It will also define a single group which contains the
5626 match except for the outermost delimiters. The maximum depth of
5627 stacked delimiters is N. Escaping delimiters is not possible."
5628 (let* ((nothing (concat "[^" left right "]*?"))
5629 (or "\\|")
5630 (re nothing)
5631 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5632 (while (> n 1)
5633 (setq n (1- n)
5634 re (concat re or next)
5635 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5636 (concat left "\\(" re "\\)" right)))
5638 (defconst org-match-substring-regexp
5639 (concat
5640 "\\(\\S-\\)\\([_^]\\)\\("
5641 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5642 "\\|"
5643 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5644 "\\|"
5645 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5646 "The regular expression matching a sub- or superscript.")
5648 (defconst org-match-substring-with-braces-regexp
5649 (concat
5650 "\\(\\S-\\)\\([_^]\\)"
5651 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5652 "The regular expression matching a sub- or superscript, forcing braces.")
5654 (defun org-make-link-regexps ()
5655 "Update the link regular expressions.
5656 This should be called after the variable `org-link-types' has changed."
5657 (setq org-link-types-re
5658 (concat
5659 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5660 org-link-re-with-space
5661 (concat
5662 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5663 "\\([^" org-non-link-chars " ]"
5664 "[^" org-non-link-chars "]*"
5665 "[^" org-non-link-chars " ]\\)>?")
5666 org-link-re-with-space2
5667 (concat
5668 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5669 "\\([^" org-non-link-chars " ]"
5670 "[^\t\n\r]*"
5671 "[^" org-non-link-chars " ]\\)>?")
5672 org-link-re-with-space3
5673 (concat
5674 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5675 "\\([^" org-non-link-chars " ]"
5676 "[^\t\n\r]*\\)")
5677 org-angle-link-re
5678 (concat
5679 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5680 "\\([^" org-non-link-chars " ]"
5681 "[^" org-non-link-chars "]*"
5682 "\\)>")
5683 org-plain-link-re
5684 (concat
5685 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5686 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5687 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5688 org-bracket-link-regexp
5689 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5690 org-bracket-link-analytic-regexp
5691 (concat
5692 "\\[\\["
5693 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5694 "\\([^]]+\\)"
5695 "\\]"
5696 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5697 "\\]")
5698 org-bracket-link-analytic-regexp++
5699 (concat
5700 "\\[\\["
5701 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5702 "\\([^]]+\\)"
5703 "\\]"
5704 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5705 "\\]")
5706 org-any-link-re
5707 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5708 org-angle-link-re "\\)\\|\\("
5709 org-plain-link-re "\\)")))
5711 (org-make-link-regexps)
5713 (defvar org-emph-face nil)
5715 (defun org-do-emphasis-faces (limit)
5716 "Run through the buffer and add overlays to emphasized strings."
5717 (let (rtn a)
5718 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5719 (if (not (= (char-after (match-beginning 3))
5720 (char-after (match-beginning 4))))
5721 (progn
5722 (setq rtn t)
5723 (setq a (assoc (match-string 3) org-emphasis-alist))
5724 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5725 'face
5726 (nth 1 a))
5727 (and (nth 2 a)
5728 (org-remove-flyspell-overlays-in
5729 (match-beginning 0) (match-end 0)))
5730 (add-text-properties (match-beginning 2) (match-end 2)
5731 '(font-lock-multiline t org-emphasis t))
5732 (when org-hide-emphasis-markers
5733 (add-text-properties (match-end 4) (match-beginning 5)
5734 '(invisible org-link))
5735 (add-text-properties (match-beginning 3) (match-end 3)
5736 '(invisible org-link)))))
5737 (goto-char (1+ (match-beginning 0))))
5738 rtn))
5740 (defun org-emphasize (&optional char)
5741 "Insert or change an emphasis, i.e. a font like bold or italic.
5742 If there is an active region, change that region to a new emphasis.
5743 If there is no region, just insert the marker characters and position
5744 the cursor between them.
5745 CHAR should be the marker character. If it is a space, it means to
5746 remove the emphasis of the selected region.
5747 If CHAR is not given (for example in an interactive call) it will be
5748 prompted for."
5749 (interactive)
5750 (let ((erc org-emphasis-regexp-components)
5751 (prompt "")
5752 (string "") beg end move c s)
5753 (if (org-region-active-p)
5754 (setq beg (region-beginning) end (region-end)
5755 string (buffer-substring beg end))
5756 (setq move t))
5758 (unless char
5759 (message "Emphasis marker or tag: [%s]"
5760 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5761 (setq char (read-char-exclusive)))
5762 (if (equal char ?\ )
5763 (setq s "" move nil)
5764 (unless (assoc (char-to-string char) org-emphasis-alist)
5765 (user-error "No such emphasis marker: \"%c\"" char))
5766 (setq s (char-to-string char)))
5767 (while (and (> (length string) 1)
5768 (equal (substring string 0 1) (substring string -1))
5769 (assoc (substring string 0 1) org-emphasis-alist))
5770 (setq string (substring string 1 -1)))
5771 (setq string (concat s string s))
5772 (if beg (delete-region beg end))
5773 (unless (or (bolp)
5774 (string-match (concat "[" (nth 0 erc) "\n]")
5775 (char-to-string (char-before (point)))))
5776 (insert " "))
5777 (unless (or (eobp)
5778 (string-match (concat "[" (nth 1 erc) "\n]")
5779 (char-to-string (char-after (point)))))
5780 (insert " ") (backward-char 1))
5781 (insert string)
5782 (and move (backward-char 1))))
5784 (defconst org-nonsticky-props
5785 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5787 (defsubst org-rear-nonsticky-at (pos)
5788 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5790 (defun org-activate-plain-links (limit)
5791 "Run through the buffer and add overlays to links."
5792 (let (f hl)
5793 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5794 (not (org-in-src-block-p)))
5795 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5796 (setq f (get-text-property (match-beginning 0) 'face))
5797 (setq hl (org-match-string-no-properties 0))
5798 (if (or (eq f 'org-tag)
5799 (and (listp f) (memq 'org-tag f)))
5801 (add-text-properties (match-beginning 0) (match-end 0)
5802 (list 'mouse-face 'highlight
5803 'face 'org-link
5804 'htmlize-link `(:uri ,hl)
5805 'keymap org-mouse-map))
5806 (org-rear-nonsticky-at (match-end 0)))
5807 t)))
5809 (defun org-activate-code (limit)
5810 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5811 (progn
5812 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5813 (remove-text-properties (match-beginning 0) (match-end 0)
5814 '(display t invisible t intangible t))
5815 t)))
5817 (defcustom org-src-fontify-natively t
5818 "When non-nil, fontify code in code blocks."
5819 :type 'boolean
5820 :version "24.4"
5821 :package-version '(Org . "8.3")
5822 :group 'org-appearance
5823 :group 'org-babel)
5825 (defcustom org-allow-promoting-top-level-subtree nil
5826 "When non-nil, allow promoting a top level subtree.
5827 The leading star of the top level headline will be replaced
5828 by a #."
5829 :type 'boolean
5830 :version "24.1"
5831 :group 'org-appearance)
5833 (defun org-fontify-meta-lines-and-blocks (limit)
5834 (condition-case nil
5835 (org-fontify-meta-lines-and-blocks-1 limit)
5836 (error (message "org-mode fontification error"))))
5838 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5839 "Fontify #+ lines and blocks."
5840 (let ((case-fold-search t))
5841 (if (re-search-forward
5842 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5843 limit t)
5844 (let ((beg (match-beginning 0))
5845 (block-start (match-end 0))
5846 (block-end nil)
5847 (lang (match-string 7))
5848 (beg1 (line-beginning-position 2))
5849 (dc1 (downcase (match-string 2)))
5850 (dc3 (downcase (match-string 3)))
5851 end end1 quoting block-type ovl)
5852 (cond
5853 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5854 ;; a single line of backend-specific content
5855 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5856 (remove-text-properties (match-beginning 0) (match-end 0)
5857 '(display t invisible t intangible t))
5858 (add-text-properties (match-beginning 1) (match-end 3)
5859 '(font-lock-fontified t face org-meta-line))
5860 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5861 '(font-lock-fontified t face org-block))
5862 ; for backend-specific code
5864 ((and (match-end 4) (equal dc3 "+begin"))
5865 ;; Truly a block
5866 (setq block-type (downcase (match-string 5))
5867 quoting (member block-type org-protecting-blocks))
5868 (when (re-search-forward
5869 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5870 nil t) ;; on purpose, we look further than LIMIT
5871 (setq end (min (point-max) (match-end 0))
5872 end1 (min (point-max) (1- (match-beginning 0))))
5873 (setq block-end (match-beginning 0))
5874 (when quoting
5875 (org-remove-flyspell-overlays-in beg1 end1)
5876 (remove-text-properties beg end
5877 '(display t invisible t intangible t)))
5878 (add-text-properties
5879 beg end '(font-lock-fontified t font-lock-multiline t))
5880 (add-text-properties beg beg1 '(face org-meta-line))
5881 (org-remove-flyspell-overlays-in beg beg1)
5882 (add-text-properties ; For end_src
5883 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5884 (org-remove-flyspell-overlays-in end1 end)
5885 (cond
5886 ((and lang (not (string= lang "")) org-src-fontify-natively)
5887 (org-src-font-lock-fontify-block lang block-start block-end)
5888 ;; remove old background overlays
5889 (mapc (lambda (ov)
5890 (if (eq (overlay-get ov 'face) 'org-block-background)
5891 (delete-overlay ov)))
5892 (overlays-at (/ (+ beg1 block-end) 2)))
5893 ;; add a background overlay
5894 (setq ovl (make-overlay beg1 block-end))
5895 (overlay-put ovl 'face 'org-block-background)
5896 (overlay-put ovl 'evaporate t)) ; make it go away when empty
5897 (quoting
5898 (add-text-properties beg1 (min (point-max) (1+ end1))
5899 '(face org-block))) ; end of source block
5900 ((not org-fontify-quote-and-verse-blocks))
5901 ((string= block-type "quote")
5902 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5903 ((string= block-type "verse")
5904 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5905 (add-text-properties beg beg1 '(face org-block-begin-line))
5906 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5907 '(face org-block-end-line))
5909 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5910 (org-remove-flyspell-overlays-in
5911 (match-beginning 0)
5912 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5913 (add-text-properties
5914 beg (match-end 3)
5915 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5916 '(font-lock-fontified t invisible t)
5917 '(font-lock-fontified t face org-document-info-keyword)))
5918 (add-text-properties
5919 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5920 (if (string-equal dc1 "+title:")
5921 '(font-lock-fontified t face org-document-title)
5922 '(font-lock-fontified t face org-document-info))))
5923 ((or (equal dc1 "+results")
5924 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5925 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5926 "+call:" "+header:" "+headers:" "+name:"))
5927 (and (match-end 4) (equal dc3 "+attr")))
5928 (org-remove-flyspell-overlays-in
5929 (match-beginning 0)
5930 (if (equal "+caption:" dc1) (match-end 2) (match-end 0)))
5931 (add-text-properties
5932 beg (match-end 0)
5933 '(font-lock-fontified t face org-meta-line))
5935 ((member dc3 '(" " ""))
5936 (org-remove-flyspell-overlays-in beg (match-end 0))
5937 (add-text-properties
5938 beg (match-end 0)
5939 '(font-lock-fontified t face font-lock-comment-face)))
5940 ((not (member (char-after beg) '(?\ ?\t)))
5941 ;; just any other in-buffer setting, but not indented
5942 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5943 (add-text-properties
5944 beg (match-end 0)
5945 '(font-lock-fontified t face org-meta-line))
5947 (t nil))))))
5949 (defun org-fontify-drawers (limit)
5950 "Fontify drawers."
5951 (when (re-search-forward org-drawer-regexp limit t)
5952 (add-text-properties
5953 (match-beginning 0) (match-end 0)
5954 '(font-lock-fontified t face org-special-keyword))
5955 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5958 (defun org-fontify-macros (limit)
5959 "Fontify macros."
5960 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5961 (add-text-properties
5962 (match-beginning 0) (match-end 0)
5963 '(font-lock-fontified t face org-macro))
5964 (when org-hide-macro-markers
5965 (add-text-properties (match-end 2) (match-beginning 2)
5966 '(invisible t))
5967 (add-text-properties (match-beginning 1) (match-end 1)
5968 '(invisible t)))
5969 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5972 (defun org-activate-angle-links (limit)
5973 "Run through the buffer and add overlays to links."
5974 (if (and (re-search-forward org-angle-link-re limit t)
5975 (not (org-in-src-block-p)))
5976 (progn
5977 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5978 (add-text-properties (match-beginning 0) (match-end 0)
5979 (list 'mouse-face 'highlight
5980 'keymap org-mouse-map))
5981 (org-rear-nonsticky-at (match-end 0))
5982 t)))
5984 (defun org-activate-footnote-links (limit)
5985 "Run through the buffer and add overlays to footnotes."
5986 (let ((fn (org-footnote-next-reference-or-definition limit)))
5987 (when fn
5988 (let* ((beg (nth 1 fn))
5989 (end (nth 2 fn))
5990 (label (car fn))
5991 (referencep (/= (line-beginning-position) beg)))
5992 (when (and referencep (nth 3 fn))
5993 (save-excursion
5994 (goto-char beg)
5995 (search-forward (or label "fn:"))
5996 (org-remove-flyspell-overlays-in beg (match-end 0))))
5997 (add-text-properties beg end
5998 (list 'mouse-face 'highlight
5999 'keymap org-mouse-map
6000 'help-echo
6001 (if referencep "Footnote reference"
6002 "Footnote definition")
6003 'font-lock-fontified t
6004 'font-lock-multiline t
6005 'face 'org-footnote))))))
6007 (defun org-activate-bracket-links (limit)
6008 "Run through the buffer and add overlays to bracketed links."
6009 (if (and (re-search-forward org-bracket-link-regexp limit t)
6010 (not (org-in-src-block-p)))
6011 (let* ((hl (org-match-string-no-properties 1))
6012 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6013 (ip (org-maybe-intangible
6014 (list 'invisible 'org-link
6015 'keymap org-mouse-map 'mouse-face 'highlight
6016 'font-lock-multiline t 'help-echo help
6017 'htmlize-link `(:uri ,hl))))
6018 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6019 'font-lock-multiline t 'help-echo help
6020 'htmlize-link `(:uri ,hl))))
6021 ;; We need to remove the invisible property here. Table narrowing
6022 ;; may have made some of this invisible.
6023 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6024 (remove-text-properties (match-beginning 0) (match-end 0)
6025 '(invisible nil))
6026 (if (match-end 3)
6027 (progn
6028 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6029 (org-rear-nonsticky-at (match-beginning 3))
6030 (add-text-properties (match-beginning 3) (match-end 3) vp)
6031 (org-rear-nonsticky-at (match-end 3))
6032 (add-text-properties (match-end 3) (match-end 0) ip)
6033 (org-rear-nonsticky-at (match-end 0)))
6034 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6035 (org-rear-nonsticky-at (match-beginning 1))
6036 (add-text-properties (match-beginning 1) (match-end 1) vp)
6037 (org-rear-nonsticky-at (match-end 1))
6038 (add-text-properties (match-end 1) (match-end 0) ip)
6039 (org-rear-nonsticky-at (match-end 0)))
6040 t)))
6042 (defun org-activate-dates (limit)
6043 "Run through the buffer and add overlays to dates."
6044 (if (and (re-search-forward org-tsr-regexp-both limit t)
6045 (not (equal (char-before (match-beginning 0)) 91)))
6046 (progn
6047 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6048 (add-text-properties (match-beginning 0) (match-end 0)
6049 (list 'mouse-face 'highlight
6050 'keymap org-mouse-map))
6051 (org-rear-nonsticky-at (match-end 0))
6052 (when org-display-custom-times
6053 (if (match-end 3)
6054 (org-display-custom-time (match-beginning 3) (match-end 3)))
6055 (org-display-custom-time (match-beginning 1) (match-end 1)))
6056 t)))
6058 (defvar org-target-link-regexp nil
6059 "Regular expression matching radio targets in plain text.")
6060 (make-variable-buffer-local 'org-target-link-regexp)
6061 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
6062 "Regular expression matching a link target.")
6063 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
6064 "Regular expression matching a radio target.")
6065 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
6066 "Regular expression matching any target.")
6068 (defun org-activate-target-links (limit)
6069 "Run through the buffer and add overlays to target matches."
6070 (when org-target-link-regexp
6071 (let ((case-fold-search t))
6072 (if (re-search-forward org-target-link-regexp limit t)
6073 (progn
6074 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6075 (add-text-properties (match-beginning 0) (match-end 0)
6076 (list 'mouse-face 'highlight
6077 'keymap org-mouse-map
6078 'help-echo "Radio target link"
6079 'org-linked-text t))
6080 (org-rear-nonsticky-at (match-end 0))
6081 t)))))
6083 (defun org-update-radio-target-regexp ()
6084 "Find all radio targets in this file and update the regular expression."
6085 (interactive)
6086 (when (memq 'radio org-activate-links)
6087 (setq org-target-link-regexp
6088 (org-make-target-link-regexp (org-all-targets 'radio)))
6089 (org-restart-font-lock)))
6091 (defun org-hide-wide-columns (limit)
6092 (let (s e)
6093 (setq s (text-property-any (point) (or limit (point-max))
6094 'org-cwidth t))
6095 (when s
6096 (setq e (next-single-property-change s 'org-cwidth))
6097 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6098 (goto-char e)
6099 t)))
6101 (defvar org-latex-and-related-regexp nil
6102 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6104 (defun org-compute-latex-and-related-regexp ()
6105 "Compute regular expression for LaTeX, entities and sub/superscript.
6106 Result depends on variable `org-highlight-latex-and-related'."
6107 (org-set-local
6108 'org-latex-and-related-regexp
6109 (let* ((re-sub
6110 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6111 ((eq org-use-sub-superscripts '{})
6112 (list org-match-substring-with-braces-regexp))
6113 (org-use-sub-superscripts (list org-match-substring-regexp))))
6114 (re-latex
6115 (when (memq 'latex org-highlight-latex-and-related)
6116 (let ((matchers (plist-get org-format-latex-options :matchers)))
6117 (delq nil
6118 (mapcar (lambda (x)
6119 (and (member (car x) matchers) (nth 1 x)))
6120 org-latex-regexps)))))
6121 (re-entities
6122 (when (memq 'entities org-highlight-latex-and-related)
6123 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6124 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6126 (defun org-do-latex-and-related (limit)
6127 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6128 LIMIT bounds the search for syntax to highlight. Stop at first
6129 highlighted object, if any. Return t if some highlighting was
6130 done, nil otherwise."
6131 (when (org-string-nw-p org-latex-and-related-regexp)
6132 (catch 'found
6133 (while (re-search-forward org-latex-and-related-regexp limit t)
6134 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6135 'face))
6136 '(org-code org-verbatim underline))
6137 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6138 '(?_ ?^))
6140 0)))
6141 (font-lock-prepend-text-property
6142 (+ offset (match-beginning 0)) (match-end 0)
6143 'face 'org-latex-and-related)
6144 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6145 '(font-lock-multiline t)))
6146 (throw 'found t)))
6147 nil)))
6149 (defun org-restart-font-lock ()
6150 "Restart `font-lock-mode', to force refontification."
6151 (when (and (boundp 'font-lock-mode) font-lock-mode)
6152 (font-lock-mode -1)
6153 (font-lock-mode 1)))
6155 (defun org-all-targets (&optional radio)
6156 "Return a list of all targets in this file.
6157 When optional argument RADIO is non-nil, only find radio
6158 targets."
6159 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6160 (save-excursion
6161 (goto-char (point-min))
6162 (while (re-search-forward re nil t)
6163 ;; Make sure point is really within the object.
6164 (backward-char)
6165 (let ((obj (org-element-context)))
6166 (when (memq (org-element-type obj) '(radio-target target))
6167 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6168 rtn)))
6170 (defun org-make-target-link-regexp (targets)
6171 "Make regular expression matching all strings in TARGETS.
6172 The regular expression finds the targets also if there is a line break
6173 between words."
6174 (and targets
6175 (concat
6176 "\\<\\("
6177 (mapconcat
6178 (lambda (x)
6179 (setq x (regexp-quote x))
6180 (while (string-match " +" x)
6181 (setq x (replace-match "\\s-+" t t x)))
6183 targets
6184 "\\|")
6185 "\\)\\>")))
6187 (defun org-activate-tags (limit)
6188 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6189 (progn
6190 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6191 (add-text-properties (match-beginning 1) (match-end 1)
6192 (list 'mouse-face 'highlight
6193 'keymap org-mouse-map))
6194 (org-rear-nonsticky-at (match-end 1))
6195 t)))
6197 (defun org-outline-level ()
6198 "Compute the outline level of the heading at point.
6199 If this is called at a normal headline, the level is the number of stars.
6200 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6201 (save-excursion
6202 (if (not (condition-case nil
6203 (org-back-to-heading t)
6204 (error nil)))
6206 (looking-at org-outline-regexp)
6207 (1- (- (match-end 0) (match-beginning 0))))))
6209 (defvar org-font-lock-keywords nil)
6211 (defsubst org-re-property (property &optional literal)
6212 "Return a regexp matching a PROPERTY line.
6213 Match group 3 will be set to the value if it exists."
6214 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6215 (if literal property (regexp-quote property))
6216 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6218 (defconst org-property-re
6219 (org-re-property ".*?" 'literal)
6220 "Regular expression matching a property line.
6221 There are four matching groups:
6222 1: :PROPKEY: including the leading and trailing colon,
6223 2: PROPKEY without the leading and trailing colon,
6224 3: PROPVAL without leading or trailing spaces,
6225 4: the indentation of the current line,
6226 5: trailing whitespace.")
6228 (defvar org-font-lock-hook nil
6229 "Functions to be called for special font lock stuff.")
6231 (defvar org-font-lock-set-keywords-hook nil
6232 "Functions that can manipulate `org-font-lock-extra-keywords'.
6233 This is called after `org-font-lock-extra-keywords' is defined, but before
6234 it is installed to be used by font lock. This can be useful if something
6235 needs to be inserted at a specific position in the font-lock sequence.")
6237 (defun org-font-lock-hook (limit)
6238 "Run `org-font-lock-hook' within LIMIT."
6239 (run-hook-with-args 'org-font-lock-hook limit))
6241 (defun org-set-font-lock-defaults ()
6242 "Set font lock defaults for the current buffer."
6243 (let* ((em org-fontify-emphasized-text)
6244 (lk org-activate-links)
6245 (org-font-lock-extra-keywords
6246 (list
6247 ;; Call the hook
6248 '(org-font-lock-hook)
6249 ;; Headlines
6250 `(,(if org-fontify-whole-heading-line
6251 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6252 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6253 (1 (org-get-level-face 1))
6254 (2 (org-get-level-face 2))
6255 (3 (org-get-level-face 3)))
6256 ;; Table lines
6257 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6258 (1 'org-table t))
6259 ;; Table internals
6260 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6261 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6262 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6263 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6264 ;; Drawers
6265 '(org-fontify-drawers)
6266 ;; Properties
6267 (list org-property-re
6268 '(1 'org-special-keyword t)
6269 '(3 'org-property-value t))
6270 ;; Links
6271 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6272 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6273 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6274 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6275 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6276 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6277 (if (memq 'footnote lk) '(org-activate-footnote-links))
6278 ;; Targets.
6279 (list org-any-target-regexp '(0 'org-target t))
6280 ;; Diary sexps.
6281 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6282 ;; Macro
6283 '(org-fontify-macros)
6284 '(org-hide-wide-columns (0 nil append))
6285 ;; TODO keyword
6286 (list (format org-heading-keyword-regexp-format
6287 org-todo-regexp)
6288 '(2 (org-get-todo-face 2) t))
6289 ;; DONE
6290 (if org-fontify-done-headline
6291 (list (format org-heading-keyword-regexp-format
6292 (concat
6293 "\\(?:"
6294 (mapconcat 'regexp-quote org-done-keywords "\\|")
6295 "\\)"))
6296 '(2 'org-headline-done t))
6297 nil)
6298 ;; Priorities
6299 '(org-font-lock-add-priority-faces)
6300 ;; Tags
6301 '(org-font-lock-add-tag-faces)
6302 ;; Tags groups
6303 (if (and org-group-tags org-tag-groups-alist)
6304 (list (concat org-outline-regexp-bol ".+\\(:"
6305 (regexp-opt (mapcar 'car org-tag-groups-alist))
6306 ":\\).*$")
6307 '(1 'org-tag-group prepend)))
6308 ;; Special keywords
6309 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6310 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6311 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6312 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6313 ;; Emphasis
6314 (if em
6315 (if (featurep 'xemacs)
6316 '(org-do-emphasis-faces (0 nil append))
6317 '(org-do-emphasis-faces)))
6318 ;; Checkboxes
6319 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6320 1 'org-checkbox prepend)
6321 (if (cdr (assq 'checkbox org-list-automatic-rules))
6322 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6323 (0 (org-get-checkbox-statistics-face) t)))
6324 ;; Description list items
6325 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6326 1 'org-list-dt prepend)
6327 ;; ARCHIVEd headings
6328 (list (concat
6329 org-outline-regexp-bol
6330 "\\(.*:" org-archive-tag ":.*\\)")
6331 '(1 'org-archived prepend))
6332 ;; Specials
6333 '(org-do-latex-and-related)
6334 '(org-fontify-entities)
6335 '(org-raise-scripts)
6336 ;; Code
6337 '(org-activate-code (1 'org-code t))
6338 ;; COMMENT
6339 (list (format org-heading-keyword-regexp-format
6340 (concat "\\(" org-comment-string "\\)"))
6341 '(2 'org-special-keyword t))
6342 ;; Blocks and meta lines
6343 '(org-fontify-meta-lines-and-blocks))))
6344 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6345 (run-hooks 'org-font-lock-set-keywords-hook)
6346 ;; Now set the full font-lock-keywords
6347 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6348 (org-set-local 'font-lock-defaults
6349 '(org-font-lock-keywords t nil nil backward-paragraph))
6350 (kill-local-variable 'font-lock-keywords) nil))
6352 (defun org-toggle-pretty-entities ()
6353 "Toggle the composition display of entities as UTF8 characters."
6354 (interactive)
6355 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6356 (org-restart-font-lock)
6357 (if org-pretty-entities
6358 (message "Entities are now displayed as UTF8 characters")
6359 (save-restriction
6360 (widen)
6361 (org-decompose-region (point-min) (point-max))
6362 (message "Entities are now displayed as plain text"))))
6364 (defvar org-custom-properties-overlays nil
6365 "List of overlays used for custom properties.")
6366 (make-variable-buffer-local 'org-custom-properties-overlays)
6368 (defun org-toggle-custom-properties-visibility ()
6369 "Display or hide properties in `org-custom-properties'."
6370 (interactive)
6371 (if org-custom-properties-overlays
6372 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6373 (setq org-custom-properties-overlays nil))
6374 (unless (not org-custom-properties)
6375 (save-excursion
6376 (save-restriction
6377 (widen)
6378 (goto-char (point-min))
6379 (while (re-search-forward org-property-re nil t)
6380 (mapc (lambda(p)
6381 (when (equal p (substring (match-string 1) 1 -1))
6382 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6383 (overlay-put o 'invisible t)
6384 (overlay-put o 'org-custom-property t)
6385 (push o org-custom-properties-overlays))))
6386 org-custom-properties)))))))
6388 (defun org-fontify-entities (limit)
6389 "Find an entity to fontify."
6390 (let (ee)
6391 (when org-pretty-entities
6392 (catch 'match
6393 (while (re-search-forward
6394 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6395 limit t)
6396 (if (and (not (org-in-indented-comment-line))
6397 (setq ee (org-entity-get (match-string 1)))
6398 (= (length (nth 6 ee)) 1))
6399 (let*
6400 ((end (if (equal (match-string 2) "{}")
6401 (match-end 2)
6402 (match-end 1))))
6403 (add-text-properties
6404 (match-beginning 0) end
6405 (list 'font-lock-fontified t))
6406 (compose-region (match-beginning 0) end
6407 (nth 6 ee) nil)
6408 (backward-char 1)
6409 (throw 'match t))))
6410 nil))))
6412 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6413 "Fontify string S like in Org-mode."
6414 (with-temp-buffer
6415 (insert s)
6416 (let ((org-odd-levels-only odd-levels))
6417 (org-mode)
6418 (font-lock-fontify-buffer)
6419 (buffer-string))))
6421 (defvar org-m nil)
6422 (defvar org-l nil)
6423 (defvar org-f nil)
6424 (defun org-get-level-face (n)
6425 "Get the right face for match N in font-lock matching of headlines."
6426 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6427 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6428 (if org-cycle-level-faces
6429 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6430 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6431 (cond
6432 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6433 ((eq n 2) org-f)
6434 (t (if org-level-color-stars-only nil org-f))))
6437 (defun org-get-todo-face (kwd)
6438 "Get the right face for a TODO keyword KWD.
6439 If KWD is a number, get the corresponding match group."
6440 (if (numberp kwd) (setq kwd (match-string kwd)))
6441 (or (org-face-from-face-or-color
6442 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6443 (and (member kwd org-done-keywords) 'org-done)
6444 'org-todo))
6446 (defun org-face-from-face-or-color (context inherit face-or-color)
6447 "Create a face list that inherits INHERIT, but sets the foreground color.
6448 When FACE-OR-COLOR is not a string, just return it."
6449 (if (stringp face-or-color)
6450 (list :inherit inherit
6451 (cdr (assoc context org-faces-easy-properties))
6452 face-or-color)
6453 face-or-color))
6455 (defun org-font-lock-add-tag-faces (limit)
6456 "Add the special tag faces."
6457 (when (and org-tag-faces org-tags-special-faces-re)
6458 (while (re-search-forward org-tags-special-faces-re limit t)
6459 (add-text-properties (match-beginning 1) (match-end 1)
6460 (list 'face (org-get-tag-face 1)
6461 'font-lock-fontified t))
6462 (backward-char 1))))
6464 (defun org-font-lock-add-priority-faces (limit)
6465 "Add the special priority faces."
6466 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6467 (when (save-match-data (org-at-heading-p))
6468 (add-text-properties
6469 (match-beginning 0) (match-end 0)
6470 (list 'face (or (org-face-from-face-or-color
6471 'priority 'org-priority
6472 (cdr (assoc (char-after (match-beginning 1))
6473 org-priority-faces)))
6474 'org-priority)
6475 'font-lock-fontified t)))))
6477 (defun org-get-tag-face (kwd)
6478 "Get the right face for a TODO keyword KWD.
6479 If KWD is a number, get the corresponding match group."
6480 (if (numberp kwd) (setq kwd (match-string kwd)))
6481 (or (org-face-from-face-or-color
6482 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6483 'org-tag))
6485 (defun org-unfontify-region (beg end &optional maybe_loudly)
6486 "Remove fontification and activation overlays from links."
6487 (font-lock-default-unfontify-region beg end)
6488 (let* ((buffer-undo-list t)
6489 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6490 (inhibit-modification-hooks t)
6491 deactivate-mark buffer-file-name buffer-file-truename)
6492 (org-decompose-region beg end)
6493 (remove-text-properties beg end
6494 '(mouse-face t keymap t org-linked-text t
6495 invisible t intangible t
6496 org-emphasis t))
6497 (org-remove-font-lock-display-properties beg end)))
6499 (defconst org-script-display '(((raise -0.3) (height 0.7))
6500 ((raise 0.3) (height 0.7))
6501 ((raise -0.5))
6502 ((raise 0.5)))
6503 "Display properties for showing superscripts and subscripts.")
6505 (defun org-remove-font-lock-display-properties (beg end)
6506 "Remove specific display properties that have been added by font lock.
6507 The will remove the raise properties that are used to show superscripts
6508 and subscripts."
6509 (let (next prop)
6510 (while (< beg end)
6511 (setq next (next-single-property-change beg 'display nil end)
6512 prop (get-text-property beg 'display))
6513 (if (member prop org-script-display)
6514 (put-text-property beg next 'display nil))
6515 (setq beg next))))
6517 (defun org-raise-scripts (limit)
6518 "Add raise properties to sub/superscripts."
6519 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6520 (if (re-search-forward
6521 (if (eq org-use-sub-superscripts t)
6522 org-match-substring-regexp
6523 org-match-substring-with-braces-regexp)
6524 limit t)
6525 (let* ((pos (point)) table-p comment-p
6526 (mpos (match-beginning 3))
6527 (emph-p (get-text-property mpos 'org-emphasis))
6528 (link-p (get-text-property mpos 'mouse-face))
6529 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6530 (goto-char (point-at-bol))
6531 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6532 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6533 (goto-char pos)
6534 ;; Handle a_b^c
6535 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6536 (if (or comment-p emph-p link-p keyw-p)
6538 (put-text-property (match-beginning 3) (match-end 0)
6539 'display
6540 (if (equal (char-after (match-beginning 2)) ?^)
6541 (nth (if table-p 3 1) org-script-display)
6542 (nth (if table-p 2 0) org-script-display)))
6543 (add-text-properties (match-beginning 2) (match-end 2)
6544 (list 'invisible t
6545 'org-dwidth t 'org-dwidth-n 1))
6546 (if (and (eq (char-after (match-beginning 3)) ?{)
6547 (eq (char-before (match-end 3)) ?}))
6548 (progn
6549 (add-text-properties
6550 (match-beginning 3) (1+ (match-beginning 3))
6551 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6552 (add-text-properties
6553 (1- (match-end 3)) (match-end 3)
6554 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6555 t)))))
6557 ;;;; Visibility cycling, including org-goto and indirect buffer
6559 ;;; Cycling
6561 (defvar org-cycle-global-status nil)
6562 (make-variable-buffer-local 'org-cycle-global-status)
6563 (put 'org-cycle-global-status 'org-state t)
6564 (defvar org-cycle-subtree-status nil)
6565 (make-variable-buffer-local 'org-cycle-subtree-status)
6566 (put 'org-cycle-subtree-status 'org-state t)
6568 (defvar org-inlinetask-min-level)
6570 (defun org-unlogged-message (&rest args)
6571 "Display a message, but avoid logging it in the *Messages* buffer."
6572 (let ((message-log-max nil))
6573 (apply 'message args)))
6575 ;;;###autoload
6576 (defun org-cycle (&optional arg)
6577 "TAB-action and visibility cycling for Org-mode.
6579 This is the command invoked in Org-mode by the TAB key. Its main purpose
6580 is outline visibility cycling, but it also invokes other actions
6581 in special contexts.
6583 - When this function is called with a prefix argument, rotate the entire
6584 buffer through 3 states (global cycling)
6585 1. OVERVIEW: Show only top-level headlines.
6586 2. CONTENTS: Show all headlines of all levels, but no body text.
6587 3. SHOW ALL: Show everything.
6588 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6589 determined by the variable `org-startup-folded', and by any VISIBILITY
6590 properties in the buffer.
6591 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6592 including any drawers.
6594 - When inside a table, re-align the table and move to the next field.
6596 - When point is at the beginning of a headline, rotate the subtree started
6597 by this line through 3 different states (local cycling)
6598 1. FOLDED: Only the main headline is shown.
6599 2. CHILDREN: The main headline and the direct children are shown.
6600 From this state, you can move to one of the children
6601 and zoom in further.
6602 3. SUBTREE: Show the entire subtree, including body text.
6603 If there is no subtree, switch directly from CHILDREN to FOLDED.
6605 - When point is at the beginning of an empty headline and the variable
6606 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6607 of the headline by demoting and promoting it to likely levels. This
6608 speeds up creation document structure by pressing TAB once or several
6609 times right after creating a new headline.
6611 - When there is a numeric prefix, go up to a heading with level ARG, do
6612 a `show-subtree' and return to the previous cursor position. If ARG
6613 is negative, go up that many levels.
6615 - When point is not at the beginning of a headline, execute the global
6616 binding for TAB, which is re-indenting the line. See the option
6617 `org-cycle-emulate-tab' for details.
6619 - Special case: if point is at the beginning of the buffer and there is
6620 no headline in line 1, this function will act as if called with prefix arg
6621 (C-u TAB, same as S-TAB) also when called without prefix arg.
6622 But only if also the variable `org-cycle-global-at-bob' is t."
6623 (interactive "P")
6624 (org-load-modules-maybe)
6625 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6626 (and org-cycle-level-after-item/entry-creation
6627 (or (org-cycle-level)
6628 (org-cycle-item-indentation))))
6629 (let* ((limit-level
6630 (or org-cycle-max-level
6631 (and (boundp 'org-inlinetask-min-level)
6632 org-inlinetask-min-level
6633 (1- org-inlinetask-min-level))))
6634 (nstars (and limit-level
6635 (if org-odd-levels-only
6636 (and limit-level (1- (* limit-level 2)))
6637 limit-level)))
6638 (org-outline-regexp
6639 (if (not (derived-mode-p 'org-mode))
6640 outline-regexp
6641 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6642 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6643 (not (looking-at org-outline-regexp))))
6644 (org-cycle-hook
6645 (if bob-special
6646 (delq 'org-optimize-window-after-visibility-change
6647 (copy-sequence org-cycle-hook))
6648 org-cycle-hook))
6649 (pos (point)))
6651 (if (or bob-special (equal arg '(4)))
6652 ;; special case: use global cycling
6653 (setq arg t))
6655 (cond
6657 ((equal arg '(16))
6658 (setq last-command 'dummy)
6659 (org-set-startup-visibility)
6660 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6662 ((equal arg '(64))
6663 (show-all)
6664 (org-unlogged-message "Entire buffer visible, including drawers"))
6666 ;; Table: enter it or move to the next field.
6667 ((org-at-table-p 'any)
6668 (if (org-at-table.el-p)
6669 (message "Use C-c ' to edit table.el tables")
6670 (if arg (org-table-edit-field t)
6671 (org-table-justify-field-maybe)
6672 (call-interactively 'org-table-next-field))))
6674 ((run-hook-with-args-until-success
6675 'org-tab-after-check-for-table-hook))
6677 ;; Global cycling: delegate to `org-cycle-internal-global'.
6678 ((eq arg t) (org-cycle-internal-global))
6680 ;; Drawers: delegate to `org-flag-drawer'.
6681 ((save-excursion
6682 (beginning-of-line 1)
6683 (looking-at org-drawer-regexp))
6684 (org-flag-drawer ; toggle block visibility
6685 (not (get-char-property (match-end 0) 'invisible))))
6687 ;; Show-subtree, ARG levels up from here.
6688 ((integerp arg)
6689 (save-excursion
6690 (org-back-to-heading)
6691 (outline-up-heading (if (< arg 0) (- arg)
6692 (- (funcall outline-level) arg)))
6693 (org-show-subtree)))
6695 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6696 ((and (featurep 'org-inlinetask)
6697 (org-inlinetask-at-task-p)
6698 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6699 (org-inlinetask-toggle-visibility))
6701 ((org-try-cdlatex-tab))
6703 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6704 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6705 (save-excursion (beginning-of-line 1)
6706 (looking-at org-outline-regexp)))
6707 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6708 (org-cycle-internal-local))
6710 ;; From there: TAB emulation and template completion.
6711 (buffer-read-only (org-back-to-heading))
6713 ((run-hook-with-args-until-success
6714 'org-tab-after-check-for-cycling-hook))
6716 ((org-try-structure-completion))
6718 ((run-hook-with-args-until-success
6719 'org-tab-before-tab-emulation-hook))
6721 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6722 (or (not (bolp))
6723 (not (looking-at org-outline-regexp))))
6724 (call-interactively (global-key-binding "\t")))
6726 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6727 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6728 (or (and (eq org-cycle-emulate-tab 'white)
6729 (= (match-end 0) (point-at-eol)))
6730 (and (eq org-cycle-emulate-tab 'whitestart)
6731 (>= (match-end 0) pos))))
6733 (eq org-cycle-emulate-tab t))
6734 (call-interactively (global-key-binding "\t")))
6736 (t (save-excursion
6737 (org-back-to-heading)
6738 (org-cycle)))))))
6740 (defun org-cycle-internal-global ()
6741 "Do the global cycling action."
6742 ;; Hack to avoid display of messages for .org attachments in Gnus
6743 (let ((ga (string-match "\\*fontification" (buffer-name))))
6744 (cond
6745 ((and (eq last-command this-command)
6746 (eq org-cycle-global-status 'overview))
6747 ;; We just created the overview - now do table of contents
6748 ;; This can be slow in very large buffers, so indicate action
6749 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6750 (unless ga (org-unlogged-message "CONTENTS..."))
6751 (org-content)
6752 (unless ga (org-unlogged-message "CONTENTS...done"))
6753 (setq org-cycle-global-status 'contents)
6754 (run-hook-with-args 'org-cycle-hook 'contents))
6756 ((and (eq last-command this-command)
6757 (eq org-cycle-global-status 'contents))
6758 ;; We just showed the table of contents - now show everything
6759 (run-hook-with-args 'org-pre-cycle-hook 'all)
6760 (show-all)
6761 (unless ga (org-unlogged-message "SHOW ALL"))
6762 (setq org-cycle-global-status 'all)
6763 (run-hook-with-args 'org-cycle-hook 'all))
6766 ;; Default action: go to overview
6767 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6768 (org-overview)
6769 (unless ga (org-unlogged-message "OVERVIEW"))
6770 (setq org-cycle-global-status 'overview)
6771 (run-hook-with-args 'org-cycle-hook 'overview)))))
6773 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6775 (defun org-cycle-internal-local ()
6776 "Do the local cycling action."
6777 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6778 ;; First, determine end of headline (EOH), end of subtree or item
6779 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6780 (save-excursion
6781 (if (org-at-item-p)
6782 (progn
6783 (beginning-of-line)
6784 (setq struct (org-list-struct))
6785 (setq eoh (point-at-eol))
6786 (setq eos (org-list-get-item-end-before-blank (point) struct))
6787 (setq has-children (org-list-has-child-p (point) struct)))
6788 (org-back-to-heading)
6789 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6790 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6791 (setq has-children
6792 (or (save-excursion
6793 (let ((level (funcall outline-level)))
6794 (outline-next-heading)
6795 (and (org-at-heading-p t)
6796 (> (funcall outline-level) level))))
6797 (save-excursion
6798 (org-list-search-forward (org-item-beginning-re) eos t)))))
6799 ;; Determine end invisible part of buffer (EOL)
6800 (beginning-of-line 2)
6801 ;; XEmacs doesn't have `next-single-char-property-change'
6802 (if (featurep 'xemacs)
6803 (while (and (not (eobp)) ;; this is like `next-line'
6804 (get-char-property (1- (point)) 'invisible))
6805 (beginning-of-line 2))
6806 (while (and (not (eobp)) ;; this is like `next-line'
6807 (get-char-property (1- (point)) 'invisible))
6808 (goto-char (next-single-char-property-change (point) 'invisible))
6809 (and (eolp) (beginning-of-line 2))))
6810 (setq eol (point)))
6811 ;; Find out what to do next and set `this-command'
6812 (cond
6813 ((= eos eoh)
6814 ;; Nothing is hidden behind this heading
6815 (unless (org-before-first-heading-p)
6816 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6817 (org-unlogged-message "EMPTY ENTRY")
6818 (setq org-cycle-subtree-status nil)
6819 (save-excursion
6820 (goto-char eos)
6821 (outline-next-heading)
6822 (if (outline-invisible-p) (org-flag-heading nil))))
6823 ((and (or (>= eol eos)
6824 (not (string-match "\\S-" (buffer-substring eol eos))))
6825 (or has-children
6826 (not (setq children-skipped
6827 org-cycle-skip-children-state-if-no-children))))
6828 ;; Entire subtree is hidden in one line: children view
6829 (unless (org-before-first-heading-p)
6830 (run-hook-with-args 'org-pre-cycle-hook 'children))
6831 (if (org-at-item-p)
6832 (org-list-set-item-visibility (point-at-bol) struct 'children)
6833 (org-show-entry)
6834 (org-with-limited-levels (show-children))
6835 ;; FIXME: This slows down the func way too much.
6836 ;; How keep drawers hidden in subtree anyway?
6837 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6838 ;; (org-cycle-hide-drawers 'subtree))
6840 ;; Fold every list in subtree to top-level items.
6841 (when (eq org-cycle-include-plain-lists 'integrate)
6842 (save-excursion
6843 (org-back-to-heading)
6844 (while (org-list-search-forward (org-item-beginning-re) eos t)
6845 (beginning-of-line 1)
6846 (let* ((struct (org-list-struct))
6847 (prevs (org-list-prevs-alist struct))
6848 (end (org-list-get-bottom-point struct)))
6849 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6850 (org-list-get-all-items (point) struct prevs))
6851 (goto-char (if (< end eos) end eos)))))))
6852 (org-unlogged-message "CHILDREN")
6853 (save-excursion
6854 (goto-char eos)
6855 (outline-next-heading)
6856 (if (outline-invisible-p) (org-flag-heading nil)))
6857 (setq org-cycle-subtree-status 'children)
6858 (unless (org-before-first-heading-p)
6859 (run-hook-with-args 'org-cycle-hook 'children)))
6860 ((or children-skipped
6861 (and (eq last-command this-command)
6862 (eq org-cycle-subtree-status 'children)))
6863 ;; We just showed the children, or no children are there,
6864 ;; now show everything.
6865 (unless (org-before-first-heading-p)
6866 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6867 (outline-flag-region eoh eos nil)
6868 (org-unlogged-message
6869 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6870 (setq org-cycle-subtree-status 'subtree)
6871 (unless (org-before-first-heading-p)
6872 (run-hook-with-args 'org-cycle-hook 'subtree)))
6874 ;; Default action: hide the subtree.
6875 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6876 (outline-flag-region eoh eos t)
6877 (org-unlogged-message "FOLDED")
6878 (setq org-cycle-subtree-status 'folded)
6879 (unless (org-before-first-heading-p)
6880 (run-hook-with-args 'org-cycle-hook 'folded))))))
6882 ;;;###autoload
6883 (defun org-global-cycle (&optional arg)
6884 "Cycle the global visibility. For details see `org-cycle'.
6885 With \\[universal-argument] prefix arg, switch to startup visibility.
6886 With a numeric prefix, show all headlines up to that level."
6887 (interactive "P")
6888 (let ((org-cycle-include-plain-lists
6889 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6890 (cond
6891 ((integerp arg)
6892 (show-all)
6893 (hide-sublevels arg)
6894 (setq org-cycle-global-status 'contents))
6895 ((equal arg '(4))
6896 (org-set-startup-visibility)
6897 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6899 (org-cycle '(4))))))
6901 (defun org-set-startup-visibility ()
6902 "Set the visibility required by startup options and properties."
6903 (cond
6904 ((eq org-startup-folded t)
6905 (org-overview))
6906 ((eq org-startup-folded 'content)
6907 (org-content))
6908 ((or (eq org-startup-folded 'showeverything)
6909 (eq org-startup-folded nil))
6910 (show-all)))
6911 (unless (eq org-startup-folded 'showeverything)
6912 (if org-hide-block-startup (org-hide-block-all))
6913 (org-set-visibility-according-to-property 'no-cleanup)
6914 (org-cycle-hide-archived-subtrees 'all)
6915 (org-cycle-hide-drawers 'all)
6916 (org-cycle-show-empty-lines t)))
6918 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6919 "Switch subtree visibilities according to :VISIBILITY: property."
6920 (interactive)
6921 (let (org-show-entry-below state)
6922 (save-excursion
6923 (goto-char (point-min))
6924 (while (re-search-forward
6925 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6926 nil t)
6927 (setq state (match-string 1))
6928 (save-excursion
6929 (org-back-to-heading t)
6930 (hide-subtree)
6931 (org-reveal)
6932 (cond
6933 ((equal state '("fold" "folded"))
6934 (hide-subtree))
6935 ((equal state "children")
6936 (org-show-hidden-entry)
6937 (show-children))
6938 ((equal state "content")
6939 (save-excursion
6940 (save-restriction
6941 (org-narrow-to-subtree)
6942 (org-content))))
6943 ((member state '("all" "showall"))
6944 (show-subtree)))))
6945 (unless no-cleanup
6946 (org-cycle-hide-archived-subtrees 'all)
6947 (org-cycle-hide-drawers 'all)
6948 (org-cycle-show-empty-lines 'all)))))
6950 ;; This function uses outline-regexp instead of the more fundamental
6951 ;; org-outline-regexp so that org-cycle-global works outside of Org
6952 ;; buffers, where outline-regexp is needed.
6953 (defun org-overview ()
6954 "Switch to overview mode, showing only top-level headlines.
6955 Really, this shows all headlines with level equal or greater than the level
6956 of the first headline in the buffer. This is important, because if the
6957 first headline is not level one, then (hide-sublevels 1) gives confusing
6958 results."
6959 (interactive)
6960 (let ((pos (point))
6961 (level (save-excursion
6962 (goto-char (point-min))
6963 (if (re-search-forward (concat "^" outline-regexp) nil t)
6964 (progn
6965 (goto-char (match-beginning 0))
6966 (funcall outline-level))))))
6967 (and level (hide-sublevels level))
6968 (recenter '(4))
6969 (goto-char pos)))
6971 (defun org-content (&optional arg)
6972 "Show all headlines in the buffer, like a table of contents.
6973 With numerical argument N, show content up to level N."
6974 (interactive "P")
6975 (org-overview)
6976 (save-excursion
6977 ;; Visit all headings and show their offspring
6978 (and (integerp arg) (org-overview))
6979 (goto-char (point-max))
6980 (catch 'exit
6981 (while (and (progn (condition-case nil
6982 (outline-previous-visible-heading 1)
6983 (error (goto-char (point-min))))
6985 (looking-at org-outline-regexp))
6986 (if (integerp arg)
6987 (show-children (1- arg))
6988 (show-branches))
6989 (if (bobp) (throw 'exit nil))))))
6991 (defun org-optimize-window-after-visibility-change (state)
6992 "Adjust the window after a change in outline visibility.
6993 This function is the default value of the hook `org-cycle-hook'."
6994 (when (get-buffer-window (current-buffer))
6995 (cond
6996 ((eq state 'content) nil)
6997 ((eq state 'all) nil)
6998 ((eq state 'folded) nil)
6999 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7000 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7002 (defun org-remove-empty-overlays-at (pos)
7003 "Remove outline overlays that do not contain non-white stuff."
7004 (mapc
7005 (lambda (o)
7006 (and (eq 'outline (overlay-get o 'invisible))
7007 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7008 (overlay-end o))))
7009 (delete-overlay o)))
7010 (overlays-at pos)))
7012 (defun org-clean-visibility-after-subtree-move ()
7013 "Fix visibility issues after moving a subtree."
7014 ;; First, find a reasonable region to look at:
7015 ;; Start two siblings above, end three below
7016 (let* ((beg (save-excursion
7017 (and (org-get-last-sibling)
7018 (org-get-last-sibling))
7019 (point)))
7020 (end (save-excursion
7021 (and (org-get-next-sibling)
7022 (org-get-next-sibling)
7023 (org-get-next-sibling))
7024 (if (org-at-heading-p)
7025 (point-at-eol)
7026 (point))))
7027 (level (looking-at "\\*+"))
7028 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7029 (save-excursion
7030 (save-restriction
7031 (narrow-to-region beg end)
7032 (when re
7033 ;; Properly fold already folded siblings
7034 (goto-char (point-min))
7035 (while (re-search-forward re nil t)
7036 (if (and (not (outline-invisible-p))
7037 (save-excursion
7038 (goto-char (point-at-eol)) (outline-invisible-p)))
7039 (hide-entry))))
7040 (org-cycle-show-empty-lines 'overview)
7041 (org-cycle-hide-drawers 'overview)))))
7043 (defun org-cycle-show-empty-lines (state)
7044 "Show empty lines above all visible headlines.
7045 The region to be covered depends on STATE when called through
7046 `org-cycle-hook'. Lisp program can use t for STATE to get the
7047 entire buffer covered. Note that an empty line is only shown if there
7048 are at least `org-cycle-separator-lines' empty lines before the headline."
7049 (when (not (= org-cycle-separator-lines 0))
7050 (save-excursion
7051 (let* ((n (abs org-cycle-separator-lines))
7052 (re (cond
7053 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7054 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7055 (t (let ((ns (number-to-string (- n 2))))
7056 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7057 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7058 beg end b e)
7059 (cond
7060 ((memq state '(overview contents t))
7061 (setq beg (point-min) end (point-max)))
7062 ((memq state '(children folded))
7063 (setq beg (point) end (progn (org-end-of-subtree t t)
7064 (beginning-of-line 2)
7065 (point)))))
7066 (when beg
7067 (goto-char beg)
7068 (while (re-search-forward re end t)
7069 (unless (get-char-property (match-end 1) 'invisible)
7070 (setq e (match-end 1))
7071 (if (< org-cycle-separator-lines 0)
7072 (setq b (save-excursion
7073 (goto-char (match-beginning 0))
7074 (org-back-over-empty-lines)
7075 (if (save-excursion
7076 (goto-char (max (point-min) (1- (point))))
7077 (org-at-heading-p))
7078 (1- (point))
7079 (point))))
7080 (setq b (match-beginning 1)))
7081 (outline-flag-region b e nil)))))))
7082 ;; Never hide empty lines at the end of the file.
7083 (save-excursion
7084 (goto-char (point-max))
7085 (outline-previous-heading)
7086 (outline-end-of-heading)
7087 (if (and (looking-at "[ \t\n]+")
7088 (= (match-end 0) (point-max)))
7089 (outline-flag-region (point) (match-end 0) nil))))
7091 (defun org-show-empty-lines-in-parent ()
7092 "Move to the parent and re-show empty lines before visible headlines."
7093 (save-excursion
7094 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7095 (org-cycle-show-empty-lines context))))
7097 (defun org-files-list ()
7098 "Return `org-agenda-files' list, plus all open org-mode files.
7099 This is useful for operations that need to scan all of a user's
7100 open and agenda-wise Org files."
7101 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7102 (dolist (buf (buffer-list))
7103 (with-current-buffer buf
7104 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7105 (let ((file (expand-file-name (buffer-file-name))))
7106 (unless (member file files)
7107 (push file files))))))
7108 files))
7110 (defsubst org-entry-beginning-position ()
7111 "Return the beginning position of the current entry."
7112 (save-excursion (outline-back-to-heading t) (point)))
7114 (defsubst org-entry-end-position ()
7115 "Return the end position of the current entry."
7116 (save-excursion (outline-next-heading) (point)))
7118 (defun org-cycle-hide-drawers (state &optional exceptions)
7119 "Re-hide all drawers after a visibility state change.
7120 When non-nil, optional argument EXCEPTIONS is a list of strings
7121 specifying which drawers should not be hidden."
7122 (when (and (derived-mode-p 'org-mode)
7123 (not (memq state '(overview folded contents))))
7124 (save-excursion
7125 (let* ((globalp (memq state '(contents all)))
7126 (beg (if globalp (point-min) (point)))
7127 (end (if globalp (point-max)
7128 (if (eq state 'children)
7129 (save-excursion (outline-next-heading) (point))
7130 (org-end-of-subtree t)))))
7131 (goto-char beg)
7132 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7133 (unless (member-ignore-case (match-string 1) exceptions)
7134 (let ((drawer (org-element-at-point)))
7135 (when (memq (org-element-type drawer) '(drawer property-drawer))
7136 (org-flag-drawer t drawer)
7137 ;; Make sure to skip drawer entirely or we might flag
7138 ;; it another time when matching its ending line with
7139 ;; `org-drawer-regexp'.
7140 (goto-char (org-element-property :end drawer))))))))))
7142 (defun org-cycle-hide-inline-tasks (state)
7143 "Re-hide inline tasks when switching to 'contents or 'children
7144 visibility state."
7145 (case state
7146 (contents
7147 (when (org-bound-and-true-p org-inlinetask-min-level)
7148 (hide-sublevels (1- org-inlinetask-min-level))))
7149 (children
7150 (when (featurep 'org-inlinetask)
7151 (save-excursion
7152 (while (and (outline-next-heading)
7153 (org-inlinetask-at-task-p))
7154 (org-inlinetask-toggle-visibility)
7155 (org-inlinetask-goto-end)))))))
7157 (defun org-flag-drawer (flag &optional element)
7158 "When FLAG is non-nil, hide the drawer we are at.
7159 Otherwise make it visible. When optional argument ELEMENT is
7160 a parsed drawer, as returned by `org-element-at-point', hide or
7161 show that drawer instead."
7162 (let ((drawer (or element (org-element-at-point))))
7163 (when (memq (org-element-type drawer) '(drawer property-drawer))
7164 (save-excursion
7165 (goto-char (org-element-property :post-affiliated drawer))
7166 (outline-flag-region
7167 (line-end-position)
7168 (progn (goto-char (org-element-property :end drawer))
7169 (skip-chars-backward " \r\t\n")
7170 (line-end-position))
7171 flag)))))
7173 (defun org-subtree-end-visible-p ()
7174 "Is the end of the current subtree visible?"
7175 (pos-visible-in-window-p
7176 (save-excursion (org-end-of-subtree t) (point))))
7178 (defun org-first-headline-recenter (&optional N)
7179 "Move cursor to the first headline and recenter the headline.
7180 Optional argument N means put the headline into the Nth line of the window."
7181 (goto-char (point-min))
7182 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7183 (beginning-of-line)
7184 (recenter (prefix-numeric-value N))))
7186 ;;; Saving and restoring visibility
7188 (defun org-outline-overlay-data (&optional use-markers)
7189 "Return a list of the locations of all outline overlays.
7190 These are overlays with the `invisible' property value `outline'.
7191 The return value is a list of cons cells, with start and stop
7192 positions for each overlay.
7193 If USE-MARKERS is set, return the positions as markers."
7194 (let (beg end)
7195 (save-excursion
7196 (save-restriction
7197 (widen)
7198 (delq nil
7199 (mapcar (lambda (o)
7200 (when (eq (overlay-get o 'invisible) 'outline)
7201 (setq beg (overlay-start o)
7202 end (overlay-end o))
7203 (and beg end (> end beg)
7204 (if use-markers
7205 (cons (copy-marker beg)
7206 (copy-marker end t))
7207 (cons beg end)))))
7208 (overlays-in (point-min) (point-max))))))))
7210 (defun org-set-outline-overlay-data (data)
7211 "Create visibility overlays for all positions in DATA.
7212 DATA should have been made by `org-outline-overlay-data'."
7213 (let (o)
7214 (save-excursion
7215 (save-restriction
7216 (widen)
7217 (show-all)
7218 (mapc (lambda (c)
7219 (outline-flag-region (car c) (cdr c) t))
7220 data)))))
7222 ;;; Folding of blocks
7224 (defvar org-hide-block-overlays nil
7225 "Overlays hiding blocks.")
7226 (make-variable-buffer-local 'org-hide-block-overlays)
7228 (defun org-block-map (function &optional start end)
7229 "Call FUNCTION at the head of all source blocks in the current buffer.
7230 Optional arguments START and END can be used to limit the range."
7231 (let ((start (or start (point-min)))
7232 (end (or end (point-max))))
7233 (save-excursion
7234 (goto-char start)
7235 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7236 (save-excursion
7237 (save-match-data
7238 (goto-char (match-beginning 0))
7239 (funcall function)))))))
7241 (defun org-hide-block-toggle-all ()
7242 "Toggle the visibility of all blocks in the current buffer."
7243 (org-block-map #'org-hide-block-toggle))
7245 (defun org-hide-block-all ()
7246 "Fold all blocks in the current buffer."
7247 (interactive)
7248 (org-show-block-all)
7249 (org-block-map #'org-hide-block-toggle-maybe))
7251 (defun org-show-block-all ()
7252 "Unfold all blocks in the current buffer."
7253 (interactive)
7254 (mapc 'delete-overlay org-hide-block-overlays)
7255 (setq org-hide-block-overlays nil))
7257 (defun org-hide-block-toggle-maybe ()
7258 "Toggle visibility of block at point."
7259 (interactive)
7260 (let ((case-fold-search t))
7261 (if (save-excursion
7262 (beginning-of-line 1)
7263 (looking-at org-block-regexp))
7264 (progn (org-hide-block-toggle)
7265 t) ;; to signal that we took action
7266 nil))) ;; to signal that we did not
7268 (defun org-hide-block-toggle (&optional force)
7269 "Toggle the visibility of the current block."
7270 (interactive)
7271 (save-excursion
7272 (beginning-of-line)
7273 (if (re-search-forward org-block-regexp nil t)
7274 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7275 (end (match-end 0)) ;; end of entire body
7277 (if (memq t (mapcar (lambda (overlay)
7278 (eq (overlay-get overlay 'invisible)
7279 'org-hide-block))
7280 (overlays-at start)))
7281 (if (or (not force) (eq force 'off))
7282 (mapc (lambda (ov)
7283 (when (member ov org-hide-block-overlays)
7284 (setq org-hide-block-overlays
7285 (delq ov org-hide-block-overlays)))
7286 (when (eq (overlay-get ov 'invisible)
7287 'org-hide-block)
7288 (delete-overlay ov)))
7289 (overlays-at start)))
7290 (setq ov (make-overlay start end))
7291 (overlay-put ov 'invisible 'org-hide-block)
7292 ;; make the block accessible to isearch
7293 (overlay-put
7294 ov 'isearch-open-invisible
7295 (lambda (ov)
7296 (when (member ov org-hide-block-overlays)
7297 (setq org-hide-block-overlays
7298 (delq ov org-hide-block-overlays)))
7299 (when (eq (overlay-get ov 'invisible)
7300 'org-hide-block)
7301 (delete-overlay ov))))
7302 (push ov org-hide-block-overlays)))
7303 (user-error "Not looking at a source block"))))
7305 ;; org-tab-after-check-for-cycling-hook
7306 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7307 ;; Remove overlays when changing major mode
7308 (add-hook 'org-mode-hook
7309 (lambda () (org-add-hook 'change-major-mode-hook
7310 'org-show-block-all 'append 'local)))
7312 ;;; Org-goto
7314 (defvar org-goto-window-configuration nil)
7315 (defvar org-goto-marker nil)
7316 (defvar org-goto-map)
7317 (defun org-goto-map ()
7318 "Set the keymap `org-goto'."
7319 (setq org-goto-map
7320 (let ((map (make-sparse-keymap)))
7321 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7322 mouse-drag-region universal-argument org-occur))
7323 cmd)
7324 (while (setq cmd (pop cmds))
7325 (substitute-key-definition cmd cmd map global-map)))
7326 (suppress-keymap map)
7327 (org-defkey map "\C-m" 'org-goto-ret)
7328 (org-defkey map [(return)] 'org-goto-ret)
7329 (org-defkey map [(left)] 'org-goto-left)
7330 (org-defkey map [(right)] 'org-goto-right)
7331 (org-defkey map [(control ?g)] 'org-goto-quit)
7332 (org-defkey map "\C-i" 'org-cycle)
7333 (org-defkey map [(tab)] 'org-cycle)
7334 (org-defkey map [(down)] 'outline-next-visible-heading)
7335 (org-defkey map [(up)] 'outline-previous-visible-heading)
7336 (if org-goto-auto-isearch
7337 (if (fboundp 'define-key-after)
7338 (define-key-after map [t] 'org-goto-local-auto-isearch)
7339 nil)
7340 (org-defkey map "q" 'org-goto-quit)
7341 (org-defkey map "n" 'outline-next-visible-heading)
7342 (org-defkey map "p" 'outline-previous-visible-heading)
7343 (org-defkey map "f" 'outline-forward-same-level)
7344 (org-defkey map "b" 'outline-backward-same-level)
7345 (org-defkey map "u" 'outline-up-heading))
7346 (org-defkey map "/" 'org-occur)
7347 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7348 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7349 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7350 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7351 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7352 map)))
7354 (defconst org-goto-help
7355 "Browse buffer copy, to find location or copy text.%s
7356 RET=jump to location C-g=quit and return to previous location
7357 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7359 (defvar org-goto-start-pos) ; dynamically scoped parameter
7361 (defun org-goto (&optional alternative-interface)
7362 "Look up a different location in the current file, keeping current visibility.
7364 When you want look-up or go to a different location in a
7365 document, the fastest way is often to fold the entire buffer and
7366 then dive into the tree. This method has the disadvantage, that
7367 the previous location will be folded, which may not be what you
7368 want.
7370 This command works around this by showing a copy of the current
7371 buffer in an indirect buffer, in overview mode. You can dive
7372 into the tree in that copy, use org-occur and incremental search
7373 to find a location. When pressing RET or `Q', the command
7374 returns to the original buffer in which the visibility is still
7375 unchanged. After RET it will also jump to the location selected
7376 in the indirect buffer and expose the headline hierarchy above.
7378 With a prefix argument, use the alternative interface: e.g. if
7379 `org-goto-interface' is 'outline use 'outline-path-completion."
7380 (interactive "P")
7381 (org-goto-map)
7382 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7383 (org-refile-use-outline-path t)
7384 (org-refile-target-verify-function nil)
7385 (interface
7386 (if (not alternative-interface)
7387 org-goto-interface
7388 (if (eq org-goto-interface 'outline)
7389 'outline-path-completion
7390 'outline)))
7391 (org-goto-start-pos (point))
7392 (selected-point
7393 (if (eq interface 'outline)
7394 (car (org-get-location (current-buffer) org-goto-help))
7395 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7396 (org-refile-check-position pa)
7397 (nth 3 pa)))))
7398 (if selected-point
7399 (progn
7400 (org-mark-ring-push org-goto-start-pos)
7401 (goto-char selected-point)
7402 (if (or (outline-invisible-p) (org-invisible-p2))
7403 (org-show-context 'org-goto)))
7404 (message "Quit"))))
7406 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7407 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7408 (defvar org-goto-local-auto-isearch-map) ; defined below
7410 (defun org-get-location (buf help)
7411 "Let the user select a location in the Org-mode buffer BUF.
7412 This function uses a recursive edit. It returns the selected position
7413 or nil."
7414 (org-no-popups
7415 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7416 (isearch-hide-immediately nil)
7417 (isearch-search-fun-function
7418 (lambda () 'org-goto-local-search-headings))
7419 (org-goto-selected-point org-goto-exit-command))
7420 (save-excursion
7421 (save-window-excursion
7422 (delete-other-windows)
7423 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7424 (org-pop-to-buffer-same-window
7425 (condition-case nil
7426 (make-indirect-buffer (current-buffer) "*org-goto*")
7427 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7428 (with-output-to-temp-buffer "*Org Help*"
7429 (princ (format help (if org-goto-auto-isearch
7430 " Just type for auto-isearch."
7431 " n/p/f/b/u to navigate, q to quit."))))
7432 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7433 (setq buffer-read-only nil)
7434 (let ((org-startup-truncated t)
7435 (org-startup-folded nil)
7436 (org-startup-align-all-tables nil))
7437 (org-mode)
7438 (org-overview))
7439 (setq buffer-read-only t)
7440 (if (and (boundp 'org-goto-start-pos)
7441 (integer-or-marker-p org-goto-start-pos))
7442 (let ((org-show-hierarchy-above t)
7443 (org-show-siblings t)
7444 (org-show-following-heading t))
7445 (goto-char org-goto-start-pos)
7446 (and (outline-invisible-p) (org-show-context)))
7447 (goto-char (point-min)))
7448 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7449 (message "Select location and press RET")
7450 (use-local-map org-goto-map)
7451 (recursive-edit)))
7452 (kill-buffer "*org-goto*")
7453 (cons org-goto-selected-point org-goto-exit-command))))
7455 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7456 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7457 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7458 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7460 (defun org-goto-local-search-headings (string bound noerror)
7461 "Search and make sure that any matches are in headlines."
7462 (catch 'return
7463 (while (if isearch-forward
7464 (search-forward string bound noerror)
7465 (search-backward string bound noerror))
7466 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7467 (and (member :headline context)
7468 (not (member :tags context))))
7469 (throw 'return (point))))))
7471 (defun org-goto-local-auto-isearch ()
7472 "Start isearch."
7473 (interactive)
7474 (goto-char (point-min))
7475 (let ((keys (this-command-keys)))
7476 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7477 (isearch-mode t)
7478 (isearch-process-search-char (string-to-char keys)))))
7480 (defun org-goto-ret (&optional arg)
7481 "Finish `org-goto' by going to the new location."
7482 (interactive "P")
7483 (setq org-goto-selected-point (point)
7484 org-goto-exit-command 'return)
7485 (throw 'exit nil))
7487 (defun org-goto-left ()
7488 "Finish `org-goto' by going to the new location."
7489 (interactive)
7490 (if (org-at-heading-p)
7491 (progn
7492 (beginning-of-line 1)
7493 (setq org-goto-selected-point (point)
7494 org-goto-exit-command 'left)
7495 (throw 'exit nil))
7496 (user-error "Not on a heading")))
7498 (defun org-goto-right ()
7499 "Finish `org-goto' by going to the new location."
7500 (interactive)
7501 (if (org-at-heading-p)
7502 (progn
7503 (setq org-goto-selected-point (point)
7504 org-goto-exit-command 'right)
7505 (throw 'exit nil))
7506 (user-error "Not on a heading")))
7508 (defun org-goto-quit ()
7509 "Finish `org-goto' without cursor motion."
7510 (interactive)
7511 (setq org-goto-selected-point nil)
7512 (setq org-goto-exit-command 'quit)
7513 (throw 'exit nil))
7515 ;;; Indirect buffer display of subtrees
7517 (defvar org-indirect-dedicated-frame nil
7518 "This is the frame being used for indirect tree display.")
7519 (defvar org-last-indirect-buffer nil)
7521 (defun org-tree-to-indirect-buffer (&optional arg)
7522 "Create indirect buffer and narrow it to current subtree.
7523 With a numerical prefix ARG, go up to this level and then take that tree.
7524 If ARG is negative, go up that many levels.
7526 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7527 indirect buffer previously made with this command, to avoid proliferation of
7528 indirect buffers. However, when you call the command with a \
7529 \\[universal-argument] prefix, or
7530 when `org-indirect-buffer-display' is `new-frame', the last buffer
7531 is kept so that you can work with several indirect buffers at the same time.
7532 If `org-indirect-buffer-display' is `dedicated-frame', the \
7533 \\[universal-argument] prefix also
7534 requests that a new frame be made for the new buffer, so that the dedicated
7535 frame is not changed."
7536 (interactive "P")
7537 (let ((cbuf (current-buffer))
7538 (cwin (selected-window))
7539 (pos (point))
7540 beg end level heading ibuf)
7541 (save-excursion
7542 (org-back-to-heading t)
7543 (when (numberp arg)
7544 (setq level (org-outline-level))
7545 (if (< arg 0) (setq arg (+ level arg)))
7546 (while (> (setq level (org-outline-level)) arg)
7547 (org-up-heading-safe)))
7548 (setq beg (point)
7549 heading (org-get-heading))
7550 (org-end-of-subtree t t)
7551 (if (org-at-heading-p) (backward-char 1))
7552 (setq end (point)))
7553 (if (and (buffer-live-p org-last-indirect-buffer)
7554 (not (eq org-indirect-buffer-display 'new-frame))
7555 (not arg))
7556 (kill-buffer org-last-indirect-buffer))
7557 (setq ibuf (org-get-indirect-buffer cbuf heading)
7558 org-last-indirect-buffer ibuf)
7559 (cond
7560 ((or (eq org-indirect-buffer-display 'new-frame)
7561 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7562 (select-frame (make-frame))
7563 (delete-other-windows)
7564 (org-pop-to-buffer-same-window ibuf)
7565 (org-set-frame-title heading))
7566 ((eq org-indirect-buffer-display 'dedicated-frame)
7567 (raise-frame
7568 (select-frame (or (and org-indirect-dedicated-frame
7569 (frame-live-p org-indirect-dedicated-frame)
7570 org-indirect-dedicated-frame)
7571 (setq org-indirect-dedicated-frame (make-frame)))))
7572 (delete-other-windows)
7573 (org-pop-to-buffer-same-window ibuf)
7574 (org-set-frame-title (concat "Indirect: " heading)))
7575 ((eq org-indirect-buffer-display 'current-window)
7576 (org-pop-to-buffer-same-window ibuf))
7577 ((eq org-indirect-buffer-display 'other-window)
7578 (pop-to-buffer ibuf))
7579 (t (error "Invalid value")))
7580 (if (featurep 'xemacs)
7581 (save-excursion (org-mode) (turn-on-font-lock)))
7582 (narrow-to-region beg end)
7583 (show-all)
7584 (goto-char pos)
7585 (run-hook-with-args 'org-cycle-hook 'all)
7586 (and (window-live-p cwin) (select-window cwin))))
7588 (defun org-get-indirect-buffer (&optional buffer heading)
7589 (setq buffer (or buffer (current-buffer)))
7590 (let ((n 1) (base (buffer-name buffer)) bname)
7591 (while (buffer-live-p
7592 (get-buffer
7593 (setq bname
7594 (concat base "-"
7595 (if heading (concat heading "-" (number-to-string n))
7596 (number-to-string n))))))
7597 (setq n (1+ n)))
7598 (condition-case nil
7599 (make-indirect-buffer buffer bname 'clone)
7600 (error (make-indirect-buffer buffer bname)))))
7602 (defun org-set-frame-title (title)
7603 "Set the title of the current frame to the string TITLE."
7604 ;; FIXME: how to name a single frame in XEmacs???
7605 (unless (featurep 'xemacs)
7606 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7608 ;;;; Structure editing
7610 ;;; Inserting headlines
7612 (defun org-previous-line-empty-p (&optional next)
7613 "Is the previous line a blank line?
7614 When NEXT is non-nil, check the next line instead."
7615 (save-excursion
7616 (and (not (bobp))
7617 (or (beginning-of-line (if next 2 0)) t)
7618 (save-match-data
7619 (looking-at "[ \t]*$")))))
7621 (defun org-insert-heading (&optional arg invisible-ok)
7622 "Insert a new heading or item with same depth at point.
7623 If point is in a plain list and ARG is nil, create a new list item.
7624 With one universal prefix argument, insert a heading even in lists.
7625 With two universal prefix arguments, insert the heading at the end
7626 of the parent subtree.
7628 If point is at the beginning of a headline, insert a sibling before
7629 the current headline. If point is not at the beginning, split the line
7630 and create a new headline with the text in the current line after point
7631 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7633 If point is at the beginning of a normal line, turn this line into
7634 a heading.
7636 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7637 This is important for non-interactive uses of the command."
7638 (interactive "P")
7639 (if (org-called-interactively-p 'any) (org-reveal))
7640 (let ((itemp (org-in-item-p))
7641 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7642 (respect-content (or org-insert-heading-respect-content
7643 (equal arg '(16))))
7644 (initial-content "")
7645 (adjust-empty-lines t))
7647 (cond
7649 ((or (= (buffer-size) 0)
7650 (and (not (save-excursion
7651 (and (ignore-errors (org-back-to-heading invisible-ok))
7652 (org-at-heading-p))))
7653 (or arg (not itemp))))
7654 ;; At beginning of buffer or so high up that only a heading
7655 ;; makes sense.
7656 (insert
7657 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7658 (if (org-in-src-block-p) ",* " "* "))
7659 (run-hooks 'org-insert-heading-hook))
7661 ((and itemp (not (equal arg '(4))))
7662 ;; Insert an item
7663 (org-insert-item))
7666 ;; Insert a heading
7667 (save-restriction
7668 (widen)
7669 (let* ((level nil)
7670 (on-heading (org-at-heading-p))
7671 (empty-line-p (if on-heading
7672 (org-previous-line-empty-p)
7673 ;; We will decide later
7674 nil))
7675 ;; Get a level string to fall back on
7676 (fix-level
7677 (save-excursion
7678 (org-back-to-heading t)
7679 (if (org-previous-line-empty-p) (setq empty-line-p t))
7680 (looking-at org-outline-regexp)
7681 (make-string (1- (length (match-string 0))) ?*)))
7682 (stars
7683 (save-excursion
7684 (condition-case nil
7685 (progn
7686 (org-back-to-heading invisible-ok)
7687 (when (and (not on-heading)
7688 (featurep 'org-inlinetask)
7689 (integerp org-inlinetask-min-level)
7690 (>= (length (match-string 0))
7691 org-inlinetask-min-level))
7692 ;; Find a heading level before the inline task
7693 (while (and (setq level (org-up-heading-safe))
7694 (>= level org-inlinetask-min-level)))
7695 (if (org-at-heading-p)
7696 (org-back-to-heading invisible-ok)
7697 (error "This should not happen")))
7698 (unless (and (save-excursion
7699 (save-match-data
7700 (org-backward-heading-same-level
7701 1 invisible-ok))
7702 (= (point) (match-beginning 0)))
7703 (not (org-previous-line-empty-p t)))
7704 (setq empty-line-p (or empty-line-p
7705 (org-previous-line-empty-p))))
7706 (match-string 0))
7707 (error (or fix-level "* ")))))
7708 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7709 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7710 pos hide-previous previous-pos)
7712 ;; If we insert after content, move there and clean up whitespace
7713 (when respect-content
7714 (org-end-of-subtree nil t)
7715 (skip-chars-backward " \r\n")
7716 (and (looking-at "[ \t]+") (replace-match ""))
7717 (unless (eobp) (forward-char 1))
7718 (when (looking-at "^\\*")
7719 (unless (bobp) (backward-char 1))
7720 (insert "\n")))
7722 ;; If we are splitting, grab the text that should be moved to the new headline
7723 (when may-split
7724 (if (org-on-heading-p)
7725 ;; This is a heading, we split intelligently (keeping tags)
7726 (let ((pos (point)))
7727 (goto-char (point-at-bol))
7728 (unless (looking-at org-complex-heading-regexp)
7729 (error "This should not happen"))
7730 (when (and (match-beginning 4)
7731 (> pos (match-beginning 4))
7732 (< pos (match-end 4)))
7733 (setq initial-content (buffer-substring pos (match-end 4)))
7734 (goto-char pos)
7735 (delete-region (point) (match-end 4))
7736 (if (looking-at "[ \t]*$")
7737 (replace-match "")
7738 (insert (make-string (length initial-content) ?\ )))
7739 (setq initial-content (org-trim initial-content)))
7740 (goto-char pos))
7741 ;; a normal line
7742 (unless (bolp)
7743 (setq initial-content (buffer-substring (point) (point-at-eol)))
7744 (delete-region (point) (point-at-eol))
7745 (setq initial-content (org-trim initial-content)))))
7747 ;; If we are at the beginning of the line, insert before it. Else after
7748 (cond
7749 ((and (bolp) (looking-at "[ \t]*$")))
7750 ((and (bolp) (not (looking-at "[ \t]*$")))
7751 (open-line 1))
7753 (goto-char (point-at-eol))
7754 (insert "\n")))
7756 ;; Insert the new heading
7757 (insert stars)
7758 (just-one-space)
7759 (insert initial-content)
7760 (when adjust-empty-lines
7761 (if (or (not blank)
7762 (and blank (not (org-previous-line-empty-p))))
7763 (org-N-empty-lines-before-current (if blank 1 0))))
7764 (run-hooks 'org-insert-heading-hook)))))))
7766 (defun org-N-empty-lines-before-current (N)
7767 "Make the number of empty lines before current exactly N.
7768 So this will delete or add empty lines."
7769 (save-excursion
7770 (goto-char (point-at-bol))
7771 (if (looking-back "\\s-+" nil 'greedy)
7772 (replace-match ""))
7773 (or (bobp) (insert "\n"))
7774 (while (> N 0)
7775 (insert "\n")
7776 (setq N (1- N)))))
7778 (defun org-get-heading (&optional no-tags no-todo)
7779 "Return the heading of the current entry, without the stars.
7780 When NO-TAGS is non-nil, don't include tags.
7781 When NO-TODO is non-nil, don't include TODO keywords."
7782 (save-excursion
7783 (org-back-to-heading t)
7784 (cond
7785 ((and no-tags no-todo)
7786 (looking-at org-complex-heading-regexp)
7787 (match-string 4))
7788 (no-tags
7789 (looking-at (concat org-outline-regexp
7790 "\\(.*?\\)"
7791 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7792 (match-string 1))
7793 (no-todo
7794 (looking-at org-todo-line-regexp)
7795 (match-string 3))
7796 (t (looking-at org-heading-regexp)
7797 (match-string 2)))))
7799 (defvar orgstruct-mode) ; defined below
7801 (defun org-heading-components ()
7802 "Return the components of the current heading.
7803 This is a list with the following elements:
7804 - the level as an integer
7805 - the reduced level, different if `org-odd-levels-only' is set.
7806 - the TODO keyword, or nil
7807 - the priority character, like ?A, or nil if no priority is given
7808 - the headline text itself, or the tags string if no headline text
7809 - the tags string, or nil."
7810 (save-excursion
7811 (org-back-to-heading t)
7812 (if (let (case-fold-search)
7813 (looking-at
7814 (if orgstruct-mode
7815 org-heading-regexp
7816 org-complex-heading-regexp)))
7817 (if orgstruct-mode
7818 (list (length (match-string 1))
7819 (org-reduced-level (length (match-string 1)))
7822 (match-string 2)
7823 nil)
7824 (list (length (match-string 1))
7825 (org-reduced-level (length (match-string 1)))
7826 (org-match-string-no-properties 2)
7827 (and (match-end 3) (aref (match-string 3) 2))
7828 (org-match-string-no-properties 4)
7829 (org-match-string-no-properties 5))))))
7831 (defun org-get-entry ()
7832 "Get the entry text, after heading, entire subtree."
7833 (save-excursion
7834 (org-back-to-heading t)
7835 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7837 (defun org-insert-heading-after-current ()
7838 "Insert a new heading with same level as current, after current subtree."
7839 (interactive)
7840 (org-back-to-heading)
7841 (org-insert-heading)
7842 (org-move-subtree-down)
7843 (end-of-line 1))
7845 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7846 "Insert heading with `org-insert-heading-respect-content' set to t."
7847 (interactive "P")
7848 (let ((org-insert-heading-respect-content t))
7849 (org-insert-heading '(4) invisible-ok)))
7851 (defun org-insert-todo-heading-respect-content (&optional force-state)
7852 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7853 (interactive "P")
7854 (let ((org-insert-heading-respect-content t))
7855 (org-insert-todo-heading force-state '(4))))
7857 (defun org-insert-todo-heading (arg &optional force-heading)
7858 "Insert a new heading with the same level and TODO state as current heading.
7859 If the heading has no TODO state, or if the state is DONE, use the first
7860 state (TODO by default). Also one prefix arg, force first state. With two
7861 prefix args, force inserting at the end of the parent subtree."
7862 (interactive "P")
7863 (when (or force-heading (not (org-insert-item 'checkbox)))
7864 (org-insert-heading (or (and (equal arg '(16)) '(16))
7865 force-heading))
7866 (save-excursion
7867 (org-back-to-heading)
7868 (outline-previous-heading)
7869 (looking-at org-todo-line-regexp))
7870 (let*
7871 ((new-mark-x
7872 (if (or arg
7873 (not (match-beginning 2))
7874 (member (match-string 2) org-done-keywords))
7875 (car org-todo-keywords-1)
7876 (match-string 2)))
7877 (new-mark
7879 (run-hook-with-args-until-success
7880 'org-todo-get-default-hook new-mark-x nil)
7881 new-mark-x)))
7882 (beginning-of-line 1)
7883 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7884 (if org-treat-insert-todo-heading-as-state-change
7885 (org-todo new-mark)
7886 (insert new-mark " "))))
7887 (when org-provide-todo-statistics
7888 (org-update-parent-todo-statistics))))
7890 (defun org-insert-subheading (arg)
7891 "Insert a new subheading and demote it.
7892 Works for outline headings and for plain lists alike."
7893 (interactive "P")
7894 (org-insert-heading arg)
7895 (cond
7896 ((org-at-heading-p) (org-do-demote))
7897 ((org-at-item-p) (org-indent-item))))
7899 (defun org-insert-todo-subheading (arg)
7900 "Insert a new subheading with TODO keyword or checkbox and demote it.
7901 Works for outline headings and for plain lists alike."
7902 (interactive "P")
7903 (org-insert-todo-heading arg)
7904 (cond
7905 ((org-at-heading-p) (org-do-demote))
7906 ((org-at-item-p) (org-indent-item))))
7908 ;;; Promotion and Demotion
7910 (defvar org-after-demote-entry-hook nil
7911 "Hook run after an entry has been demoted.
7912 The cursor will be at the beginning of the entry.
7913 When a subtree is being demoted, the hook will be called for each node.")
7915 (defvar org-after-promote-entry-hook nil
7916 "Hook run after an entry has been promoted.
7917 The cursor will be at the beginning of the entry.
7918 When a subtree is being promoted, the hook will be called for each node.")
7920 (defun org-promote-subtree ()
7921 "Promote the entire subtree.
7922 See also `org-promote'."
7923 (interactive)
7924 (save-excursion
7925 (org-with-limited-levels (org-map-tree 'org-promote)))
7926 (org-fix-position-after-promote))
7928 (defun org-demote-subtree ()
7929 "Demote the entire subtree. See `org-demote'.
7930 See also `org-promote'."
7931 (interactive)
7932 (save-excursion
7933 (org-with-limited-levels (org-map-tree 'org-demote)))
7934 (org-fix-position-after-promote))
7937 (defun org-do-promote ()
7938 "Promote the current heading higher up the tree.
7939 If the region is active in `transient-mark-mode', promote all headings
7940 in the region."
7941 (interactive)
7942 (save-excursion
7943 (if (org-region-active-p)
7944 (org-map-region 'org-promote (region-beginning) (region-end))
7945 (org-promote)))
7946 (org-fix-position-after-promote))
7948 (defun org-do-demote ()
7949 "Demote the current heading lower down the tree.
7950 If the region is active in `transient-mark-mode', demote all headings
7951 in the region."
7952 (interactive)
7953 (save-excursion
7954 (if (org-region-active-p)
7955 (org-map-region 'org-demote (region-beginning) (region-end))
7956 (org-demote)))
7957 (org-fix-position-after-promote))
7959 (defun org-fix-position-after-promote ()
7960 "Make sure that after pro/demotion cursor position is right."
7961 (let ((pos (point)))
7962 (when (save-excursion
7963 (beginning-of-line 1)
7964 (looking-at org-todo-line-regexp)
7965 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7966 (cond ((eobp) (insert " "))
7967 ((eolp) (insert " "))
7968 ((equal (char-after) ?\ ) (forward-char 1))))))
7970 (defun org-current-level ()
7971 "Return the level of the current entry, or nil if before the first headline.
7972 The level is the number of stars at the beginning of the headline."
7973 (save-excursion
7974 (org-with-limited-levels
7975 (if (ignore-errors (org-back-to-heading t))
7976 (funcall outline-level)))))
7978 (defun org-get-previous-line-level ()
7979 "Return the outline depth of the last headline before the current line.
7980 Returns 0 for the first headline in the buffer, and nil if before the
7981 first headline."
7982 (and (org-current-level)
7983 (or (and (/= (line-beginning-position) (point-min))
7984 (save-excursion (beginning-of-line 0) (org-current-level)))
7985 0)))
7987 (defun org-reduced-level (l)
7988 "Compute the effective level of a heading.
7989 This takes into account the setting of `org-odd-levels-only'."
7990 (cond
7991 ((zerop l) 0)
7992 (org-odd-levels-only (1+ (floor (/ l 2))))
7993 (t l)))
7995 (defun org-level-increment ()
7996 "Return the number of stars that will be added or removed at a
7997 time to headlines when structure editing, based on the value of
7998 `org-odd-levels-only'."
7999 (if org-odd-levels-only 2 1))
8001 (defun org-get-valid-level (level &optional change)
8002 "Rectify a level change under the influence of `org-odd-levels-only'
8003 LEVEL is a current level, CHANGE is by how much the level should be
8004 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8005 even level numbers will become the next higher odd number."
8006 (if org-odd-levels-only
8007 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8008 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8009 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8010 (max 1 (+ level (or change 0)))))
8012 (if (boundp 'define-obsolete-function-alias)
8013 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8014 (define-obsolete-function-alias 'org-get-legal-level
8015 'org-get-valid-level)
8016 (define-obsolete-function-alias 'org-get-legal-level
8017 'org-get-valid-level "23.1")))
8019 (defun org-promote ()
8020 "Promote the current heading higher up the tree.
8021 If the region is active in `transient-mark-mode', promote all headings
8022 in the region."
8023 (org-back-to-heading t)
8024 (let* ((level (save-match-data (funcall outline-level)))
8025 (after-change-functions (remove 'flyspell-after-change-function
8026 after-change-functions))
8027 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8028 (diff (abs (- level (length up-head) -1))))
8029 (cond ((and (= level 1) org-called-with-limited-levels
8030 org-allow-promoting-top-level-subtree)
8031 (replace-match "# " nil t))
8032 ((= level 1)
8033 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8034 (t (replace-match up-head nil t)))
8035 ;; Fixup tag positioning
8036 (unless (= level 1)
8037 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8038 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8039 (run-hooks 'org-after-promote-entry-hook)))
8041 (defun org-demote ()
8042 "Demote the current heading lower down the tree.
8043 If the region is active in `transient-mark-mode', demote all headings
8044 in the region."
8045 (org-back-to-heading t)
8046 (let* ((level (save-match-data (funcall outline-level)))
8047 (after-change-functions (remove 'flyspell-after-change-function
8048 after-change-functions))
8049 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8050 (diff (abs (- level (length down-head) -1))))
8051 (replace-match down-head nil t)
8052 ;; Fixup tag positioning
8053 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8054 (if org-adapt-indentation (org-fixup-indentation diff))
8055 (run-hooks 'org-after-demote-entry-hook)))
8057 (defun org-cycle-level ()
8058 "Cycle the level of an empty headline through possible states.
8059 This goes first to child, then to parent, level, then up the hierarchy.
8060 After top level, it switches back to sibling level."
8061 (interactive)
8062 (let ((org-adapt-indentation nil))
8063 (when (org-point-at-end-of-empty-headline)
8064 (setq this-command 'org-cycle-level) ; Only needed for caching
8065 (let ((cur-level (org-current-level))
8066 (prev-level (org-get-previous-line-level)))
8067 (cond
8068 ;; If first headline in file, promote to top-level.
8069 ((= prev-level 0)
8070 (loop repeat (/ (- cur-level 1) (org-level-increment))
8071 do (org-do-promote)))
8072 ;; If same level as prev, demote one.
8073 ((= prev-level cur-level)
8074 (org-do-demote))
8075 ;; If parent is top-level, promote to top level if not already.
8076 ((= prev-level 1)
8077 (loop repeat (/ (- cur-level 1) (org-level-increment))
8078 do (org-do-promote)))
8079 ;; If top-level, return to prev-level.
8080 ((= cur-level 1)
8081 (loop repeat (/ (- prev-level 1) (org-level-increment))
8082 do (org-do-demote)))
8083 ;; If less than prev-level, promote one.
8084 ((< cur-level prev-level)
8085 (org-do-promote))
8086 ;; If deeper than prev-level, promote until higher than
8087 ;; prev-level.
8088 ((> cur-level prev-level)
8089 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8090 do (org-do-promote))))
8091 t))))
8093 (defun org-map-tree (fun)
8094 "Call FUN for every heading underneath the current one."
8095 (org-back-to-heading)
8096 (let ((level (funcall outline-level)))
8097 (save-excursion
8098 (funcall fun)
8099 (while (and (progn
8100 (outline-next-heading)
8101 (> (funcall outline-level) level))
8102 (not (eobp)))
8103 (funcall fun)))))
8105 (defun org-map-region (fun beg end)
8106 "Call FUN for every heading between BEG and END."
8107 (let ((org-ignore-region t))
8108 (save-excursion
8109 (setq end (copy-marker end))
8110 (goto-char beg)
8111 (if (and (re-search-forward org-outline-regexp-bol nil t)
8112 (< (point) end))
8113 (funcall fun))
8114 (while (and (progn
8115 (outline-next-heading)
8116 (< (point) end))
8117 (not (eobp)))
8118 (funcall fun)))))
8120 (defvar org-property-end-re) ; silence byte-compiler
8121 (defun org-fixup-indentation (diff)
8122 "Change the indentation in the current entry by DIFF.
8123 However, if any line in the current entry has no indentation, or if it
8124 would end up with no indentation after the change, nothing at all is done."
8125 (save-excursion
8126 (let ((end (save-excursion (outline-next-heading)
8127 (point-marker)))
8128 (prohibit (if (> diff 0)
8129 "^\\S-"
8130 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8131 col)
8132 (unless (save-excursion (end-of-line 1)
8133 (re-search-forward prohibit end t))
8134 (while (and (< (point) end)
8135 (re-search-forward "^[ \t]+" end t))
8136 (goto-char (match-end 0))
8137 (setq col (current-column))
8138 (if (< diff 0) (replace-match ""))
8139 (org-indent-to-column (+ diff col))))
8140 (move-marker end nil))))
8142 (defun org-convert-to-odd-levels ()
8143 "Convert an org-mode file with all levels allowed to one with odd levels.
8144 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8145 level 5 etc."
8146 (interactive)
8147 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8148 (let ((outline-level 'org-outline-level)
8149 (org-odd-levels-only nil) n)
8150 (save-excursion
8151 (goto-char (point-min))
8152 (while (re-search-forward "^\\*\\*+ " nil t)
8153 (setq n (- (length (match-string 0)) 2))
8154 (while (>= (setq n (1- n)) 0)
8155 (org-demote))
8156 (end-of-line 1))))))
8158 (defun org-convert-to-oddeven-levels ()
8159 "Convert an org-mode file with only odd levels to one with odd/even levels.
8160 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8161 file contains a section with an even level, conversion would
8162 destroy the structure of the file. An error is signaled in this
8163 case."
8164 (interactive)
8165 (goto-char (point-min))
8166 ;; First check if there are no even levels
8167 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8168 (org-show-context t)
8169 (error "Not all levels are odd in this file. Conversion not possible"))
8170 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8171 (let ((outline-regexp org-outline-regexp)
8172 (outline-level 'org-outline-level)
8173 (org-odd-levels-only nil) n)
8174 (save-excursion
8175 (goto-char (point-min))
8176 (while (re-search-forward "^\\*\\*+ " nil t)
8177 (setq n (/ (1- (length (match-string 0))) 2))
8178 (while (>= (setq n (1- n)) 0)
8179 (org-promote))
8180 (end-of-line 1))))))
8182 (defun org-tr-level (n)
8183 "Make N odd if required."
8184 (if org-odd-levels-only (1+ (/ n 2)) n))
8186 ;;; Vertical tree motion, cutting and pasting of subtrees
8188 (defun org-move-subtree-up (&optional arg)
8189 "Move the current subtree up past ARG headlines of the same level."
8190 (interactive "p")
8191 (org-move-subtree-down (- (prefix-numeric-value arg))))
8193 (defun org-move-subtree-down (&optional arg)
8194 "Move the current subtree down past ARG headlines of the same level."
8195 (interactive "p")
8196 (setq arg (prefix-numeric-value arg))
8197 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8198 'org-get-last-sibling))
8199 (ins-point (make-marker))
8200 (cnt (abs arg))
8201 (col (current-column))
8202 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8203 ;; Select the tree
8204 (org-back-to-heading)
8205 (setq beg0 (point))
8206 (save-excursion
8207 (setq ne-beg (org-back-over-empty-lines))
8208 (setq beg (point)))
8209 (save-match-data
8210 (save-excursion (outline-end-of-heading)
8211 (setq folded (outline-invisible-p)))
8212 (outline-end-of-subtree))
8213 (outline-next-heading)
8214 (setq ne-end (org-back-over-empty-lines))
8215 (setq end (point))
8216 (goto-char beg0)
8217 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8218 ;; include less whitespace
8219 (save-excursion
8220 (goto-char beg)
8221 (forward-line (- ne-beg ne-end))
8222 (setq beg (point))))
8223 ;; Find insertion point, with error handling
8224 (while (> cnt 0)
8225 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8226 (progn (goto-char beg0)
8227 (user-error "Cannot move past superior level or buffer limit")))
8228 (setq cnt (1- cnt)))
8229 (if (> arg 0)
8230 ;; Moving forward - still need to move over subtree
8231 (progn (org-end-of-subtree t t)
8232 (save-excursion
8233 (org-back-over-empty-lines)
8234 (or (bolp) (newline)))))
8235 (setq ne-ins (org-back-over-empty-lines))
8236 (move-marker ins-point (point))
8237 (setq txt (buffer-substring beg end))
8238 (org-save-markers-in-region beg end)
8239 (delete-region beg end)
8240 (org-remove-empty-overlays-at beg)
8241 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8242 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8243 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8244 (let ((bbb (point)))
8245 (insert-before-markers txt)
8246 (org-reinstall-markers-in-region bbb)
8247 (move-marker ins-point bbb))
8248 (or (bolp) (insert "\n"))
8249 (setq ins-end (point))
8250 (goto-char ins-point)
8251 (org-skip-whitespace)
8252 (when (and (< arg 0)
8253 (org-first-sibling-p)
8254 (> ne-ins ne-beg))
8255 ;; Move whitespace back to beginning
8256 (save-excursion
8257 (goto-char ins-end)
8258 (let ((kill-whole-line t))
8259 (kill-line (- ne-ins ne-beg)) (point)))
8260 (insert (make-string (- ne-ins ne-beg) ?\n)))
8261 (move-marker ins-point nil)
8262 (if folded
8263 (hide-subtree)
8264 (org-show-entry)
8265 (show-children)
8266 (org-cycle-hide-drawers 'children))
8267 (org-clean-visibility-after-subtree-move)
8268 ;; move back to the initial column we were at
8269 (move-to-column col)))
8271 (defvar org-subtree-clip ""
8272 "Clipboard for cut and paste of subtrees.
8273 This is actually only a copy of the kill, because we use the normal kill
8274 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8276 (defvar org-subtree-clip-folded nil
8277 "Was the last copied subtree folded?
8278 This is used to fold the tree back after pasting.")
8280 (defun org-cut-subtree (&optional n)
8281 "Cut the current subtree into the clipboard.
8282 With prefix arg N, cut this many sequential subtrees.
8283 This is a short-hand for marking the subtree and then cutting it."
8284 (interactive "p")
8285 (org-copy-subtree n 'cut))
8287 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8288 "Copy the current subtree it in the clipboard.
8289 With prefix arg N, copy this many sequential subtrees.
8290 This is a short-hand for marking the subtree and then copying it.
8291 If CUT is non-nil, actually cut the subtree.
8292 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8293 of some markers in the region, even if CUT is non-nil. This is
8294 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8295 (interactive "p")
8296 (let (beg end folded (beg0 (point)))
8297 (if (org-called-interactively-p 'any)
8298 (org-back-to-heading nil) ; take what looks like a subtree
8299 (org-back-to-heading t)) ; take what is really there
8300 (setq beg (point))
8301 (skip-chars-forward " \t\r\n")
8302 (save-match-data
8303 (if nosubtrees
8304 (outline-next-heading)
8305 (save-excursion (outline-end-of-heading)
8306 (setq folded (outline-invisible-p)))
8307 (condition-case nil
8308 (org-forward-heading-same-level (1- n) t)
8309 (error nil))
8310 (org-end-of-subtree t t)))
8311 (setq end (point))
8312 (goto-char beg0)
8313 (when (> end beg)
8314 (setq org-subtree-clip-folded folded)
8315 (when (or cut force-store-markers)
8316 (org-save-markers-in-region beg end))
8317 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8318 (setq org-subtree-clip (current-kill 0))
8319 (message "%s: Subtree(s) with %d characters"
8320 (if cut "Cut" "Copied")
8321 (length org-subtree-clip)))))
8323 (defun org-paste-subtree (&optional level tree for-yank)
8324 "Paste the clipboard as a subtree, with modification of headline level.
8325 The entire subtree is promoted or demoted in order to match a new headline
8326 level.
8328 If the cursor is at the beginning of a headline, the same level as
8329 that headline is used to paste the tree.
8331 If not, the new level is derived from the *visible* headings
8332 before and after the insertion point, and taken to be the inferior headline
8333 level of the two. So if the previous visible heading is level 3 and the
8334 next is level 4 (or vice versa), level 4 will be used for insertion.
8335 This makes sure that the subtree remains an independent subtree and does
8336 not swallow low level entries.
8338 You can also force a different level, either by using a numeric prefix
8339 argument, or by inserting the heading marker by hand. For example, if the
8340 cursor is after \"*****\", then the tree will be shifted to level 5.
8342 If optional TREE is given, use this text instead of the kill ring.
8344 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8345 move back over whitespace before inserting, and move point to the end of
8346 the inserted text when done."
8347 (interactive "P")
8348 (setq tree (or tree (and kill-ring (current-kill 0))))
8349 (unless (org-kill-is-subtree-p tree)
8350 (user-error "%s"
8351 (substitute-command-keys
8352 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8353 (org-with-limited-levels
8354 (let* ((visp (not (outline-invisible-p)))
8355 (txt tree)
8356 (^re_ "\\(\\*+\\)[ \t]*")
8357 (old-level (if (string-match org-outline-regexp-bol txt)
8358 (- (match-end 0) (match-beginning 0) 1)
8359 -1))
8360 (force-level (cond (level (prefix-numeric-value level))
8361 ((and (looking-at "[ \t]*$")
8362 (string-match
8363 "^\\*+$" (buffer-substring
8364 (point-at-bol) (point))))
8365 (- (match-end 1) (match-beginning 1)))
8366 ((and (bolp)
8367 (looking-at org-outline-regexp))
8368 (- (match-end 0) (point) 1))))
8369 (previous-level (save-excursion
8370 (condition-case nil
8371 (progn
8372 (outline-previous-visible-heading 1)
8373 (if (looking-at ^re_)
8374 (- (match-end 0) (match-beginning 0) 1)
8376 (error 1))))
8377 (next-level (save-excursion
8378 (condition-case nil
8379 (progn
8380 (or (looking-at org-outline-regexp)
8381 (outline-next-visible-heading 1))
8382 (if (looking-at ^re_)
8383 (- (match-end 0) (match-beginning 0) 1)
8385 (error 1))))
8386 (new-level (or force-level (max previous-level next-level)))
8387 (shift (if (or (= old-level -1)
8388 (= new-level -1)
8389 (= old-level new-level))
8391 (- new-level old-level)))
8392 (delta (if (> shift 0) -1 1))
8393 (func (if (> shift 0) 'org-demote 'org-promote))
8394 (org-odd-levels-only nil)
8395 beg end newend)
8396 ;; Remove the forced level indicator
8397 (if force-level
8398 (delete-region (point-at-bol) (point)))
8399 ;; Paste
8400 (beginning-of-line (if (bolp) 1 2))
8401 (setq beg (point))
8402 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8403 (insert-before-markers txt)
8404 (unless (string-match "\n\\'" txt) (insert "\n"))
8405 (setq newend (point))
8406 (org-reinstall-markers-in-region beg)
8407 (setq end (point))
8408 (goto-char beg)
8409 (skip-chars-forward " \t\n\r")
8410 (setq beg (point))
8411 (if (and (outline-invisible-p) visp)
8412 (save-excursion (outline-show-heading)))
8413 ;; Shift if necessary
8414 (unless (= shift 0)
8415 (save-restriction
8416 (narrow-to-region beg end)
8417 (while (not (= shift 0))
8418 (org-map-region func (point-min) (point-max))
8419 (setq shift (+ delta shift)))
8420 (goto-char (point-min))
8421 (setq newend (point-max))))
8422 (when (or (org-called-interactively-p 'interactive) for-yank)
8423 (message "Clipboard pasted as level %d subtree" new-level))
8424 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8425 kill-ring
8426 (eq org-subtree-clip (current-kill 0))
8427 org-subtree-clip-folded)
8428 ;; The tree was folded before it was killed/copied
8429 (hide-subtree))
8430 (and for-yank (goto-char newend)))))
8432 (defun org-kill-is-subtree-p (&optional txt)
8433 "Check if the current kill is an outline subtree, or a set of trees.
8434 Returns nil if kill does not start with a headline, or if the first
8435 headline level is not the largest headline level in the tree.
8436 So this will actually accept several entries of equal levels as well,
8437 which is OK for `org-paste-subtree'.
8438 If optional TXT is given, check this string instead of the current kill."
8439 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8440 (re (org-get-limited-outline-regexp))
8441 (^re (concat "^" re))
8442 (start-level (and kill
8443 (string-match
8444 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8445 kill)
8446 (- (match-end 2) (match-beginning 2) 1)))
8447 (start (1+ (or (match-beginning 2) -1))))
8448 (if (not start-level)
8449 (progn
8450 nil) ;; does not even start with a heading
8451 (catch 'exit
8452 (while (setq start (string-match ^re kill (1+ start)))
8453 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8454 (throw 'exit nil)))
8455 t))))
8457 (defvar org-markers-to-move nil
8458 "Markers that should be moved with a cut-and-paste operation.
8459 Those markers are stored together with their positions relative to
8460 the start of the region.")
8462 (defun org-save-markers-in-region (beg end)
8463 "Check markers in region.
8464 If these markers are between BEG and END, record their position relative
8465 to BEG, so that after moving the block of text, we can put the markers back
8466 into place.
8467 This function gets called just before an entry or tree gets cut from the
8468 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8469 called immediately, to move the markers with the entries."
8470 (setq org-markers-to-move nil)
8471 (when (featurep 'org-clock)
8472 (org-clock-save-markers-for-cut-and-paste beg end))
8473 (when (featurep 'org-agenda)
8474 (org-agenda-save-markers-for-cut-and-paste beg end)))
8476 (defun org-check-and-save-marker (marker beg end)
8477 "Check if MARKER is between BEG and END.
8478 If yes, remember the marker and the distance to BEG."
8479 (when (and (marker-buffer marker)
8480 (equal (marker-buffer marker) (current-buffer)))
8481 (if (and (>= marker beg) (< marker end))
8482 (push (cons marker (- marker beg)) org-markers-to-move))))
8484 (defun org-reinstall-markers-in-region (beg)
8485 "Move all remembered markers to their position relative to BEG."
8486 (mapc (lambda (x)
8487 (move-marker (car x) (+ beg (cdr x))))
8488 org-markers-to-move)
8489 (setq org-markers-to-move nil))
8491 (defun org-narrow-to-subtree ()
8492 "Narrow buffer to the current subtree."
8493 (interactive)
8494 (save-excursion
8495 (save-match-data
8496 (org-with-limited-levels
8497 (narrow-to-region
8498 (progn (org-back-to-heading t) (point))
8499 (progn (org-end-of-subtree t t)
8500 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8501 (point)))))))
8503 (defun org-narrow-to-block ()
8504 "Narrow buffer to the current block."
8505 (interactive)
8506 (let* ((case-fold-search t)
8507 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8508 "^[ \t]*#\\+end_.*")))
8509 (if blockp
8510 (narrow-to-region (car blockp) (cdr blockp))
8511 (user-error "Not in a block"))))
8513 (eval-when-compile
8514 (defvar org-property-drawer-re))
8516 (defvar org-property-start-re) ;; defined below
8517 (defun org-clone-subtree-with-time-shift (n &optional shift)
8518 "Clone the task (subtree) at point N times.
8519 The clones will be inserted as siblings.
8521 In interactive use, the user will be prompted for the number of
8522 clones to be produced. If the entry has a timestamp, the user
8523 will also be prompted for a time shift, which may be a repeater
8524 as used in time stamps, for example `+3d'. To disable this,
8525 you can call the function with a universal prefix argument.
8527 When a valid repeater is given and the entry contains any time
8528 stamps, the clones will become a sequence in time, with time
8529 stamps in the subtree shifted for each clone produced. If SHIFT
8530 is nil or the empty string, time stamps will be left alone. The
8531 ID property of the original subtree is removed.
8533 If the original subtree did contain time stamps with a repeater,
8534 the following will happen:
8535 - the repeater will be removed in each clone
8536 - an additional clone will be produced, with the current, unshifted
8537 date(s) in the entry.
8538 - the original entry will be placed *after* all the clones, with
8539 repeater intact.
8540 - the start days in the repeater in the original entry will be shifted
8541 to past the last clone.
8542 In this way you can spell out a number of instances of a repeating task,
8543 and still retain the repeater to cover future instances of the task."
8544 (interactive "nNumber of clones to produce: ")
8545 (let ((shift
8546 (or shift
8547 (if (and (not (equal current-prefix-arg '(4)))
8548 (save-excursion
8549 (re-search-forward org-ts-regexp-both
8550 (save-excursion
8551 (org-end-of-subtree t)
8552 (point)) t)))
8553 (read-from-minibuffer
8554 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8555 ""))) ;; No time shift
8556 (n-no-remove -1)
8557 (drawer-re org-drawer-regexp)
8558 beg end template task idprop
8559 shift-n shift-what doshift nmin nmax)
8560 (if (not (and (integerp n) (> n 0)))
8561 (error "Invalid number of replications %s" n))
8562 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8563 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8564 shift)))
8565 (error "Invalid shift specification %s" shift))
8566 (when doshift
8567 (setq shift-n (string-to-number (match-string 1 shift))
8568 shift-what (cdr (assoc (match-string 2 shift)
8569 '(("d" . day) ("w" . week)
8570 ("m" . month) ("y" . year))))))
8571 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8572 (setq nmin 1 nmax n)
8573 (org-back-to-heading t)
8574 (setq beg (point))
8575 (setq idprop (org-entry-get nil "ID"))
8576 (org-end-of-subtree t t)
8577 (or (bolp) (insert "\n"))
8578 (setq end (point))
8579 (setq template (buffer-substring beg end))
8580 (when (and doshift
8581 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8582 (delete-region beg end)
8583 (setq end beg)
8584 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8585 (goto-char end)
8586 (loop for n from nmin to nmax do
8587 ;; prepare clone
8588 (with-temp-buffer
8589 (insert template)
8590 (org-mode)
8591 (goto-char (point-min))
8592 (org-show-subtree)
8593 (and idprop (if org-clone-delete-id
8594 (org-entry-delete nil "ID")
8595 (org-id-get-create t)))
8596 (unless (= n 0)
8597 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8598 (kill-whole-line))
8599 (goto-char (point-min))
8600 (while (re-search-forward drawer-re nil t)
8601 (org-remove-empty-drawer-at (point))))
8602 (goto-char (point-min))
8603 (when doshift
8604 (while (re-search-forward org-ts-regexp-both nil t)
8605 (org-timestamp-change (* n shift-n) shift-what))
8606 (unless (= n n-no-remove)
8607 (goto-char (point-min))
8608 (while (re-search-forward org-ts-regexp nil t)
8609 (save-excursion
8610 (goto-char (match-beginning 0))
8611 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8612 (delete-region (match-beginning 1) (match-end 1)))))))
8613 (setq task (buffer-string)))
8614 (insert task))
8615 (goto-char beg)))
8617 ;;; Outline Sorting
8619 (defun org-sort (with-case)
8620 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8621 Optional argument WITH-CASE means sort case-sensitively."
8622 (interactive "P")
8623 (cond
8624 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8625 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8627 (org-call-with-arg 'org-sort-entries with-case))))
8629 (defun org-sort-remove-invisible (s)
8630 "Remove invisible links from string S."
8631 (remove-text-properties 0 (length s) org-rm-props s)
8632 (while (string-match org-bracket-link-regexp s)
8633 (setq s (replace-match (if (match-end 2)
8634 (match-string 3 s)
8635 (match-string 1 s)) t t s)))
8636 (let ((st (format " %s " s)))
8637 (while (string-match org-emph-re st)
8638 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8639 (setq s (substring st 1 -1)))
8642 (defvar org-priority-regexp) ; defined later in the file
8644 (defvar org-after-sorting-entries-or-items-hook nil
8645 "Hook that is run after a bunch of entries or items have been sorted.
8646 When children are sorted, the cursor is in the parent line when this
8647 hook gets called. When a region or a plain list is sorted, the cursor
8648 will be in the first entry of the sorted region/list.")
8650 (defun org-sort-entries
8651 (&optional with-case sorting-type getkey-func compare-func property)
8652 "Sort entries on a certain level of an outline tree.
8653 If there is an active region, the entries in the region are sorted.
8654 Else, if the cursor is before the first entry, sort the top-level items.
8655 Else, the children of the entry at point are sorted.
8657 Sorting can be alphabetically, numerically, by date/time as given by
8658 a time stamp, by a property, by priority order, or by a custom function.
8660 The command prompts for the sorting type unless it has been given to the
8661 function through the SORTING-TYPE argument, which needs to be a character,
8662 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8663 precise meaning of each character:
8665 n Numerically, by converting the beginning of the entry/item to a number.
8666 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8667 o By order of TODO keywords.
8668 t By date/time, either the first active time stamp in the entry, or, if
8669 none exist, by the first inactive one.
8670 s By the scheduled date/time.
8671 d By deadline date/time.
8672 c By creation time, which is assumed to be the first inactive time stamp
8673 at the beginning of a line.
8674 p By priority according to the cookie.
8675 r By the value of a property.
8677 Capital letters will reverse the sort order.
8679 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8680 called with point at the beginning of the record. It must return either
8681 a string or a number that should serve as the sorting key for that record.
8683 Comparing entries ignores case by default. However, with an optional argument
8684 WITH-CASE, the sorting considers case as well.
8686 Sorting is done against the visible part of the headlines, it ignores hidden
8687 links.
8689 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8690 (interactive "P")
8691 (let ((case-func (if with-case 'identity 'downcase))
8692 (cmstr
8693 ;; The clock marker is lost when using `sort-subr', let's
8694 ;; store the clocking string.
8695 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8696 (save-excursion
8697 (goto-char org-clock-marker)
8698 (looking-back "^.*") (match-string-no-properties 0))))
8699 start beg end stars re re2
8700 txt what tmp)
8701 ;; Find beginning and end of region to sort
8702 (cond
8703 ((org-region-active-p)
8704 ;; we will sort the region
8705 (setq end (region-end)
8706 what "region")
8707 (goto-char (region-beginning))
8708 (if (not (org-at-heading-p)) (outline-next-heading))
8709 (setq start (point)))
8710 ((or (org-at-heading-p)
8711 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8712 ;; we will sort the children of the current headline
8713 (org-back-to-heading)
8714 (setq start (point)
8715 end (progn (org-end-of-subtree t t)
8716 (or (bolp) (insert "\n"))
8717 (org-back-over-empty-lines)
8718 (point))
8719 what "children")
8720 (goto-char start)
8721 (show-subtree)
8722 (outline-next-heading))
8724 ;; we will sort the top-level entries in this file
8725 (goto-char (point-min))
8726 (or (org-at-heading-p) (outline-next-heading))
8727 (setq start (point))
8728 (goto-char (point-max))
8729 (beginning-of-line 1)
8730 (when (looking-at ".*?\\S-")
8731 ;; File ends in a non-white line
8732 (end-of-line 1)
8733 (insert "\n"))
8734 (setq end (point-max))
8735 (setq what "top-level")
8736 (goto-char start)
8737 (show-all)))
8739 (setq beg (point))
8740 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8742 (looking-at "\\(\\*+\\)")
8743 (setq stars (match-string 1)
8744 re (concat "^" (regexp-quote stars) " +")
8745 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8746 txt (buffer-substring beg end))
8747 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8748 (if (and (not (equal stars "*")) (string-match re2 txt))
8749 (user-error "Region to sort contains a level above the first entry"))
8751 (unless sorting-type
8752 (message
8753 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8754 [t]ime [s]cheduled [d]eadline [c]reated
8755 A/N/P/R/O/F/T/S/D/C means reversed:"
8756 what)
8757 (setq sorting-type (read-char-exclusive))
8759 (unless getkey-func
8760 (and (= (downcase sorting-type) ?f)
8761 (setq getkey-func
8762 (org-icompleting-read "Sort using function: "
8763 obarray 'fboundp t nil nil))
8764 (setq getkey-func (intern getkey-func))))
8766 (and (= (downcase sorting-type) ?r)
8767 (not property)
8768 (setq property
8769 (org-icompleting-read "Property: "
8770 (mapcar 'list (org-buffer-property-keys t))
8771 nil t))))
8773 (message "Sorting entries...")
8775 (save-restriction
8776 (narrow-to-region start end)
8777 (let ((dcst (downcase sorting-type))
8778 (case-fold-search nil)
8779 (now (current-time)))
8780 (sort-subr
8781 (/= dcst sorting-type)
8782 ;; This function moves to the beginning character of the "record" to
8783 ;; be sorted.
8784 (lambda nil
8785 (if (re-search-forward re nil t)
8786 (goto-char (match-beginning 0))
8787 (goto-char (point-max))))
8788 ;; This function moves to the last character of the "record" being
8789 ;; sorted.
8790 (lambda nil
8791 (save-match-data
8792 (condition-case nil
8793 (outline-forward-same-level 1)
8794 (error
8795 (goto-char (point-max))))))
8796 ;; This function returns the value that gets sorted against.
8797 (lambda nil
8798 (cond
8799 ((= dcst ?n)
8800 (if (looking-at org-complex-heading-regexp)
8801 (string-to-number (org-sort-remove-invisible (match-string 4)))
8802 nil))
8803 ((= dcst ?a)
8804 (if (looking-at org-complex-heading-regexp)
8805 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8806 nil))
8807 ((= dcst ?t)
8808 (let ((end (save-excursion (outline-next-heading) (point))))
8809 (if (or (re-search-forward org-ts-regexp end t)
8810 (re-search-forward org-ts-regexp-both end t))
8811 (org-time-string-to-seconds (match-string 0))
8812 (org-float-time now))))
8813 ((= dcst ?c)
8814 (let ((end (save-excursion (outline-next-heading) (point))))
8815 (if (re-search-forward
8816 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8817 end t)
8818 (org-time-string-to-seconds (match-string 0))
8819 (org-float-time now))))
8820 ((= dcst ?s)
8821 (let ((end (save-excursion (outline-next-heading) (point))))
8822 (if (re-search-forward org-scheduled-time-regexp end t)
8823 (org-time-string-to-seconds (match-string 1))
8824 (org-float-time now))))
8825 ((= dcst ?d)
8826 (let ((end (save-excursion (outline-next-heading) (point))))
8827 (if (re-search-forward org-deadline-time-regexp end t)
8828 (org-time-string-to-seconds (match-string 1))
8829 (org-float-time now))))
8830 ((= dcst ?p)
8831 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8832 (string-to-char (match-string 2))
8833 org-default-priority))
8834 ((= dcst ?r)
8835 (or (org-entry-get nil property) ""))
8836 ((= dcst ?o)
8837 (if (looking-at org-complex-heading-regexp)
8838 (- 9999 (length (member (match-string 2)
8839 org-todo-keywords-1)))))
8840 ((= dcst ?f)
8841 (if getkey-func
8842 (progn
8843 (setq tmp (funcall getkey-func))
8844 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8845 tmp)
8846 (error "Invalid key function `%s'" getkey-func)))
8847 (t (error "Invalid sorting type `%c'" sorting-type))))
8849 (cond
8850 ((= dcst ?a) 'string<)
8851 ((= dcst ?f) compare-func)
8852 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8853 (run-hooks 'org-after-sorting-entries-or-items-hook)
8854 ;; Reset the clock marker if needed
8855 (when cmstr
8856 (save-excursion
8857 (goto-char start)
8858 (search-forward cmstr nil t)
8859 (move-marker org-clock-marker (point))))
8860 (message "Sorting entries...done")))
8862 (defun org-do-sort (table what &optional with-case sorting-type)
8863 "Sort TABLE of WHAT according to SORTING-TYPE.
8864 The user will be prompted for the SORTING-TYPE if the call to this
8865 function does not specify it. WHAT is only for the prompt, to indicate
8866 what is being sorted. The sorting key will be extracted from
8867 the car of the elements of the table.
8868 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8869 (unless sorting-type
8870 (message
8871 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8872 what)
8873 (setq sorting-type (read-char-exclusive)))
8874 (let ((dcst (downcase sorting-type))
8875 extractfun comparefun)
8876 ;; Define the appropriate functions
8877 (cond
8878 ((= dcst ?n)
8879 (setq extractfun 'string-to-number
8880 comparefun (if (= dcst sorting-type) '< '>)))
8881 ((= dcst ?a)
8882 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8883 (lambda(x) (downcase (org-sort-remove-invisible x))))
8884 comparefun (if (= dcst sorting-type)
8885 'string<
8886 (lambda (a b) (and (not (string< a b))
8887 (not (string= a b)))))))
8888 ((= dcst ?t)
8889 (setq extractfun
8890 (lambda (x)
8891 (if (or (string-match org-ts-regexp x)
8892 (string-match org-ts-regexp-both x))
8893 (org-float-time
8894 (org-time-string-to-time (match-string 0 x)))
8896 comparefun (if (= dcst sorting-type) '< '>)))
8897 (t (error "Invalid sorting type `%c'" sorting-type)))
8899 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8900 table)
8901 (lambda (a b) (funcall comparefun (car a) (car b))))))
8904 ;;; The orgstruct minor mode
8906 ;; Define a minor mode which can be used in other modes in order to
8907 ;; integrate the org-mode structure editing commands.
8909 ;; This is really a hack, because the org-mode structure commands use
8910 ;; keys which normally belong to the major mode. Here is how it
8911 ;; works: The minor mode defines all the keys necessary to operate the
8912 ;; structure commands, but wraps the commands into a function which
8913 ;; tests if the cursor is currently at a headline or a plain list
8914 ;; item. If that is the case, the structure command is used,
8915 ;; temporarily setting many Org-mode variables like regular
8916 ;; expressions for filling etc. However, when any of those keys is
8917 ;; used at a different location, function uses `key-binding' to look
8918 ;; up if the key has an associated command in another currently active
8919 ;; keymap (minor modes, major mode, global), and executes that
8920 ;; command. There might be problems if any of the keys is otherwise
8921 ;; used as a prefix key.
8923 (defcustom orgstruct-heading-prefix-regexp ""
8924 "Regexp that matches the custom prefix of Org headlines in
8925 orgstruct(++)-mode."
8926 :group 'org
8927 :version "24.4"
8928 :package-version '(Org . "8.3")
8929 :type 'regexp)
8930 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8932 (defcustom orgstruct-setup-hook nil
8933 "Hook run after orgstruct-mode-map is filled."
8934 :group 'org
8935 :version "24.4"
8936 :package-version '(Org . "8.0")
8937 :type 'hook)
8939 (defvar orgstruct-initialized nil)
8941 (defvar org-local-vars nil
8942 "List of local variables, for use by `orgstruct-mode'.")
8944 ;;;###autoload
8945 (define-minor-mode orgstruct-mode
8946 "Toggle the minor mode `orgstruct-mode'.
8947 This mode is for using Org-mode structure commands in other
8948 modes. The following keys behave as if Org-mode were active, if
8949 the cursor is on a headline, or on a plain list item (both as
8950 defined by Org-mode)."
8951 nil " OrgStruct" (make-sparse-keymap)
8952 (funcall (if orgstruct-mode
8953 'add-to-invisibility-spec
8954 'remove-from-invisibility-spec)
8955 '(outline . t))
8956 (when orgstruct-mode
8957 (org-load-modules-maybe)
8958 (unless orgstruct-initialized
8959 (orgstruct-setup)
8960 (setq orgstruct-initialized t))))
8962 ;;;###autoload
8963 (defun turn-on-orgstruct ()
8964 "Unconditionally turn on `orgstruct-mode'."
8965 (orgstruct-mode 1))
8967 (defvar org-fb-vars nil)
8968 (make-variable-buffer-local 'org-fb-vars)
8969 (defun orgstruct++-mode (&optional arg)
8970 "Toggle `orgstruct-mode', the enhanced version of it.
8971 In addition to setting orgstruct-mode, this also exports all
8972 indentation and autofilling variables from org-mode into the
8973 buffer. It will also recognize item context in multiline items."
8974 (interactive "P")
8975 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8976 (if (< arg 1)
8977 (progn (orgstruct-mode -1)
8978 (mapc (lambda(v)
8979 (org-set-local (car v)
8980 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8981 org-fb-vars))
8982 (orgstruct-mode 1)
8983 (setq org-fb-vars nil)
8984 (unless org-local-vars
8985 (setq org-local-vars (org-get-local-variables)))
8986 (let (var val)
8987 (mapc
8988 (lambda (x)
8989 (when (string-match
8990 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8991 (symbol-name (car x)))
8992 (setq var (car x) val (nth 1 x))
8993 (push (list var `(quote ,(eval var))) org-fb-vars)
8994 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8995 org-local-vars)
8996 (org-set-local 'orgstruct-is-++ t))))
8998 (defvar orgstruct-is-++ nil
8999 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9000 (make-variable-buffer-local 'orgstruct-is-++)
9002 ;;;###autoload
9003 (defun turn-on-orgstruct++ ()
9004 "Unconditionally turn on `orgstruct++-mode'."
9005 (orgstruct++-mode 1))
9007 (defun orgstruct-error ()
9008 "Error when there is no default binding for a structure key."
9009 (interactive)
9010 (funcall (if (fboundp 'user-error)
9011 'user-error
9012 'error)
9013 "This key has no function outside structure elements"))
9015 (defun orgstruct-setup ()
9016 "Setup orgstruct keymap."
9017 (dolist (cell '((org-demote . t)
9018 (org-metaleft . t)
9019 (org-metaright . t)
9020 (org-promote . t)
9021 (org-shiftmetaleft . t)
9022 (org-shiftmetaright . t)
9023 org-backward-element
9024 org-backward-heading-same-level
9025 org-ctrl-c-ret
9026 org-ctrl-c-minus
9027 org-ctrl-c-star
9028 org-cycle
9029 org-forward-heading-same-level
9030 org-insert-heading
9031 org-insert-heading-respect-content
9032 org-kill-note-or-show-branches
9033 org-mark-subtree
9034 org-meta-return
9035 org-metadown
9036 org-metaup
9037 org-narrow-to-subtree
9038 org-promote-subtree
9039 org-reveal
9040 org-shiftdown
9041 org-shiftleft
9042 org-shiftmetadown
9043 org-shiftmetaup
9044 org-shiftright
9045 org-shifttab
9046 org-shifttab
9047 org-shiftup
9048 org-show-subtree
9049 org-sort
9050 org-up-element
9051 outline-demote
9052 outline-next-visible-heading
9053 outline-previous-visible-heading
9054 outline-promote
9055 outline-up-heading
9056 show-children))
9057 (let ((f (or (car-safe cell) cell))
9058 (disable-when-heading-prefix (cdr-safe cell)))
9059 (when (fboundp f)
9060 (let ((new-bindings))
9061 (dolist (binding (nconc (where-is-internal f org-mode-map)
9062 (where-is-internal f outline-mode-map)))
9063 (push binding new-bindings)
9064 ;; TODO use local-function-key-map
9065 (dolist (rep '(("<tab>" . "TAB")
9066 ("<return>" . "RET")
9067 ("<escape>" . "ESC")
9068 ("<delete>" . "DEL")))
9069 (setq binding (read-kbd-macro
9070 (let ((case-fold-search))
9071 (replace-regexp-in-string
9072 (regexp-quote (cdr rep))
9073 (car rep)
9074 (key-description binding)))))
9075 (pushnew binding new-bindings :test 'equal)))
9076 (dolist (binding new-bindings)
9077 (let ((key (lookup-key orgstruct-mode-map binding)))
9078 (when (or (not key) (numberp key))
9079 (condition-case nil
9080 (org-defkey orgstruct-mode-map
9081 binding
9082 (orgstruct-make-binding f binding disable-when-heading-prefix))
9083 (error nil)))))))))
9084 (run-hooks 'orgstruct-setup-hook))
9086 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9087 "Create a function for binding in the structure minor mode.
9088 FUN is the command to call inside a table. KEY is the key that
9089 should be checked in for a command to execute outside of tables.
9090 Non-nil `disable-when-heading-prefix' means to disable the command
9091 if `orgstruct-heading-prefix-regexp' is not empty."
9092 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9093 (let ((nname name)
9094 (i 0))
9095 (while (fboundp (intern nname))
9096 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9097 (setq name (intern nname)))
9098 (eval
9099 (let ((bindings '((org-heading-regexp
9100 (concat "^"
9101 orgstruct-heading-prefix-regexp
9102 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9103 (org-outline-regexp
9104 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9105 (org-outline-regexp-bol
9106 (concat "^" org-outline-regexp))
9107 (outline-regexp org-outline-regexp)
9108 (outline-heading-end-regexp "\n")
9109 (outline-level 'org-outline-level)
9110 (outline-heading-alist))))
9111 `(defun ,name (arg)
9112 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9113 "Outside of structure, run the binding of `"
9114 (key-description key) "'."
9115 (when disable-when-heading-prefix
9116 (concat
9117 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9118 "back to the default binding due to limitations of Org's implementation of\n"
9119 "`" (symbol-name fun) "'.")))
9120 (interactive "p")
9121 (let* ((disable
9122 ,(and disable-when-heading-prefix
9123 '(not (string= orgstruct-heading-prefix-regexp ""))))
9124 (fallback
9125 (or disable
9126 (not
9127 (let* ,bindings
9128 (org-context-p 'headline 'item
9129 ,(when (memq fun
9130 '(org-insert-heading
9131 org-insert-heading-respect-content
9132 org-meta-return))
9133 '(when orgstruct-is-++
9134 'item-body))))))))
9135 (if fallback
9136 (let* ((orgstruct-mode)
9137 (binding
9138 (loop with key = ,key
9139 for rep in
9140 '(nil
9141 ("<\\([^>]*\\)tab>" . "\\1TAB")
9142 ("<\\([^>]*\\)return>" . "\\1RET")
9143 ("<\\([^>]*\\)escape>" . "\\1ESC")
9144 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9146 (when rep
9147 (setq key (read-kbd-macro
9148 (let ((case-fold-search))
9149 (replace-regexp-in-string
9150 (car rep)
9151 (cdr rep)
9152 (key-description key))))))
9153 thereis (key-binding key))))
9154 (if (keymapp binding)
9155 (org-set-transient-map binding)
9156 (let ((func (or binding
9157 (unless disable
9158 'orgstruct-error))))
9159 (when func
9160 (call-interactively func)))))
9161 (org-run-like-in-org-mode
9162 (lambda ()
9163 (interactive)
9164 (let* ,bindings
9165 (call-interactively ',fun)))))))))
9166 name))
9168 (defun org-contextualize-keys (alist contexts)
9169 "Return valid elements in ALIST depending on CONTEXTS.
9171 `org-agenda-custom-commands' or `org-capture-templates' are the
9172 values used for ALIST, and `org-agenda-custom-commands-contexts'
9173 or `org-capture-templates-contexts' are the associated contexts
9174 definitions."
9175 (let ((contexts
9176 ;; normalize contexts
9177 (mapcar
9178 (lambda(c) (cond ((listp (cadr c))
9179 (list (car c) (car c) (cadr c)))
9180 ((string= "" (cadr c))
9181 (list (car c) (car c) (caddr c)))
9182 (t c))) contexts))
9183 (a alist) c r s)
9184 ;; loop over all commands or templates
9185 (while (setq c (pop a))
9186 (let (vrules repl)
9187 (cond
9188 ((not (assoc (car c) contexts))
9189 (push c r))
9190 ((and (assoc (car c) contexts)
9191 (setq vrules (org-contextualize-validate-key
9192 (car c) contexts)))
9193 (mapc (lambda (vr)
9194 (when (not (equal (car vr) (cadr vr)))
9195 (setq repl vr))) vrules)
9196 (if (not repl) (push c r)
9197 (push (cadr repl) s)
9198 (push
9199 (cons (car c)
9200 (cdr (or (assoc (cadr repl) alist)
9201 (error "Undefined key `%s' as contextual replacement for `%s'"
9202 (cadr repl) (car c)))))
9203 r))))))
9204 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9205 (delq
9207 (delete-dups
9208 (mapcar (lambda (x)
9209 (let ((tpl (car x)))
9210 (when (not (delq
9212 (mapcar (lambda(y)
9213 (equal y tpl)) s))) x)))
9214 (reverse r))))))
9216 (defun org-contextualize-validate-key (key contexts)
9217 "Check CONTEXTS for agenda or capture KEY."
9218 (let (r rr res)
9219 (while (setq r (pop contexts))
9220 (mapc
9221 (lambda (rr)
9222 (when
9223 (and (equal key (car r))
9224 (if (functionp rr) (funcall rr)
9225 (or (and (eq (car rr) 'in-file)
9226 (buffer-file-name)
9227 (string-match (cdr rr) (buffer-file-name)))
9228 (and (eq (car rr) 'in-mode)
9229 (string-match (cdr rr) (symbol-name major-mode)))
9230 (and (eq (car rr) 'in-buffer)
9231 (string-match (cdr rr) (buffer-name)))
9232 (when (and (eq (car rr) 'not-in-file)
9233 (buffer-file-name))
9234 (not (string-match (cdr rr) (buffer-file-name))))
9235 (when (eq (car rr) 'not-in-mode)
9236 (not (string-match (cdr rr) (symbol-name major-mode))))
9237 (when (eq (car rr) 'not-in-buffer)
9238 (not (string-match (cdr rr) (buffer-name)))))))
9239 (push r res)))
9240 (car (last r))))
9241 (delete-dups (delq nil res))))
9243 (defun org-context-p (&rest contexts)
9244 "Check if local context is any of CONTEXTS.
9245 Possible values in the list of contexts are `table', `headline', and `item'."
9246 (let ((pos (point)))
9247 (goto-char (point-at-bol))
9248 (prog1 (or (and (memq 'table contexts)
9249 (looking-at "[ \t]*|"))
9250 (and (memq 'headline contexts)
9251 (looking-at org-outline-regexp))
9252 (and (memq 'item contexts)
9253 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9254 (and (memq 'item-body contexts)
9255 (org-in-item-p)))
9256 (goto-char pos))))
9258 (defun org-get-local-variables ()
9259 "Return a list of all local variables in an Org mode buffer."
9260 (let (varlist)
9261 (with-current-buffer (get-buffer-create "*Org tmp*")
9262 (erase-buffer)
9263 (org-mode)
9264 (setq varlist (buffer-local-variables)))
9265 (kill-buffer "*Org tmp*")
9266 (delq nil
9267 (mapcar
9268 (lambda (x)
9269 (setq x
9270 (if (symbolp x)
9271 (list x)
9272 (list (car x) (cdr x))))
9273 (if (and (not (get (car x) 'org-state))
9274 (string-match
9275 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9276 (symbol-name (car x))))
9277 x nil))
9278 varlist))))
9280 (defun org-clone-local-variables (from-buffer &optional regexp)
9281 "Clone local variables from FROM-BUFFER.
9282 Optional argument REGEXP selects variables to clone."
9283 (mapc
9284 (lambda (pair)
9285 (and (symbolp (car pair))
9286 (or (null regexp)
9287 (string-match regexp (symbol-name (car pair))))
9288 (set (make-local-variable (car pair))
9289 (cdr pair))))
9290 (buffer-local-variables from-buffer)))
9292 ;;;###autoload
9293 (defun org-run-like-in-org-mode (cmd)
9294 "Run a command, pretending that the current buffer is in Org-mode.
9295 This will temporarily bind local variables that are typically bound in
9296 Org-mode to the values they have in Org-mode, and then interactively
9297 call CMD."
9298 (org-load-modules-maybe)
9299 (unless org-local-vars
9300 (setq org-local-vars (org-get-local-variables)))
9301 (let (binds)
9302 (dolist (var org-local-vars)
9303 (when (or (not (boundp (car var)))
9304 (eq (symbol-value (car var))
9305 (default-value (car var))))
9306 (push (list (car var) `(quote ,(cadr var))) binds)))
9307 (eval `(let ,binds
9308 (call-interactively (quote ,cmd))))))
9310 ;;;; Archiving
9312 (defun org-get-category (&optional pos force-refresh)
9313 "Get the category applying to position POS."
9314 (save-match-data
9315 (if force-refresh (org-refresh-category-properties))
9316 (let ((pos (or pos (point))))
9317 (or (get-text-property pos 'org-category)
9318 (progn (org-refresh-category-properties)
9319 (get-text-property pos 'org-category))))))
9321 (defun org-refresh-category-properties ()
9322 "Refresh category text properties in the buffer."
9323 (let ((case-fold-search t)
9324 (inhibit-read-only t)
9325 (def-cat (cond
9326 ((null org-category)
9327 (if buffer-file-name
9328 (file-name-sans-extension
9329 (file-name-nondirectory buffer-file-name))
9330 "???"))
9331 ((symbolp org-category) (symbol-name org-category))
9332 (t org-category)))
9333 beg end cat pos optionp)
9334 (org-with-silent-modifications
9335 (save-excursion
9336 (save-restriction
9337 (widen)
9338 (goto-char (point-min))
9339 (put-text-property (point) (point-max) 'org-category def-cat)
9340 (while (re-search-forward
9341 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9342 (setq pos (match-end 0)
9343 optionp (equal (char-after (match-beginning 0)) ?#)
9344 cat (org-trim (match-string 2)))
9345 (if optionp
9346 (setq beg (point-at-bol) end (point-max))
9347 (org-back-to-heading t)
9348 (setq beg (point) end (org-end-of-subtree t t)))
9349 (put-text-property beg end 'org-category cat)
9350 (put-text-property beg end 'org-category-position beg)
9351 (goto-char pos)))))))
9353 (defun org-refresh-properties (dprop tprop)
9354 "Refresh buffer text properties.
9355 DPROP is the drawer property and TPROP is the corresponding text
9356 property to set."
9357 (let ((case-fold-search t)
9358 (inhibit-read-only t) p)
9359 (org-with-silent-modifications
9360 (save-excursion
9361 (save-restriction
9362 (widen)
9363 (goto-char (point-min))
9364 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9365 (setq p (org-match-string-no-properties 1))
9366 (save-excursion
9367 (org-back-to-heading t)
9368 (put-text-property
9369 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9372 ;;;; Link Stuff
9374 ;;; Link abbreviations
9376 (defun org-link-expand-abbrev (link)
9377 "Apply replacements as defined in `org-link-abbrev-alist'."
9378 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9379 (let* ((key (match-string 1 link))
9380 (as (or (assoc key org-link-abbrev-alist-local)
9381 (assoc key org-link-abbrev-alist)))
9382 (tag (and (match-end 2) (match-string 3 link)))
9383 rpl)
9384 (if (not as)
9385 link
9386 (setq rpl (cdr as))
9387 (cond
9388 ((symbolp rpl) (funcall rpl tag))
9389 ((string-match "%(\\([^)]+\\))" rpl)
9390 (replace-match
9391 (save-match-data
9392 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9393 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9394 ((string-match "%h" rpl)
9395 (replace-match (url-hexify-string (or tag "")) t t rpl))
9396 (t (concat rpl tag)))))
9397 link))
9399 ;;; Storing and inserting links
9401 (defvar org-insert-link-history nil
9402 "Minibuffer history for links inserted with `org-insert-link'.")
9404 (defvar org-stored-links nil
9405 "Contains the links stored with `org-store-link'.")
9407 (defvar org-store-link-plist nil
9408 "Plist with info about the most recently link created with `org-store-link'.")
9410 (defvar org-link-protocols nil
9411 "Link protocols added to Org-mode using `org-add-link-type'.")
9413 (defvar org-store-link-functions nil
9414 "List of functions that are called to create and store a link.
9415 Each function will be called in turn until one returns a non-nil
9416 value. Each function should check if it is responsible for creating
9417 this link (for example by looking at the major mode).
9418 If not, it must exit and return nil.
9419 If yes, it should return a non-nil value after a calling
9420 `org-store-link-props' with a list of properties and values.
9421 Special properties are:
9423 :type The link prefix, like \"http\". This must be given.
9424 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9425 This is obligatory as well.
9426 :description Optional default description for the second pair
9427 of brackets in an Org-mode link. The user can still change
9428 this when inserting this link into an Org-mode buffer.
9430 In addition to these, any additional properties can be specified
9431 and then used in capture templates.")
9433 (defun org-add-link-type (type &optional follow export)
9434 "Add TYPE to the list of `org-link-types'.
9435 Re-compute all regular expressions depending on `org-link-types'
9437 FOLLOW and EXPORT are two functions.
9439 FOLLOW should take the link path as the single argument and do whatever
9440 is necessary to follow the link, for example find a file or display
9441 a mail message.
9443 EXPORT should format the link path for export to one of the export formats.
9444 It should be a function accepting three arguments:
9446 path the path of the link, the text after the prefix (like \"http:\")
9447 desc the description of the link, if any, or a description added by
9448 org-export-normalize-links if there is none
9449 format the export format, a symbol like `html' or `latex' or `ascii'..
9451 The function may use the FORMAT information to return different values
9452 depending on the format. The return value will be put literally into
9453 the exported file. If the return value is nil, this means Org should
9454 do what it normally does with links which do not have EXPORT defined.
9456 Org-mode has a built-in default for exporting links. If you are happy with
9457 this default, there is no need to define an export function for the link
9458 type. For a simple example of an export function, see `org-bbdb.el'."
9459 (add-to-list 'org-link-types type t)
9460 (org-make-link-regexps)
9461 (if (assoc type org-link-protocols)
9462 (setcdr (assoc type org-link-protocols) (list follow export))
9463 (push (list type follow export) org-link-protocols)))
9465 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9466 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9468 ;;;###autoload
9469 (defun org-store-link (arg)
9470 "\\<org-mode-map>Store an org-link to the current location.
9471 This link is added to `org-stored-links' and can later be inserted
9472 into an org-buffer with \\[org-insert-link].
9474 For some link types, a prefix arg is interpreted.
9475 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9476 For file links, arg negates `org-context-in-file-links'.
9478 A double prefix arg force skipping storing functions that are not
9479 part of Org's core.
9481 A triple prefix arg force storing a link for each line in the
9482 active region."
9483 (interactive "P")
9484 (org-load-modules-maybe)
9485 (if (and (equal arg '(64)) (org-region-active-p))
9486 (save-excursion
9487 (let ((end (region-end)))
9488 (goto-char (region-beginning))
9489 (set-mark (point))
9490 (while (< (point-at-eol) end)
9491 (move-end-of-line 1) (activate-mark)
9492 (let (current-prefix-arg)
9493 (call-interactively 'org-store-link))
9494 (move-beginning-of-line 2)
9495 (set-mark (point)))))
9496 (org-with-limited-levels
9497 (setq org-store-link-plist nil)
9498 (let (link cpltxt desc description search
9499 txt custom-id agenda-link sfuns sfunsn)
9500 (cond
9502 ;; Store a link using an external link type
9503 ((and (not (equal arg '(16)))
9504 (setq sfuns
9505 (delq
9506 nil (mapcar (lambda (f)
9507 (let (fs) (if (funcall f) (push f fs))))
9508 org-store-link-functions))
9509 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9510 (or (and (cdr sfuns)
9511 (funcall (intern
9512 (completing-read
9513 "Which function for creating the link? "
9514 sfunsn nil t (car sfunsn)))))
9515 (funcall (caar sfuns)))
9516 (setq link (plist-get org-store-link-plist :link)
9517 desc (or (plist-get org-store-link-plist
9518 :description) link))))
9520 ;; Store a link from a source code buffer
9521 ((org-src-edit-buffer-p)
9522 (let (label gc)
9523 (while (or (not label)
9524 (save-excursion
9525 (save-restriction
9526 (widen)
9527 (goto-char (point-min))
9528 (re-search-forward
9529 (regexp-quote (format org-coderef-label-format label))
9530 nil t))))
9531 (when label (message "Label exists already") (sit-for 2))
9532 (setq label (read-string "Code line label: " label)))
9533 (end-of-line 1)
9534 (setq link (format org-coderef-label-format label))
9535 (setq gc (- 79 (length link)))
9536 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9537 (insert link)
9538 (setq link (concat "(" label ")") desc nil)))
9540 ;; We are in the agenda, link to referenced location
9541 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9542 (let ((m (or (get-text-property (point) 'org-hd-marker)
9543 (get-text-property (point) 'org-marker))))
9544 (when m
9545 (org-with-point-at m
9546 (setq agenda-link
9547 (if (org-called-interactively-p 'any)
9548 (call-interactively 'org-store-link)
9549 (org-store-link nil)))))))
9551 ((eq major-mode 'calendar-mode)
9552 (let ((cd (calendar-cursor-to-date)))
9553 (setq link
9554 (format-time-string
9555 (car org-time-stamp-formats)
9556 (apply 'encode-time
9557 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9558 nil nil nil))))
9559 (org-store-link-props :type "calendar" :date cd)))
9561 ((eq major-mode 'help-mode)
9562 (setq link (concat "help:" (save-excursion
9563 (goto-char (point-min))
9564 (looking-at "^[^ ]+")
9565 (match-string 0))))
9566 (org-store-link-props :type "help"))
9568 ((eq major-mode 'w3-mode)
9569 (setq cpltxt (if (and (buffer-name)
9570 (not (string-match "Untitled" (buffer-name))))
9571 (buffer-name)
9572 (url-view-url t))
9573 link (url-view-url t))
9574 (org-store-link-props :type "w3" :url (url-view-url t)))
9576 ((eq major-mode 'image-mode)
9577 (setq cpltxt (concat "file:"
9578 (abbreviate-file-name buffer-file-name))
9579 link cpltxt)
9580 (org-store-link-props :type "image" :file buffer-file-name))
9582 ;; In dired, store a link to the file of the current line
9583 ((eq major-mode 'dired-mode)
9584 (let ((file (dired-get-filename nil t)))
9585 (setq file (if file
9586 (abbreviate-file-name
9587 (expand-file-name (dired-get-filename nil t)))
9588 ;; otherwise, no file so use current directory.
9589 default-directory))
9590 (setq cpltxt (concat "file:" file)
9591 link cpltxt)))
9593 ((setq search (run-hook-with-args-until-success
9594 'org-create-file-search-functions))
9595 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9596 "::" search))
9597 (setq cpltxt (or description link)))
9599 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9600 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9601 (cond
9602 ;; Store a link using the target at point
9603 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9604 (setq cpltxt
9605 (concat "file:"
9606 (abbreviate-file-name
9607 (buffer-file-name (buffer-base-buffer)))
9608 "::" (match-string 1))
9609 link cpltxt))
9610 ((and (featurep 'org-id)
9611 (or (eq org-id-link-to-org-use-id t)
9612 (and (org-called-interactively-p 'any)
9613 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9614 (and (eq org-id-link-to-org-use-id
9615 'create-if-interactive-and-no-custom-id)
9616 (not custom-id))))
9617 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9618 ;; Store a link using the ID at point
9619 (setq link (condition-case nil
9620 (prog1 (org-id-store-link)
9621 (setq desc (plist-get org-store-link-plist
9622 :description)))
9623 (error
9624 ;; Probably before first headline, link only to file
9625 (concat "file:"
9626 (abbreviate-file-name
9627 (buffer-file-name (buffer-base-buffer))))))))
9629 ;; Just link to current headline
9630 (setq cpltxt (concat "file:"
9631 (abbreviate-file-name
9632 (buffer-file-name (buffer-base-buffer)))))
9633 ;; Add a context search string
9634 (when (org-xor org-context-in-file-links arg)
9635 (let* ((ee (org-element-at-point))
9636 (et (org-element-type ee))
9637 (ev (plist-get (cadr ee) :value))
9638 (ek (plist-get (cadr ee) :key))
9639 (eok (and (stringp ek) (string-match "name" ek))))
9640 (setq txt (cond
9641 ((org-at-heading-p) nil)
9642 ((and (eq et 'keyword) eok) ev)
9643 ((org-region-active-p)
9644 (buffer-substring (region-beginning) (region-end)))))
9645 (when (or (null txt) (string-match "\\S-" txt))
9646 (setq cpltxt
9647 (concat cpltxt "::"
9648 (condition-case nil
9649 (org-make-org-heading-search-string txt)
9650 (error "")))
9651 desc (or (and (eq et 'keyword) eok ev)
9652 (nth 4 (ignore-errors (org-heading-components)))
9653 "NONE")))))
9654 (if (string-match "::\\'" cpltxt)
9655 (setq cpltxt (substring cpltxt 0 -2)))
9656 (setq link cpltxt))))
9658 ((buffer-file-name (buffer-base-buffer))
9659 ;; Just link to this file here.
9660 (setq cpltxt (concat "file:"
9661 (abbreviate-file-name
9662 (buffer-file-name (buffer-base-buffer)))))
9663 ;; Add a context string.
9664 (when (org-xor org-context-in-file-links arg)
9665 (setq txt (if (org-region-active-p)
9666 (buffer-substring (region-beginning) (region-end))
9667 (buffer-substring (point-at-bol) (point-at-eol))))
9668 ;; Only use search option if there is some text.
9669 (when (string-match "\\S-" txt)
9670 (setq cpltxt
9671 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9672 desc "NONE")))
9673 (setq link cpltxt))
9675 ((org-called-interactively-p 'interactive)
9676 (user-error "No method for storing a link from this buffer"))
9678 (t (setq link nil)))
9680 ;; We're done setting link and desc, clean up
9681 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9682 (setq link (or link cpltxt)
9683 desc (or desc cpltxt))
9684 (cond ((equal desc "NONE") (setq desc nil))
9685 ((string-match org-bracket-link-analytic-regexp desc)
9686 (let ((d0 (match-string 3 desc))
9687 (p0 (match-string 5 desc)))
9688 (setq desc
9689 (replace-regexp-in-string
9690 org-bracket-link-regexp
9691 (concat (or p0 d0)
9692 (if (equal (length (match-string 0 desc))
9693 (length desc)) "*" "")) desc)))))
9695 ;; Return the link
9696 (if (not (and (or (org-called-interactively-p 'any)
9697 executing-kbd-macro) link))
9698 (or agenda-link (and link (org-make-link-string link desc)))
9699 (push (list link desc) org-stored-links)
9700 (message "Stored: %s" (or desc link))
9701 (when custom-id
9702 (setq link (concat "file:" (abbreviate-file-name
9703 (buffer-file-name)) "::#" custom-id))
9704 (push (list link desc) org-stored-links))
9705 (car org-stored-links))))))
9707 (defun org-store-link-props (&rest plist)
9708 "Store link properties, extract names and addresses."
9709 (let (x adr)
9710 (when (setq x (plist-get plist :from))
9711 (setq adr (mail-extract-address-components x))
9712 (setq plist (plist-put plist :fromname (car adr)))
9713 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9714 (when (setq x (plist-get plist :to))
9715 (setq adr (mail-extract-address-components x))
9716 (setq plist (plist-put plist :toname (car adr)))
9717 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9718 (let ((from (plist-get plist :from))
9719 (to (plist-get plist :to)))
9720 (when (and from to org-from-is-user-regexp)
9721 (setq plist
9722 (plist-put plist :fromto
9723 (if (string-match org-from-is-user-regexp from)
9724 (concat "to %t")
9725 (concat "from %f"))))))
9726 (setq org-store-link-plist plist))
9728 (defun org-add-link-props (&rest plist)
9729 "Add these properties to the link property list."
9730 (let (key value)
9731 (while plist
9732 (setq key (pop plist) value (pop plist))
9733 (setq org-store-link-plist
9734 (plist-put org-store-link-plist key value)))))
9736 (defun org-email-link-description (&optional fmt)
9737 "Return the description part of an email link.
9738 This takes information from `org-store-link-plist' and formats it
9739 according to FMT (default from `org-email-link-description-format')."
9740 (setq fmt (or fmt org-email-link-description-format))
9741 (let* ((p org-store-link-plist)
9742 (to (plist-get p :toaddress))
9743 (from (plist-get p :fromaddress))
9744 (table
9745 (list
9746 (cons "%c" (plist-get p :fromto))
9747 (cons "%F" (plist-get p :from))
9748 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9749 (cons "%T" (plist-get p :to))
9750 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9751 (cons "%s" (plist-get p :subject))
9752 (cons "%d" (plist-get p :date))
9753 (cons "%m" (plist-get p :message-id)))))
9754 (when (string-match "%c" fmt)
9755 ;; Check if the user wrote this message
9756 (if (and org-from-is-user-regexp from to
9757 (save-match-data (string-match org-from-is-user-regexp from)))
9758 (setq fmt (replace-match "to %t" t t fmt))
9759 (setq fmt (replace-match "from %f" t t fmt))))
9760 (org-replace-escapes fmt table)))
9762 (defun org-make-org-heading-search-string (&optional string)
9763 "Make search string for the current headline or STRING."
9764 (let ((s (or string
9765 (and (derived-mode-p 'org-mode)
9766 (save-excursion
9767 (org-back-to-heading t)
9768 (org-element-property :raw-value (org-element-at-point))))))
9769 (lines org-context-in-file-links))
9770 (or string (setq s (concat "*" s))) ; Add * for headlines
9771 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9772 (when (and string (integerp lines) (> lines 0))
9773 (let ((slines (org-split-string s "\n")))
9774 (when (< lines (length slines))
9775 (setq s (mapconcat
9776 'identity
9777 (reverse (nthcdr (- (length slines) lines)
9778 (reverse slines))) "\n")))))
9779 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9781 (defun org-make-link-string (link &optional description)
9782 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9783 (unless (string-match "\\S-" link)
9784 (error "Empty link"))
9785 (when (and description
9786 (stringp description)
9787 (not (string-match "\\S-" description)))
9788 (setq description nil))
9789 (when (stringp description)
9790 ;; Remove brackets from the description, they are fatal.
9791 (while (string-match "\\[" description)
9792 (setq description (replace-match "{" t t description)))
9793 (while (string-match "\\]" description)
9794 (setq description (replace-match "}" t t description))))
9795 (when (equal link description)
9796 ;; No description needed, it is identical
9797 (setq description nil))
9798 (when (and (not description)
9799 (not (string-match (org-image-file-name-regexp) link))
9800 (not (equal link (org-link-escape link))))
9801 (setq description (org-extract-attributes link)))
9802 (setq link
9803 (cond ((string-match (org-image-file-name-regexp) link) link)
9804 ((string-match org-link-types-re link)
9805 (concat (match-string 1 link)
9806 (org-link-escape (substring link (match-end 1)))))
9807 (t (org-link-escape link))))
9808 (concat "[[" link "]"
9809 (if description (concat "[" description "]") "")
9810 "]"))
9812 (defconst org-link-escape-chars
9813 ;;%20 %2B %3B %3D %5B %5D
9814 '(?\ ?\+ ?\; ?\= ?\[ ?\])
9815 "List of characters that should be escaped in a link when stored to Org.
9816 This is the list that is used for internal purposes.")
9818 (defconst org-link-escape-chars-browser
9819 ;;%20 %22
9820 '(?\ ?\")
9821 "List of characters to be escaped before handing over to the browser.
9822 If you consider using this constant then you probably want to use
9823 the function `org-link-escape-browser' instead. See there why
9824 this constant is a candidate to be removed once Org drops support
9825 for Emacs 24.1 and 24.2.")
9827 (defun org-link-escape (text &optional table merge)
9828 "Return percent escaped representation of TEXT.
9829 TEXT is a string with the text to escape.
9830 Optional argument TABLE is a list with characters that should be
9831 escaped. When nil, `org-link-escape-chars' is used.
9832 If optional argument MERGE is set, merge TABLE into
9833 `org-link-escape-chars'."
9834 (cond
9835 ((and table merge)
9836 (mapc (lambda (defchr)
9837 (unless (member defchr table)
9838 (setq table (cons defchr table)))) org-link-escape-chars))
9839 ((null table)
9840 (setq table org-link-escape-chars)))
9841 (mapconcat
9842 (lambda (char)
9843 (if (or (member char table)
9844 (and (or (< char 32) (= char ?\%) (> char 126))
9845 org-url-hexify-p))
9846 (mapconcat (lambda (sequence-element)
9847 (format "%%%.2X" sequence-element))
9848 (or (encode-coding-char char 'utf-8)
9849 (error "Unable to percent escape character: %s"
9850 (char-to-string char))) "")
9851 (char-to-string char))) text ""))
9853 (defun org-link-escape-browser (text)
9854 "Escape some characters before handing over to the browser.
9855 This function is a candidate to be removed together with the
9856 constant `org-link-escape-chars-browser' once Org drops support
9857 for Emacs 24.1 and 24.2. All calls to this function will have to
9858 be replaced with `url-encode-url' which is available since Emacs
9859 24.3.1."
9860 ;; Example with the Org link
9861 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
9862 ;; to open the browser with +subject:"Release 8.2" filled into the
9863 ;; query field: In this case the variable TEXT contains the
9864 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
9865 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
9866 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
9867 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
9868 (if (fboundp 'url-encode-url)
9869 (url-encode-url text)
9870 (if (org-string-match-p
9871 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
9872 text)
9873 (org-link-escape text org-link-escape-chars-browser)
9874 text)))
9876 (defun org-link-unescape (str)
9877 "Unhex hexified Unicode strings as returned from the JavaScript function
9878 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9879 (unless (and (null str) (string= "" str))
9880 (let ((pos 0) (case-fold-search t) unhexed)
9881 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9882 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9883 (setq str (replace-match unhexed t t str))
9884 (setq pos (+ pos (length unhexed))))))
9885 str)
9887 (defun org-link-unescape-compound (hex)
9888 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9889 Note: this function also decodes single byte encodings like
9890 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9891 (save-match-data
9892 (let* ((bytes (cdr (split-string hex "%")))
9893 (ret "")
9894 (eat 0)
9895 (sum 0))
9896 (while bytes
9897 (let* ((val (string-to-number (pop bytes) 16))
9898 (shift-xor
9899 (if (= 0 eat)
9900 (cond
9901 ((>= val 252) (cons 6 252))
9902 ((>= val 248) (cons 5 248))
9903 ((>= val 240) (cons 4 240))
9904 ((>= val 224) (cons 3 224))
9905 ((>= val 192) (cons 2 192))
9906 (t (cons 0 0)))
9907 (cons 6 128))))
9908 (if (>= val 192) (setq eat (car shift-xor)))
9909 (setq val (logxor val (cdr shift-xor)))
9910 (setq sum (+ (lsh sum (car shift-xor)) val))
9911 (if (> eat 0) (setq eat (- eat 1)))
9912 (cond
9913 ((= 0 eat) ;multi byte
9914 (setq ret (concat ret (org-char-to-string sum)))
9915 (setq sum 0))
9916 ((not bytes) ; single byte(s)
9917 (setq ret (org-link-unescape-single-byte-sequence hex))))
9918 )) ;; end (while bytes
9919 ret )))
9921 (defun org-link-unescape-single-byte-sequence (hex)
9922 "Unhexify hex-encoded single byte character sequences."
9923 (mapconcat (lambda (byte)
9924 (char-to-string (string-to-number byte 16)))
9925 (cdr (split-string hex "%")) ""))
9927 (defun org-xor (a b)
9928 "Exclusive or."
9929 (if a (not b) b))
9931 (defun org-fixup-message-id-for-http (s)
9932 "Replace special characters in a message id, so it can be used in an http query."
9933 (when (string-match "%" s)
9934 (setq s (mapconcat (lambda (c)
9935 (if (eq c ?%)
9936 "%25"
9937 (char-to-string c)))
9938 s "")))
9939 (while (string-match "<" s)
9940 (setq s (replace-match "%3C" t t s)))
9941 (while (string-match ">" s)
9942 (setq s (replace-match "%3E" t t s)))
9943 (while (string-match "@" s)
9944 (setq s (replace-match "%40" t t s)))
9947 (defun org-link-prettify (link)
9948 "Return a human-readable representation of LINK.
9949 The car of LINK must be a raw link the cdr of LINK must be either
9950 a link description or nil."
9951 (let ((desc (or (cadr link) "<no description>")))
9952 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9953 "<" (car link) ">")))
9955 ;;;###autoload
9956 (defun org-insert-link-global ()
9957 "Insert a link like Org-mode does.
9958 This command can be called in any mode to insert a link in Org-mode syntax."
9959 (interactive)
9960 (org-load-modules-maybe)
9961 (org-run-like-in-org-mode 'org-insert-link))
9963 (defun org-insert-all-links (arg &optional pre post)
9964 "Insert all links in `org-stored-links'.
9965 When a universal prefix, do not delete the links from `org-stored-links'.
9966 When `ARG' is a number, insert the last N link(s).
9967 `PRE' and `POST' are optional arguments to define a string to
9968 prepend or to append."
9969 (interactive "P")
9970 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9971 (links (copy-seq org-stored-links))
9972 (pr (or pre "- "))
9973 (po (or post "\n"))
9974 (cnt 1) l)
9975 (if (null org-stored-links)
9976 (message "No link to insert")
9977 (while (and (or (listp arg) (>= arg cnt))
9978 (setq l (if (listp arg)
9979 (pop links)
9980 (pop org-stored-links))))
9981 (setq cnt (1+ cnt))
9982 (insert pr)
9983 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9984 (insert po)))))
9986 (defun org-insert-last-stored-link (arg)
9987 "Insert the last link stored in `org-stored-links'."
9988 (interactive "p")
9989 (org-insert-all-links arg "" "\n"))
9991 (defun org-link-fontify-links-to-this-file ()
9992 "Fontify links to the current file in `org-stored-links'."
9993 (let ((f (buffer-file-name)) a b)
9994 (setq a (mapcar (lambda(l)
9995 (let ((ll (car l)))
9996 (when (and (string-match "^file:\\(.+\\)::" ll)
9997 (equal f (expand-file-name (match-string 1 ll))))
9998 ll)))
9999 org-stored-links))
10000 (when (featurep 'org-id)
10001 (setq b (mapcar (lambda(l)
10002 (let ((ll (car l)))
10003 (when (and (string-match "^id:\\(.+\\)$" ll)
10004 (equal f (expand-file-name
10005 (or (org-id-find-id-file
10006 (match-string 1 ll)) ""))))
10007 ll)))
10008 org-stored-links)))
10009 (mapcar (lambda(l)
10010 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10011 (delq nil (append a b)))))
10013 (defvar org-link-links-in-this-file nil)
10014 (defun org-insert-link (&optional complete-file link-location default-description)
10015 "Insert a link. At the prompt, enter the link.
10017 Completion can be used to insert any of the link protocol prefixes like
10018 http or ftp in use.
10020 The history can be used to select a link previously stored with
10021 `org-store-link'. When the empty string is entered (i.e. if you just
10022 press RET at the prompt), the link defaults to the most recently
10023 stored link. As SPC triggers completion in the minibuffer, you need to
10024 use M-SPC or C-q SPC to force the insertion of a space character.
10026 You will also be prompted for a description, and if one is given, it will
10027 be displayed in the buffer instead of the link.
10029 If there is already a link at point, this command will allow you to edit link
10030 and description parts.
10032 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10033 be selected using completion. The path to the file will be relative to the
10034 current directory if the file is in the current directory or a subdirectory.
10035 Otherwise, the link will be the absolute path as completed in the minibuffer
10036 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10037 option `org-link-file-path-type'.
10039 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10040 the current directory or below.
10042 With three \\[universal-argument] prefixes, negate the meaning of
10043 `org-keep-stored-link-after-insertion'.
10045 If `org-make-link-description-function' is non-nil, this function will be
10046 called with the link target, and the result will be the default
10047 link description.
10049 If the LINK-LOCATION parameter is non-nil, this value will be
10050 used as the link location instead of reading one interactively.
10052 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10053 be used as the default description."
10054 (interactive "P")
10055 (let* ((wcf (current-window-configuration))
10056 (origbuf (current-buffer))
10057 (region (if (org-region-active-p)
10058 (buffer-substring (region-beginning) (region-end))))
10059 (remove (and region (list (region-beginning) (region-end))))
10060 (desc region)
10061 tmphist ; byte-compile incorrectly complains about this
10062 (link link-location)
10063 (abbrevs org-link-abbrev-alist-local)
10064 entry file all-prefixes auto-desc)
10065 (cond
10066 (link-location) ; specified by arg, just use it.
10067 ((org-in-regexp org-bracket-link-regexp 1)
10068 ;; We do have a link at point, and we are going to edit it.
10069 (setq remove (list (match-beginning 0) (match-end 0)))
10070 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10071 (setq link (read-string "Link: "
10072 (org-link-unescape
10073 (org-match-string-no-properties 1)))))
10074 ((or (org-in-regexp org-angle-link-re)
10075 (org-in-regexp org-plain-link-re))
10076 ;; Convert to bracket link
10077 (setq remove (list (match-beginning 0) (match-end 0))
10078 link (read-string "Link: "
10079 (org-remove-angle-brackets (match-string 0)))))
10080 ((member complete-file '((4) (16)))
10081 ;; Completing read for file names.
10082 (setq link (org-file-complete-link complete-file)))
10084 ;; Read link, with completion for stored links.
10085 (org-link-fontify-links-to-this-file)
10086 (org-switch-to-buffer-other-window "*Org Links*")
10087 (with-current-buffer "*Org Links*"
10088 (erase-buffer)
10089 (insert "Insert a link.
10090 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10091 (when org-stored-links
10092 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10093 (insert (mapconcat 'org-link-prettify
10094 (reverse org-stored-links) "\n")))
10095 (goto-char (point-min)))
10096 (let ((cw (selected-window)))
10097 (select-window (get-buffer-window "*Org Links*" 'visible))
10098 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10099 (unless (pos-visible-in-window-p (point-max))
10100 (org-fit-window-to-buffer))
10101 (and (window-live-p cw) (select-window cw)))
10102 ;; Fake a link history, containing the stored links.
10103 (setq tmphist (append (mapcar 'car org-stored-links)
10104 org-insert-link-history))
10105 (setq all-prefixes (append (mapcar 'car abbrevs)
10106 (mapcar 'car org-link-abbrev-alist)
10107 org-link-types))
10108 (unwind-protect
10109 (progn
10110 (setq link
10111 (org-completing-read
10112 "Link: "
10113 (append
10114 (mapcar (lambda (x) (concat x ":"))
10115 all-prefixes)
10116 (mapcar 'car org-stored-links))
10117 nil nil nil
10118 'tmphist
10119 (caar org-stored-links)))
10120 (if (not (string-match "\\S-" link))
10121 (user-error "No link selected"))
10122 (mapc (lambda(l)
10123 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10124 org-stored-links)
10125 (if (or (member link all-prefixes)
10126 (and (equal ":" (substring link -1))
10127 (member (substring link 0 -1) all-prefixes)
10128 (setq link (substring link 0 -1))))
10129 (setq link (with-current-buffer origbuf
10130 (org-link-try-special-completion link)))))
10131 (set-window-configuration wcf)
10132 (kill-buffer "*Org Links*"))
10133 (setq entry (assoc link org-stored-links))
10134 (or entry (push link org-insert-link-history))
10135 (setq desc (or desc (nth 1 entry)))))
10137 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10138 (not org-keep-stored-link-after-insertion))
10139 (setq org-stored-links (delq (assoc link org-stored-links)
10140 org-stored-links)))
10142 (if (and (string-match org-plain-link-re link)
10143 (not (string-match org-ts-regexp link)))
10144 ;; URL-like link, normalize the use of angular brackets.
10145 (setq link (org-remove-angle-brackets link)))
10147 ;; Check if we are linking to the current file with a search
10148 ;; option If yes, simplify the link by using only the search
10149 ;; option.
10150 (when (and buffer-file-name
10151 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10152 (let* ((path (match-string 1 link))
10153 (case-fold-search nil)
10154 (search (match-string 2 link)))
10155 (save-match-data
10156 (if (equal (file-truename buffer-file-name) (file-truename path))
10157 ;; We are linking to this same file, with a search option
10158 (setq link search)))))
10160 ;; Check if we can/should use a relative path. If yes, simplify the link
10161 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10162 (let* ((type (match-string 1 link))
10163 (path (match-string 2 link))
10164 (origpath path)
10165 (case-fold-search nil))
10166 (cond
10167 ((or (eq org-link-file-path-type 'absolute)
10168 (equal complete-file '(16)))
10169 (setq path (abbreviate-file-name (expand-file-name path))))
10170 ((eq org-link-file-path-type 'noabbrev)
10171 (setq path (expand-file-name path)))
10172 ((eq org-link-file-path-type 'relative)
10173 (setq path (file-relative-name path)))
10175 (save-match-data
10176 (if (string-match (concat "^" (regexp-quote
10177 (expand-file-name
10178 (file-name-as-directory
10179 default-directory))))
10180 (expand-file-name path))
10181 ;; We are linking a file with relative path name.
10182 (setq path (substring (expand-file-name path)
10183 (match-end 0)))
10184 (setq path (abbreviate-file-name (expand-file-name path)))))))
10185 (setq link (concat type path))
10186 (if (equal desc origpath)
10187 (setq desc path))))
10189 (if org-make-link-description-function
10190 (setq desc
10191 (or (condition-case nil
10192 (funcall org-make-link-description-function link desc)
10193 (error (progn (message "Can't get link description from `%s'"
10194 (symbol-name org-make-link-description-function))
10195 (sit-for 2) nil)))
10196 (read-string "Description: " default-description)))
10197 (if default-description (setq desc default-description)
10198 (setq desc (or (and auto-desc desc)
10199 (read-string "Description: " desc)))))
10201 (unless (string-match "\\S-" desc) (setq desc nil))
10202 (if remove (apply 'delete-region remove))
10203 (insert (org-make-link-string link desc))))
10205 (defun org-link-try-special-completion (type)
10206 "If there is completion support for link type TYPE, offer it."
10207 (let ((fun (intern (concat "org-" type "-complete-link"))))
10208 (if (functionp fun)
10209 (funcall fun)
10210 (read-string "Link (no completion support): " (concat type ":")))))
10212 (defun org-file-complete-link (&optional arg)
10213 "Create a file link using completion."
10214 (let (file link)
10215 (setq file (org-iread-file-name "File: "))
10216 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10217 (pwd1 (file-name-as-directory (abbreviate-file-name
10218 (expand-file-name ".")))))
10219 (cond
10220 ((equal arg '(16))
10221 (setq link (concat
10222 "file:"
10223 (abbreviate-file-name (expand-file-name file)))))
10224 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10225 (setq link (concat "file:" (match-string 1 file))))
10226 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10227 (expand-file-name file))
10228 (setq link (concat
10229 "file:" (match-string 1 (expand-file-name file)))))
10230 (t (setq link (concat "file:" file)))))
10231 link))
10233 (defun org-iread-file-name (&rest args)
10234 "Read-file-name using `ido-mode' speedup if available.
10235 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10236 See `read-file-name' for a description of parameters."
10237 (org-without-partial-completion
10238 (if (and org-completion-use-ido
10239 (fboundp 'ido-read-file-name)
10240 (boundp 'ido-mode) ido-mode
10241 (listp (second args)))
10242 (let ((ido-enter-matching-directory nil))
10243 (apply 'ido-read-file-name args))
10244 (apply 'read-file-name args))))
10246 (defun org-completing-read (&rest args)
10247 "Completing-read with SPACE being a normal character."
10248 (let ((enable-recursive-minibuffers t)
10249 (minibuffer-local-completion-map
10250 (copy-keymap minibuffer-local-completion-map)))
10251 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10252 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10253 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10254 (apply 'org-icompleting-read args)))
10256 (defun org-completing-read-no-i (&rest args)
10257 (let (org-completion-use-ido org-completion-use-iswitchb)
10258 (apply 'org-completing-read args)))
10260 (defun org-iswitchb-completing-read (prompt choices &rest args)
10261 "Use iswitch as a completing-read replacement to choose from choices.
10262 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10263 from."
10264 (let* ((iswitchb-use-virtual-buffers nil)
10265 (iswitchb-make-buflist-hook
10266 (lambda ()
10267 (setq iswitchb-temp-buflist choices))))
10268 (iswitchb-read-buffer prompt)))
10270 (defun org-icompleting-read (&rest args)
10271 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10272 (org-without-partial-completion
10273 (if (and org-completion-use-ido
10274 (fboundp 'ido-completing-read)
10275 (boundp 'ido-mode) ido-mode
10276 (listp (second args)))
10277 (let ((ido-enter-matching-directory nil))
10278 (apply 'ido-completing-read (concat (car args))
10279 (if (consp (car (nth 1 args)))
10280 (mapcar 'car (nth 1 args))
10281 (nth 1 args))
10282 (cddr args)))
10283 (if (and org-completion-use-iswitchb
10284 (boundp 'iswitchb-mode) iswitchb-mode
10285 (listp (second args)))
10286 (apply 'org-iswitchb-completing-read (concat (car args))
10287 (if (consp (car (nth 1 args)))
10288 (mapcar 'car (nth 1 args))
10289 (nth 1 args))
10290 (cddr args))
10291 (apply 'completing-read args)))))
10293 (defun org-extract-attributes (s)
10294 "Extract the attributes cookie from a string and set as text property."
10295 (let (a attr (start 0) key value)
10296 (save-match-data
10297 (when (string-match "{{\\([^}]+\\)}}$" s)
10298 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10299 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10300 (setq key (match-string 1 a) value (match-string 2 a)
10301 start (match-end 0)
10302 attr (plist-put attr (intern key) value))))
10303 (org-add-props s nil 'org-attr attr))
10306 ;;; Opening/following a link
10308 (defvar org-link-search-failed nil)
10310 (defvar org-open-link-functions nil
10311 "Hook for functions finding a plain text link.
10312 These functions must take a single argument, the link content.
10313 They will be called for links that look like [[link text][description]]
10314 when LINK TEXT does not have a protocol like \"http:\" and does not look
10315 like a filename (e.g. \"./blue.png\").
10317 These functions will be called *before* Org attempts to resolve the
10318 link by doing text searches in the current buffer - so if you want a
10319 link \"[[target]]\" to still find \"<<target>>\", your function should
10320 handle this as a special case.
10322 When the function does handle the link, it must return a non-nil value.
10323 If it decides that it is not responsible for this link, it must return
10324 nil to indicate that that Org-mode can continue with other options
10325 like exact and fuzzy text search.")
10327 (defun org-next-link (&optional search-backward)
10328 "Move forward to the next link.
10329 If the link is in hidden text, expose it."
10330 (interactive "P")
10331 (when (and org-link-search-failed (eq this-command last-command))
10332 (goto-char (point-min))
10333 (message "Link search wrapped back to beginning of buffer"))
10334 (setq org-link-search-failed nil)
10335 (let* ((pos (point))
10336 (ct (org-context))
10337 (a (assoc :link ct))
10338 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10339 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10340 ((looking-at org-any-link-re)
10341 ;; Don't stay stuck at link without an org-link face
10342 (forward-char (if search-backward -1 1))))
10343 (if (funcall srch-fun org-any-link-re nil t)
10344 (progn
10345 (goto-char (match-beginning 0))
10346 (if (outline-invisible-p) (org-show-context)))
10347 (goto-char pos)
10348 (setq org-link-search-failed t)
10349 (message "No further link found"))))
10351 (defun org-previous-link ()
10352 "Move backward to the previous link.
10353 If the link is in hidden text, expose it."
10354 (interactive)
10355 (funcall 'org-next-link t))
10357 (defun org-translate-link (s)
10358 "Translate a link string if a translation function has been defined."
10359 (if (and org-link-translation-function
10360 (fboundp org-link-translation-function)
10361 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10362 (progn
10363 (setq s (funcall org-link-translation-function
10364 (match-string 1 s) (match-string 2 s)))
10365 (concat (car s) ":" (cdr s)))
10368 (defun org-translate-link-from-planner (type path)
10369 "Translate a link from Emacs Planner syntax so that Org can follow it.
10370 This is still an experimental function, your mileage may vary."
10371 (cond
10372 ((member type '("http" "https" "news" "ftp"))
10373 ;; standard Internet links are the same.
10374 nil)
10375 ((and (equal type "irc") (string-match "^//" path))
10376 ;; Planner has two / at the beginning of an irc link, we have 1.
10377 ;; We should have zero, actually....
10378 (setq path (substring path 1)))
10379 ((and (equal type "lisp") (string-match "^/" path))
10380 ;; Planner has a slash, we do not.
10381 (setq type "elisp" path (substring path 1)))
10382 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10383 ;; A typical message link. Planner has the id after the final slash,
10384 ;; we separate it with a hash mark
10385 (setq path (concat (match-string 1 path) "#"
10386 (org-remove-angle-brackets (match-string 2 path))))))
10387 (cons type path))
10389 (defun org-find-file-at-mouse (ev)
10390 "Open file link or URL at mouse."
10391 (interactive "e")
10392 (mouse-set-point ev)
10393 (org-open-at-point 'in-emacs))
10395 (defun org-open-at-mouse (ev)
10396 "Open file link or URL at mouse.
10397 See the docstring of `org-open-file' for details."
10398 (interactive "e")
10399 (mouse-set-point ev)
10400 (if (eq major-mode 'org-agenda-mode)
10401 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10402 (org-open-at-point))
10404 (defvar org-window-config-before-follow-link nil
10405 "The window configuration before following a link.
10406 This is saved in case the need arises to restore it.")
10408 (defvar org-open-link-marker (make-marker)
10409 "Marker pointing to the location where `org-open-at-point' was called.")
10411 ;;;###autoload
10412 (defun org-open-at-point-global ()
10413 "Follow a link like Org-mode does.
10414 This command can be called in any mode to follow a link that has
10415 Org-mode syntax."
10416 (interactive)
10417 (org-run-like-in-org-mode 'org-open-at-point))
10419 ;;;###autoload
10420 (defun org-open-link-from-string (s &optional arg reference-buffer)
10421 "Open a link in the string S, as if it was in Org-mode."
10422 (interactive "sLink: \nP")
10423 (let ((reference-buffer (or reference-buffer (current-buffer))))
10424 (with-temp-buffer
10425 (let ((org-inhibit-startup (not reference-buffer)))
10426 (org-mode)
10427 (insert s)
10428 (goto-char (point-min))
10429 (when reference-buffer
10430 (setq org-link-abbrev-alist-local
10431 (with-current-buffer reference-buffer
10432 org-link-abbrev-alist-local)))
10433 (org-open-at-point arg reference-buffer)))))
10435 (defvar org-open-at-point-functions nil
10436 "Hook that is run when following a link at point.
10438 Functions in this hook must return t if they identify and follow
10439 a link at point. If they don't find anything interesting at point,
10440 they must return nil.")
10442 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10443 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10444 (defun org-open-at-point (&optional arg reference-buffer)
10445 "Open link, timestamp, footnote or tags at point.
10447 When point is on a link, follow it. Normally, files will be
10448 opened by an appropriate application. If the optional prefix
10449 argument ARG is non-nil, Emacs will visit the file. With
10450 a double prefix argument, try to open outside of Emacs, in the
10451 application the system uses for this file type.
10453 When point is on a timestamp, open the agenda at the day
10454 specified.
10456 When point is a footnote definition, move to the first reference
10457 found. If it is on a reference, move to the associated
10458 definition.
10460 When point is on a headline, display a list of every link in the
10461 entry, so it is possible to pick one, or all, of them. If point
10462 is on a tag, call `org-tags-view' instead.
10464 When optional argument REFERENCE-BUFFER is non-nil, it should
10465 specify a buffer from where the link search should happen. This
10466 is used internally by `org-open-link-from-string'."
10467 (interactive "P")
10468 ;; On a code block, open block's results.
10469 (unless (call-interactively #'org-babel-open-src-block-result)
10470 (org-load-modules-maybe)
10471 (move-marker org-open-link-marker (point))
10472 (setq org-window-config-before-follow-link (current-window-configuration))
10473 (org-remove-occur-highlights nil nil t)
10474 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10475 (let* ((context (org-element-context)) type)
10476 ;; On an unsupported type, check if point is contained within
10477 ;; a support one.
10478 (while (and (not (memq (setq type (org-element-type context))
10479 '(headline inlinetask link footnote-definition
10480 footnote-reference timestamp)))
10481 (setq context (org-element-property :parent context))))
10482 (cond
10483 ((not context) (user-error "No link found"))
10484 ;; On a headline or an inlinetask, but not on a timestamp,
10485 ;; a link, a footnote reference or on tags.
10486 ((and (memq type '(headline inlinetask))
10487 ;; Not on tags.
10488 (progn (save-excursion (beginning-of-line)
10489 (looking-at org-complex-heading-regexp))
10490 (or (not (match-beginning 5))
10491 (< (point) (match-beginning 5)))))
10492 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10493 (links (car data))
10494 (links-end (cdr data)))
10495 (if links
10496 (dolist (link (if (stringp links) (list links) links))
10497 (search-forward link nil links-end)
10498 (goto-char (match-beginning 0))
10499 (org-open-at-point))
10500 (require 'org-attach)
10501 (org-attach-reveal 'if-exists))))
10502 ;; Do nothing on white spaces after an object.
10503 ((let ((end (org-element-property :end context)))
10504 (= (save-excursion
10505 ;; Make sure we're not on invisible text, as it would
10506 ;; make the check unpredictable on object's borders.
10507 (when (invisible-p (point))
10508 (goto-char
10509 (next-single-property-change (point) 'invisible nil end)))
10510 (skip-chars-forward " \t" end) (point))
10511 end))
10512 (user-error "No link found"))
10513 ((eq type 'timestamp) (org-follow-timestamp-link))
10514 ;; On tags within a headline or an inlinetask.
10515 ((and (memq type '(headline inlinetask))
10516 (progn (save-excursion (beginning-of-line)
10517 (looking-at org-complex-heading-regexp))
10518 (and (match-beginning 5)
10519 (>= (point) (match-beginning 5)))))
10520 (org-tags-view arg (substring (match-string 5) 0 -1)))
10521 ((eq type 'link)
10522 (let ((type (org-element-property :type context))
10523 (path (org-element-property :path context)))
10524 ;; Switch back to REFERENCE-BUFFER needed when called in
10525 ;; a temporary buffer through `org-open-link-from-string'.
10526 (with-current-buffer (or reference-buffer (current-buffer))
10527 (cond
10528 ((equal type "file")
10529 (if (string-match "[*?{]" (file-name-nondirectory path))
10530 (dired path)
10531 (apply
10532 (or (let ((app (org-element-property :application context)))
10533 (nth 1 (assoc (concat "file" (and app (concat "+" app)))
10534 org-link-protocols)))
10535 #'org-open-file)
10536 path arg
10537 (let ((option (org-element-property :search-option context)))
10538 (cond ((not option) nil)
10539 ((org-string-match-p "\\`[0-9]+\\'" option)
10540 (list (string-to-number option)))
10541 (t (list nil option)))))))
10542 ((assoc type org-link-protocols)
10543 (funcall (nth 1 (assoc type org-link-protocols)) path))
10544 ((equal type "help")
10545 (let ((f-or-v (intern path)))
10546 (cond ((fboundp f-or-v) (describe-function f-or-v))
10547 ((boundp f-or-v) (describe-variable f-or-v))
10548 (t (error "Not a known function or variable")))))
10549 ((equal type "mailto")
10550 (let ((cmd (car org-link-mailto-program))
10551 (args (cdr org-link-mailto-program))
10552 (spec
10553 (format-spec-make
10554 ?a path ; %a is address.
10555 ?s (let ((option ; %s is subject.
10556 (org-element-property
10557 :search-option context)))
10558 (if (not option) "" (org-link-escape option)))))
10559 final-args)
10560 (apply cmd
10561 (dolist (arg args (nreverse final-args))
10562 (if (not (stringp arg)) (push arg final-args)
10563 (push (format-spec arg spec) final-args))))))
10564 ((member type '("http" "https" "ftp" "news"))
10565 (browse-url (org-link-escape-browser (concat type ":" path))))
10566 ((equal type "doi")
10567 (browse-url
10568 (org-link-escape-browser (concat org-doi-server-url path))))
10569 ((equal type "message") (browse-url (concat type ":" path)))
10570 ((equal type "shell")
10571 (let ((buf (generate-new-buffer "*Org Shell Output"))
10572 (cmd path))
10573 (if (or (and (org-string-nw-p
10574 org-confirm-shell-link-not-regexp)
10575 (string-match
10576 org-confirm-shell-link-not-regexp cmd))
10577 (not org-confirm-shell-link-function)
10578 (funcall org-confirm-shell-link-function
10579 (format "Execute \"%s\" in shell? "
10580 (org-add-props cmd nil
10581 'face 'org-warning))))
10582 (progn
10583 (message "Executing %s" cmd)
10584 (shell-command cmd buf)
10585 (when (featurep 'midnight)
10586 (setq clean-buffer-list-kill-buffer-names
10587 (cons buf
10588 clean-buffer-list-kill-buffer-names))))
10589 (error "Abort"))))
10590 ((equal type "elisp")
10591 (let ((cmd path))
10592 (if (or (and (org-string-nw-p
10593 org-confirm-elisp-link-not-regexp)
10594 (org-string-match-p
10595 org-confirm-elisp-link-not-regexp cmd))
10596 (not org-confirm-elisp-link-function)
10597 (funcall org-confirm-elisp-link-function
10598 (format "Execute \"%s\" as elisp? "
10599 (org-add-props cmd nil
10600 'face 'org-warning))))
10601 (message "%s => %s" cmd
10602 (if (eq (string-to-char cmd) ?\()
10603 (eval (read cmd))
10604 (call-interactively (read cmd))))
10605 (error "Abort"))))
10606 ((equal type "id")
10607 (require 'ord-id)
10608 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10609 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10610 (unless (run-hook-with-args-until-success
10611 'org-open-link-functions path)
10612 (if (not arg) (org-mark-ring-push)
10613 (switch-to-buffer-other-window
10614 (org-get-buffer-for-internal-link (current-buffer))))
10615 (let ((cmd `(org-link-search
10616 ,(org-element-property :raw-link context)
10617 ,(cond ((equal arg '(4)) ''occur)
10618 ((equal arg '(16)) ''org-occur))
10619 ,(org-element-property :begin context))))
10620 (condition-case nil
10621 (let ((org-link-search-inhibit-query t))
10622 (eval cmd))
10623 (error (progn (widen) (eval cmd)))))))
10624 (t (browse-url-at-point))))))
10625 ;; On a footnote reference or at a footnote definition's label.
10626 ((or (eq type 'footnote-reference)
10627 (and (eq type 'footnote-definition)
10628 (save-excursion
10629 ;; Do not validate action when point is on the
10630 ;; spaces right after the footnote label, in
10631 ;; order to be on par with behaviour on links.
10632 (skip-chars-forward " \t")
10633 (let ((begin
10634 (org-element-property :contents-begin context)))
10635 (if begin (< (point) begin)
10636 (= (org-element-property :post-affiliated context)
10637 (line-beginning-position)))))))
10638 (org-footnote-action))
10639 (t (user-error "No link found")))))
10640 (move-marker org-open-link-marker nil)
10641 (run-hook-with-args 'org-follow-link-hook)))
10643 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10644 "Offer links in the current entry and return the selected link.
10645 If there is only one link, return it.
10646 If NTH is an integer, return the NTH link found.
10647 If ZERO is a string, check also this string for a link, and if
10648 there is one, return it."
10649 (with-current-buffer buffer
10650 (save-excursion
10651 (save-restriction
10652 (widen)
10653 (goto-char marker)
10654 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10655 "\\(" org-angle-link-re "\\)\\|"
10656 "\\(" org-plain-link-re "\\)"))
10657 (cnt ?0)
10658 (in-emacs (if (integerp nth) nil nth))
10659 have-zero end links link c)
10660 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10661 (push (match-string 0 zero) links)
10662 (setq cnt (1- cnt) have-zero t))
10663 (save-excursion
10664 (org-back-to-heading t)
10665 (setq end (save-excursion (outline-next-heading) (point)))
10666 (while (re-search-forward re end t)
10667 (push (match-string 0) links))
10668 (setq links (org-uniquify (reverse links))))
10669 (cond
10670 ((null links)
10671 (message "No links"))
10672 ((equal (length links) 1)
10673 (setq link (car links)))
10674 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10675 (setq link (nth (if have-zero nth (1- nth)) links)))
10676 (t ; we have to select a link
10677 (save-excursion
10678 (save-window-excursion
10679 (delete-other-windows)
10680 (with-output-to-temp-buffer "*Select Link*"
10681 (mapc (lambda (l)
10682 (if (not (string-match org-bracket-link-regexp l))
10683 (princ (format "[%c] %s\n" (incf cnt)
10684 (org-remove-angle-brackets l)))
10685 (if (match-end 3)
10686 (princ (format "[%c] %s (%s)\n" (incf cnt)
10687 (match-string 3 l) (match-string 1 l)))
10688 (princ (format "[%c] %s\n" (incf cnt)
10689 (match-string 1 l))))))
10690 links))
10691 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10692 (message "Select link to open, RET to open all:")
10693 (setq c (read-char-exclusive))
10694 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10695 (when (equal c ?q) (error "Abort"))
10696 (if (equal c ?\C-m)
10697 (setq link links)
10698 (setq nth (- c ?0))
10699 (if have-zero (setq nth (1+ nth)))
10700 (unless (and (integerp nth) (>= (length links) nth))
10701 (user-error "Invalid link selection"))
10702 (setq link (nth (1- nth) links)))))
10703 (cons link end))))))
10705 ;; Add special file links that specify the way of opening
10707 (org-add-link-type "file+sys" 'org-open-file-with-system)
10708 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10709 (defun org-open-file-with-system (path &optional arg line search)
10710 "Open file at PATH using the system way of opening it.
10711 Optional argument ARG is ignored. See `org-open-file' for LINE
10712 and SEARCH arguments."
10713 (org-open-file path 'system line search))
10714 (defun org-open-file-with-emacs (path &optional arg line search)
10715 "Open file at PATH in Emacs.
10716 Optional argument ARG is ignored. See `org-open-file' for LINE
10717 and SEARCH arguments."
10718 (org-open-file path 'emacs line search))
10721 ;;; File search
10723 (defvar org-create-file-search-functions nil
10724 "List of functions to construct the right search string for a file link.
10725 These functions are called in turn with point at the location to
10726 which the link should point.
10728 A function in the hook should first test if it would like to
10729 handle this file type, for example by checking the `major-mode'
10730 or the file extension. If it decides not to handle this file, it
10731 should just return nil to give other functions a chance. If it
10732 does handle the file, it must return the search string to be used
10733 when following the link. The search string will be part of the
10734 file link, given after a double colon, and `org-open-at-point'
10735 will automatically search for it. If special measures must be
10736 taken to make the search successful, another function should be
10737 added to the companion hook `org-execute-file-search-functions',
10738 which see.
10740 A function in this hook may also use `setq' to set the variable
10741 `description' to provide a suggestion for the descriptive text to
10742 be used for this link when it gets inserted into an Org-mode
10743 buffer with \\[org-insert-link].")
10745 (defvar org-execute-file-search-functions nil
10746 "List of functions to execute a file search triggered by a link.
10748 Functions added to this hook must accept a single argument, the
10749 search string that was part of the file link, the part after the
10750 double colon. The function must first check if it would like to
10751 handle this search, for example by checking the `major-mode' or
10752 the file extension. If it decides not to handle this search, it
10753 should just return nil to give other functions a chance. If it
10754 does handle the search, it must return a non-nil value to keep
10755 other functions from trying.
10757 Each function can access the current prefix argument through the
10758 variable `current-prefix-arg'. Note that a single prefix is used
10759 to force opening a link in Emacs, so it may be good to only use a
10760 numeric or double prefix to guide the search function.
10762 In case this is needed, a function in this hook can also restore
10763 the window configuration before `org-open-at-point' was called using:
10765 (set-window-configuration org-window-config-before-follow-link)")
10767 (defun org-link-search (s &optional type avoid-pos stealth)
10768 "Search for a link search option.
10769 If S is surrounded by forward slashes, it is interpreted as a
10770 regular expression. In org-mode files, this will create an `org-occur'
10771 sparse tree. In ordinary files, `occur' will be used to list matches.
10772 If the current buffer is in `dired-mode', grep will be used to search
10773 in all files. If AVOID-POS is given, ignore matches near that position.
10775 When optional argument STEALTH is non-nil, do not modify
10776 visibility around point, thus ignoring
10777 `org-show-hierarchy-above', `org-show-following-heading' and
10778 `org-show-siblings' variables."
10779 (let ((case-fold-search t)
10780 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10781 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10782 (append '(("") (" ") ("\t") ("\n"))
10783 org-emphasis-alist)
10784 "\\|") "\\)"))
10785 (pos (point))
10786 (pre nil) (post nil)
10787 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10788 (cond
10789 ;; First check if there are any special search functions
10790 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10791 ;; Now try the builtin stuff
10792 ((and (equal (string-to-char s0) ?#)
10793 (> (length s0) 1)
10794 (save-excursion
10795 (goto-char (point-min))
10796 (and
10797 (re-search-forward
10798 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10799 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10800 (setq type 'dedicated
10801 pos (match-beginning 0))))
10802 ;; There is an exact target for this
10803 (goto-char pos)
10804 (org-back-to-heading t)))
10805 ((save-excursion
10806 (goto-char (point-min))
10807 (and
10808 (re-search-forward
10809 (concat "<<" (regexp-quote s0) ">>") nil t)
10810 (setq type 'dedicated
10811 pos (match-beginning 0))))
10812 ;; There is an exact target for this
10813 (goto-char pos))
10814 ((save-excursion
10815 (goto-char (point-min))
10816 (and
10817 (re-search-forward
10818 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10819 (setq type 'dedicated pos (match-beginning 0))))
10820 ;; Found an element with a matching #+name affiliated keyword.
10821 (goto-char pos))
10822 ((and (string-match "^(\\(.*\\))$" s0)
10823 (save-excursion
10824 (goto-char (point-min))
10825 (and
10826 (re-search-forward
10827 (concat "[^[]" (regexp-quote
10828 (format org-coderef-label-format
10829 (match-string 1 s0))))
10830 nil t)
10831 (setq type 'dedicated
10832 pos (1+ (match-beginning 0))))))
10833 ;; There is a coderef target for this
10834 (goto-char pos))
10835 ((string-match "^/\\(.*\\)/$" s)
10836 ;; A regular expression
10837 (cond
10838 ((derived-mode-p 'org-mode)
10839 (org-occur (match-string 1 s)))
10840 (t (org-do-occur (match-string 1 s)))))
10841 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10842 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10843 (goto-char (point-min))
10844 (cond
10845 ((let (case-fold-search)
10846 (re-search-forward (format org-complex-heading-regexp-format
10847 (regexp-quote s))
10848 nil t))
10849 ;; OK, found a match
10850 (setq type 'dedicated)
10851 (goto-char (match-beginning 0)))
10852 ((and (not org-link-search-inhibit-query)
10853 (eq org-link-search-must-match-exact-headline 'query-to-create)
10854 (y-or-n-p "No match - create this as a new heading? "))
10855 (goto-char (point-max))
10856 (or (bolp) (newline))
10857 (insert "* " s "\n")
10858 (beginning-of-line 0))
10860 (goto-char pos)
10861 (error "No match"))))
10863 ;; A normal search string
10864 (when (equal (string-to-char s) ?*)
10865 ;; Anchor on headlines, post may include tags.
10866 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10867 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10868 s (substring s 1)))
10869 (remove-text-properties
10870 0 (length s)
10871 '(face nil mouse-face nil keymap nil fontified nil) s)
10872 ;; Make a series of regular expressions to find a match
10873 (setq words (org-split-string s "[ \n\r\t]+")
10875 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10876 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10877 "\\)" markers)
10878 re2a_ (concat "\\(" (mapconcat 'downcase words
10879 "[ \t\r\n]+") "\\)[ \t\r\n]")
10880 re2a (concat "[ \t\r\n]" re2a_)
10881 re4_ (concat "\\(" (mapconcat 'downcase words
10882 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10883 re4 (concat "[^a-zA-Z_]" re4_)
10885 re1 (concat pre re2 post)
10886 re3 (concat pre (if pre re4_ re4) post)
10887 re5 (concat pre ".*" re4)
10888 re2 (concat pre re2)
10889 re2a (concat pre (if pre re2a_ re2a))
10890 re4 (concat pre (if pre re4_ re4))
10891 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10892 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10893 re5 "\\)"))
10894 (cond
10895 ((eq type 'org-occur) (org-occur reall))
10896 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10897 (t (goto-char (point-min))
10898 (setq type 'fuzzy)
10899 (if (or (and (org-search-not-self 1 re0 nil t)
10900 (setq type 'dedicated))
10901 (org-search-not-self 1 re1 nil t)
10902 (org-search-not-self 1 re2 nil t)
10903 (org-search-not-self 1 re2a nil t)
10904 (org-search-not-self 1 re3 nil t)
10905 (org-search-not-self 1 re4 nil t)
10906 (org-search-not-self 1 re5 nil t))
10907 (goto-char (match-beginning 1))
10908 (goto-char pos)
10909 (error "No match"))))))
10910 (and (derived-mode-p 'org-mode)
10911 (not stealth)
10912 (org-show-context 'link-search))
10913 type))
10915 (defun org-search-not-self (group &rest args)
10916 "Execute `re-search-forward', but only accept matches that do not
10917 enclose the position of `org-open-link-marker'."
10918 (let ((m org-open-link-marker))
10919 (catch 'exit
10920 (while (apply 're-search-forward args)
10921 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10922 (goto-char (match-end group))
10923 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10924 (> (match-beginning 0) (marker-position m))
10925 (< (match-end 0) (marker-position m)))
10926 (save-match-data
10927 (or (not (org-in-regexp
10928 org-bracket-link-analytic-regexp 1))
10929 (not (match-end 4)) ; no description
10930 (and (<= (match-beginning 4) (point))
10931 (>= (match-end 4) (point))))))
10932 (throw 'exit (point))))))))
10934 (defun org-get-buffer-for-internal-link (buffer)
10935 "Return a buffer to be used for displaying the link target of internal links."
10936 (cond
10937 ((not org-display-internal-link-with-indirect-buffer)
10938 buffer)
10939 ((string-match "(Clone)$" (buffer-name buffer))
10940 (message "Buffer is already a clone, not making another one")
10941 ;; we also do not modify visibility in this case
10942 buffer)
10943 (t ; make a new indirect buffer for displaying the link
10944 (let* ((bn (buffer-name buffer))
10945 (ibn (concat bn "(Clone)"))
10946 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10947 (with-current-buffer ib (org-overview))
10948 ib))))
10950 (defun org-do-occur (regexp &optional cleanup)
10951 "Call the Emacs command `occur'.
10952 If CLEANUP is non-nil, remove the printout of the regular expression
10953 in the *Occur* buffer. This is useful if the regex is long and not useful
10954 to read."
10955 (occur regexp)
10956 (when cleanup
10957 (let ((cwin (selected-window)) win beg end)
10958 (when (setq win (get-buffer-window "*Occur*"))
10959 (select-window win))
10960 (goto-char (point-min))
10961 (when (re-search-forward "match[a-z]+" nil t)
10962 (setq beg (match-end 0))
10963 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10964 (setq end (1- (match-beginning 0)))))
10965 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10966 (goto-char (point-min))
10967 (select-window cwin))))
10969 ;;; The mark ring for links jumps
10971 (defvar org-mark-ring nil
10972 "Mark ring for positions before jumps in Org-mode.")
10973 (defvar org-mark-ring-last-goto nil
10974 "Last position in the mark ring used to go back.")
10975 ;; Fill and close the ring
10976 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10977 (loop for i from 1 to org-mark-ring-length do
10978 (push (make-marker) org-mark-ring))
10979 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10980 org-mark-ring)
10982 (defun org-mark-ring-push (&optional pos buffer)
10983 "Put the current position or POS into the mark ring and rotate it."
10984 (interactive)
10985 (setq pos (or pos (point)))
10986 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10987 (move-marker (car org-mark-ring)
10988 (or pos (point))
10989 (or buffer (current-buffer)))
10990 (message "%s"
10991 (substitute-command-keys
10992 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10994 (defun org-mark-ring-goto (&optional n)
10995 "Jump to the previous position in the mark ring.
10996 With prefix arg N, jump back that many stored positions. When
10997 called several times in succession, walk through the entire ring.
10998 Org-mode commands jumping to a different position in the current file,
10999 or to another Org-mode file, automatically push the old position
11000 onto the ring."
11001 (interactive "p")
11002 (let (p m)
11003 (if (eq last-command this-command)
11004 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11005 (setq p org-mark-ring))
11006 (setq org-mark-ring-last-goto p)
11007 (setq m (car p))
11008 (org-pop-to-buffer-same-window (marker-buffer m))
11009 (goto-char m)
11010 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11012 (defun org-remove-angle-brackets (s)
11013 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11014 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11016 (defun org-add-angle-brackets (s)
11017 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11018 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11020 (defun org-remove-double-quotes (s)
11021 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11022 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11025 ;;; Following specific links
11027 (defun org-follow-timestamp-link ()
11028 "Open an agenda view for the time-stamp date/range at point."
11029 (cond
11030 ((org-at-date-range-p t)
11031 (let ((org-agenda-start-on-weekday)
11032 (t1 (match-string 1))
11033 (t2 (match-string 2)) tt1 tt2)
11034 (setq tt1 (time-to-days (org-time-string-to-time t1))
11035 tt2 (time-to-days (org-time-string-to-time t2)))
11036 (let ((org-agenda-buffer-tmp-name
11037 (format "*Org Agenda(a:%s)"
11038 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11039 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11040 ((org-at-timestamp-p t)
11041 (let ((org-agenda-buffer-tmp-name
11042 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11043 (org-agenda-list nil (time-to-days (org-time-string-to-time
11044 (substring (match-string 1) 0 10)))
11045 1)))
11046 (t (error "This should not happen"))))
11049 ;;; Following file links
11050 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11051 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11052 (declare-function mailcap-mime-info
11053 "mailcap" (string &optional request no-decode))
11054 (defvar org-wait nil)
11055 (defun org-open-file (path &optional in-emacs line search)
11056 "Open the file at PATH.
11057 First, this expands any special file name abbreviations. Then the
11058 configuration variable `org-file-apps' is checked if it contains an
11059 entry for this file type, and if yes, the corresponding command is launched.
11061 If no application is found, Emacs simply visits the file.
11063 With optional prefix argument IN-EMACS, Emacs will visit the file.
11064 With a double \\[universal-argument] \\[universal-argument] \
11065 prefix arg, Org tries to avoid opening in Emacs
11066 and to use an external application to visit the file.
11068 Optional LINE specifies a line to go to, optional SEARCH a string
11069 to search for. If LINE or SEARCH is given, the file will be
11070 opened in Emacs, unless an entry from org-file-apps that makes
11071 use of groups in a regexp matches.
11073 If you want to change the way frames are used when following a
11074 link, please customize `org-link-frame-setup'.
11076 If the file does not exist, an error is thrown."
11077 (let* ((file (if (equal path "")
11078 buffer-file-name
11079 (substitute-in-file-name (expand-file-name path))))
11080 (file-apps (append org-file-apps (org-default-apps)))
11081 (apps (org-remove-if
11082 'org-file-apps-entry-match-against-dlink-p file-apps))
11083 (apps-dlink (org-remove-if-not
11084 'org-file-apps-entry-match-against-dlink-p file-apps))
11085 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11086 (dirp (if remp nil (file-directory-p file)))
11087 (file (if (and dirp org-open-directory-means-index-dot-org)
11088 (concat (file-name-as-directory file) "index.org")
11089 file))
11090 (a-m-a-p (assq 'auto-mode apps))
11091 (dfile (downcase file))
11092 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11093 (link (cond ((and (eq line nil)
11094 (eq search nil))
11095 file)
11096 (line
11097 (concat file "::" (number-to-string line)))
11098 (search
11099 (concat file "::" search))))
11100 (dlink (downcase link))
11101 (old-buffer (current-buffer))
11102 (old-pos (point))
11103 (old-mode major-mode)
11104 ext cmd link-match-data)
11105 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11106 (setq ext (match-string 1 dfile))
11107 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11108 (setq ext (match-string 1 dfile))))
11109 (cond
11110 ((member in-emacs '((16) system))
11111 (setq cmd (cdr (assoc 'system apps))))
11112 (in-emacs (setq cmd 'emacs))
11114 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11115 (and dirp (cdr (assoc 'directory apps)))
11116 ; first, try matching against apps-dlink
11117 ; if we get a match here, store the match data for later
11118 (let ((match (assoc-default dlink apps-dlink
11119 'string-match)))
11120 (if match
11121 (progn (setq link-match-data (match-data))
11122 match)
11123 (progn (setq in-emacs (or in-emacs line search))
11124 nil))) ; if we have no match in apps-dlink,
11125 ; always open the file in emacs if line or search
11126 ; is given (for backwards compatibility)
11127 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11128 'string-match)
11129 (cdr (assoc ext apps))
11130 (cdr (assoc t apps))))))
11131 (when (eq cmd 'system)
11132 (setq cmd (cdr (assoc 'system apps))))
11133 (when (eq cmd 'default)
11134 (setq cmd (cdr (assoc t apps))))
11135 (when (eq cmd 'mailcap)
11136 (require 'mailcap)
11137 (mailcap-parse-mailcaps)
11138 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11139 (command (mailcap-mime-info mime-type)))
11140 (if (stringp command)
11141 (setq cmd command)
11142 (setq cmd 'emacs))))
11143 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11144 (not (file-exists-p file))
11145 (not org-open-non-existing-files))
11146 (user-error "No such file: %s" file))
11147 (cond
11148 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11149 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11150 (while (string-match "['\"]%s['\"]" cmd)
11151 (setq cmd (replace-match "%s" t t cmd)))
11152 (while (string-match "%s" cmd)
11153 (setq cmd (replace-match
11154 (save-match-data
11155 (shell-quote-argument
11156 (convert-standard-filename file)))
11157 t t cmd)))
11159 ;; Replace "%1", "%2" etc. in command with group matches from regex
11160 (save-match-data
11161 (let ((match-index 1)
11162 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11163 (set-match-data link-match-data)
11164 (while (<= match-index number-of-groups)
11165 (let ((regex (concat "%" (number-to-string match-index)))
11166 (replace-with (match-string match-index dlink)))
11167 (while (string-match regex cmd)
11168 (setq cmd (replace-match replace-with t t cmd))))
11169 (setq match-index (+ match-index 1)))))
11171 (save-window-excursion
11172 (message "Running %s...done" cmd)
11173 (start-process-shell-command cmd nil cmd)
11174 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11175 ((or (stringp cmd)
11176 (eq cmd 'emacs))
11177 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11178 (widen)
11179 (if line (progn (org-goto-line line)
11180 (if (derived-mode-p 'org-mode)
11181 (org-reveal)))
11182 (if search (org-link-search search))))
11183 ((consp cmd)
11184 (let ((file (convert-standard-filename file)))
11185 (save-match-data
11186 (set-match-data link-match-data)
11187 (eval cmd))))
11188 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11189 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11190 (or (not (equal old-buffer (current-buffer)))
11191 (not (equal old-pos (point))))
11192 (org-mark-ring-push old-pos old-buffer))))
11194 (defun org-file-apps-entry-match-against-dlink-p (entry)
11195 "This function returns non-nil if `entry' uses a regular
11196 expression which should be matched against the whole link by
11197 org-open-file.
11199 It assumes that is the case when the entry uses a regular
11200 expression which has at least one grouping construct and the
11201 action is either a lisp form or a command string containing
11202 '%1', i.e. using at least one subexpression match as a
11203 parameter."
11204 (let ((selector (car entry))
11205 (action (cdr entry)))
11206 (if (stringp selector)
11207 (and (> (regexp-opt-depth selector) 0)
11208 (or (and (stringp action)
11209 (string-match "%[0-9]" action))
11210 (consp action)))
11211 nil)))
11213 (defun org-default-apps ()
11214 "Return the default applications for this operating system."
11215 (cond
11216 ((eq system-type 'darwin)
11217 org-file-apps-defaults-macosx)
11218 ((eq system-type 'windows-nt)
11219 org-file-apps-defaults-windowsnt)
11220 (t org-file-apps-defaults-gnu)))
11222 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11223 "Convert extensions to regular expressions in the cars of LIST.
11224 Also, weed out any non-string entries, because the return value is used
11225 only for regexp matching.
11226 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11227 point to the symbol `emacs', indicating that the file should
11228 be opened in Emacs."
11229 (append
11230 (delq nil
11231 (mapcar (lambda (x)
11232 (if (not (stringp (car x)))
11234 (if (string-match "\\W" (car x))
11236 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11237 list))
11238 (if add-auto-mode
11239 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11241 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11242 (defun org-file-remote-p (file)
11243 "Test whether FILE specifies a location on a remote system.
11244 Return non-nil if the location is indeed remote.
11246 For example, the filename \"/user@host:/foo\" specifies a location
11247 on the system \"/user@host:\"."
11248 (cond ((fboundp 'file-remote-p)
11249 (file-remote-p file))
11250 ((fboundp 'tramp-handle-file-remote-p)
11251 (tramp-handle-file-remote-p file))
11252 ((and (boundp 'ange-ftp-name-format)
11253 (string-match (car ange-ftp-name-format) file))
11254 t)))
11257 ;;;; Refiling
11259 (defun org-get-org-file ()
11260 "Read a filename, with default directory `org-directory'."
11261 (let ((default (or org-default-notes-file remember-data-file)))
11262 (read-file-name (format "File name [%s]: " default)
11263 (file-name-as-directory org-directory)
11264 default)))
11266 (defun org-notes-order-reversed-p ()
11267 "Check if the current file should receive notes in reversed order."
11268 (cond
11269 ((not org-reverse-note-order) nil)
11270 ((eq t org-reverse-note-order) t)
11271 ((not (listp org-reverse-note-order)) nil)
11272 (t (catch 'exit
11273 (let ((all org-reverse-note-order)
11274 entry)
11275 (while (setq entry (pop all))
11276 (if (string-match (car entry) buffer-file-name)
11277 (throw 'exit (cdr entry))))
11278 nil)))))
11280 (defvar org-refile-target-table nil
11281 "The list of refile targets, created by `org-refile'.")
11283 (defvar org-agenda-new-buffers nil
11284 "Buffers created to visit agenda files.")
11286 (defvar org-refile-cache nil
11287 "Cache for refile targets.")
11289 (defvar org-refile-markers nil
11290 "All the markers used for caching refile locations.")
11292 (defun org-refile-marker (pos)
11293 "Get a new refile marker, but only if caching is in use."
11294 (if (not org-refile-use-cache)
11296 (let ((m (make-marker)))
11297 (move-marker m pos)
11298 (push m org-refile-markers)
11299 m)))
11301 (defun org-refile-cache-clear ()
11302 "Clear the refile cache and disable all the markers."
11303 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11304 (setq org-refile-markers nil)
11305 (setq org-refile-cache nil)
11306 (message "Refile cache has been cleared"))
11308 (defun org-refile-cache-check-set (set)
11309 "Check if all the markers in the cache still have live buffers."
11310 (let (marker)
11311 (catch 'exit
11312 (while (and set (setq marker (nth 3 (pop set))))
11313 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11314 (when (and marker (null (marker-buffer marker)))
11315 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11316 (sit-for 3)
11317 (throw 'exit nil)))
11318 t)))
11320 (defun org-refile-cache-put (set &rest identifiers)
11321 "Push the refile targets SET into the cache, under IDENTIFIERS."
11322 (let* ((key (sha1 (prin1-to-string identifiers)))
11323 (entry (assoc key org-refile-cache)))
11324 (if entry
11325 (setcdr entry set)
11326 (push (cons key set) org-refile-cache))))
11328 (defun org-refile-cache-get (&rest identifiers)
11329 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11330 (cond
11331 ((not org-refile-cache) nil)
11332 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11334 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11335 org-refile-cache))))
11336 (and set (org-refile-cache-check-set set) set)))))
11338 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11339 "Produce a table with refile targets."
11340 (let ((case-fold-search nil)
11341 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11342 (entries (or org-refile-targets '((nil . (:level . 1)))))
11343 targets tgs txt re files f desc descre fast-path-p level pos0)
11344 (message "Getting targets...")
11345 (with-current-buffer (or default-buffer (current-buffer))
11346 (while (setq entry (pop entries))
11347 (setq files (car entry) desc (cdr entry))
11348 (setq fast-path-p nil)
11349 (cond
11350 ((null files) (setq files (list (current-buffer))))
11351 ((eq files 'org-agenda-files)
11352 (setq files (org-agenda-files 'unrestricted)))
11353 ((and (symbolp files) (fboundp files))
11354 (setq files (funcall files)))
11355 ((and (symbolp files) (boundp files))
11356 (setq files (symbol-value files))))
11357 (if (stringp files) (setq files (list files)))
11358 (cond
11359 ((eq (car desc) :tag)
11360 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11361 ((eq (car desc) :todo)
11362 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11363 ((eq (car desc) :regexp)
11364 (setq descre (cdr desc)))
11365 ((eq (car desc) :level)
11366 (setq descre (concat "^\\*\\{" (number-to-string
11367 (if org-odd-levels-only
11368 (1- (* 2 (cdr desc)))
11369 (cdr desc)))
11370 "\\}[ \t]")))
11371 ((eq (car desc) :maxlevel)
11372 (setq fast-path-p t)
11373 (setq descre (concat "^\\*\\{1," (number-to-string
11374 (if org-odd-levels-only
11375 (1- (* 2 (cdr desc)))
11376 (cdr desc)))
11377 "\\}[ \t]")))
11378 (t (error "Bad refiling target description %s" desc)))
11379 (while (setq f (pop files))
11380 (with-current-buffer
11381 (if (bufferp f) f (org-get-agenda-file-buffer f))
11383 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11384 (progn
11385 (if (bufferp f) (setq f (buffer-file-name
11386 (buffer-base-buffer f))))
11387 (setq f (and f (expand-file-name f)))
11388 (if (eq org-refile-use-outline-path 'file)
11389 (push (list (file-name-nondirectory f) f nil nil) tgs))
11390 (save-excursion
11391 (save-restriction
11392 (widen)
11393 (goto-char (point-min))
11394 (while (re-search-forward descre nil t)
11395 (goto-char (setq pos0 (point-at-bol)))
11396 (catch 'next
11397 (when org-refile-target-verify-function
11398 (save-match-data
11399 (or (funcall org-refile-target-verify-function)
11400 (throw 'next t))))
11401 (when (and (looking-at org-complex-heading-regexp)
11402 (not (member (match-string 4) excluded-entries))
11403 (match-string 4))
11404 (setq level (org-reduced-level
11405 (- (match-end 1) (match-beginning 1)))
11406 txt (org-link-display-format (match-string 4))
11407 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11408 re (format org-complex-heading-regexp-format
11409 (regexp-quote (match-string 4))))
11410 (when org-refile-use-outline-path
11411 (setq txt (mapconcat
11412 'org-protect-slash
11413 (append
11414 (if (eq org-refile-use-outline-path
11415 'file)
11416 (list (file-name-nondirectory
11417 (buffer-file-name
11418 (buffer-base-buffer))))
11419 (if (eq org-refile-use-outline-path
11420 'full-file-path)
11421 (list (buffer-file-name
11422 (buffer-base-buffer)))))
11423 (org-get-outline-path fast-path-p
11424 level txt)
11425 (list txt))
11426 "/")))
11427 (push (list txt f re (org-refile-marker (point)))
11428 tgs)))
11429 (when (= (point) pos0)
11430 ;; verification function has not moved point
11431 (goto-char (point-at-eol))))))))
11432 (when org-refile-use-cache
11433 (org-refile-cache-put tgs (buffer-file-name) descre))
11434 (setq targets (append tgs targets))))))
11435 (message "Getting targets...done")
11436 (nreverse targets)))
11438 (defun org-protect-slash (s)
11439 (while (string-match "/" s)
11440 (setq s (replace-match "\\" t t s)))
11443 (defvar org-olpa (make-vector 20 nil))
11445 (defun org-get-outline-path (&optional fastp level heading)
11446 "Return the outline path to the current entry, as a list.
11448 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11449 routine which makes outline path derivations for an entire file,
11450 avoiding backtracing. Refile target collection makes use of that."
11451 (if fastp
11452 (progn
11453 (if (> level 19)
11454 (error "Outline path failure, more than 19 levels"))
11455 (loop for i from level upto 19 do
11456 (aset org-olpa i nil))
11457 (prog1
11458 (delq nil (append org-olpa nil))
11459 (aset org-olpa level heading)))
11460 (let (rtn case-fold-search)
11461 (save-excursion
11462 (save-restriction
11463 (widen)
11464 (while (org-up-heading-safe)
11465 (when (looking-at org-complex-heading-regexp)
11466 (push (org-trim
11467 (replace-regexp-in-string
11468 ;; Remove statistical/checkboxes cookies
11469 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11470 (org-match-string-no-properties 4)))
11471 rtn)))
11472 rtn)))))
11474 (defun org-format-outline-path (path &optional width prefix separator)
11475 "Format the outline path PATH for display.
11476 WIDTH is the maximum number of characters that is available.
11477 PREFIX is a prefix to be included in the returned string,
11478 such as the file name.
11479 SEPARATOR is inserted between the different parts of the path,
11480 the default is \"/\"."
11481 (setq width (or width 79))
11482 (if prefix (setq width (- width (length prefix))))
11483 (if (not path)
11484 (or prefix "")
11485 (let* ((nsteps (length path))
11486 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11487 (maxwidth (if (<= total-width width)
11488 10000 ;; everything fits
11489 ;; we need to shorten the level headings
11490 (/ (- width nsteps) nsteps)))
11491 (org-odd-levels-only nil)
11492 (n 0)
11493 (total (1+ (length prefix))))
11494 (setq maxwidth (max maxwidth 10))
11495 (concat prefix
11496 (if prefix (or separator "/"))
11497 (mapconcat
11498 (lambda (h)
11499 (setq n (1+ n))
11500 (if (and (= n nsteps) (< maxwidth 10000))
11501 (setq maxwidth (- total-width total)))
11502 (if (< (length h) maxwidth)
11503 (progn (setq total (+ total (length h) 1)) h)
11504 (setq h (substring h 0 (- maxwidth 2))
11505 total (+ total maxwidth 1))
11506 (if (string-match "[ \t]+\\'" h)
11507 (setq h (substring h 0 (match-beginning 0))))
11508 (setq h (concat h "..")))
11509 (org-add-props h nil 'face
11510 (nth (% (1- n) org-n-level-faces)
11511 org-level-faces))
11513 path (or separator "/"))))))
11515 (defun org-display-outline-path (&optional file current separator just-return-string)
11516 "Display the current outline path in the echo area.
11518 If FILE is non-nil, prepend the output with the file name.
11519 If CURRENT is non-nil, append the current heading to the output.
11520 SEPARATOR is passed through to `org-format-outline-path'. It separates
11521 the different parts of the path and defaults to \"/\".
11522 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11523 (interactive "P")
11524 (let* (case-fold-search
11525 (bfn (buffer-file-name (buffer-base-buffer)))
11526 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11527 res)
11528 (if current (setq path (append path
11529 (save-excursion
11530 (org-back-to-heading t)
11531 (if (looking-at org-complex-heading-regexp)
11532 (list (match-string 4)))))))
11533 (setq res
11534 (org-format-outline-path
11535 path
11536 (1- (frame-width))
11537 (and file bfn (concat (file-name-nondirectory bfn) separator))
11538 separator))
11539 (if just-return-string
11540 (org-no-properties res)
11541 (org-unlogged-message "%s" res))))
11543 (defvar org-refile-history nil
11544 "History for refiling operations.")
11546 (defvar org-after-refile-insert-hook nil
11547 "Hook run after `org-refile' has inserted its stuff at the new location.
11548 Note that this is still *before* the stuff will be removed from
11549 the *old* location.")
11551 (defvar org-capture-last-stored-marker)
11552 (defvar org-refile-keep nil
11553 "Non-nil means `org-refile' will copy instead of refile.")
11555 (defun org-copy ()
11556 "Like `org-refile', but copy."
11557 (interactive)
11558 (let ((org-refile-keep t))
11559 (funcall 'org-refile nil nil nil "Copy")))
11561 (defun org-refile (&optional goto default-buffer rfloc msg)
11562 "Move the entry or entries at point to another heading.
11563 The list of target headings is compiled using the information in
11564 `org-refile-targets', which see.
11566 At the target location, the entry is filed as a subitem of the target
11567 heading. Depending on `org-reverse-note-order', the new subitem will
11568 either be the first or the last subitem.
11570 If there is an active region, all entries in that region will be moved.
11571 However, the region must fulfill the requirement that the first heading
11572 is the first one sets the top-level of the moved text - at most siblings
11573 below it are allowed.
11575 With prefix arg GOTO, the command will only visit the target location
11576 and not actually move anything.
11578 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11579 go to the location where the last refiling operation has put the subtree.
11581 With a numeric prefix argument of `2', refile to the running clock.
11583 With a numeric prefix argument of `3', emulate `org-refile-keep'
11584 being set to `t' and copy to the target location, don't move it.
11585 Beware that keeping refiled entries may result in duplicated ID
11586 properties.
11588 RFLOC can be a refile location obtained in a different way.
11590 MSG is a string to replace \"Refile\" in the default prompt with
11591 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11593 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11595 If you are using target caching (see `org-refile-use-cache'),
11596 you have to clear the target cache in order to find new targets.
11597 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11598 prefix argument (`C-u C-u C-u C-c C-w')."
11600 (interactive "P")
11601 (if (member goto '(0 (64)))
11602 (org-refile-cache-clear)
11603 (let* ((actionmsg (or msg "Refile"))
11604 (cbuf (current-buffer))
11605 (regionp (org-region-active-p))
11606 (region-start (and regionp (region-beginning)))
11607 (region-end (and regionp (region-end)))
11608 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11609 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11610 pos it nbuf file re level reversed)
11611 (setq last-command nil)
11612 (when regionp
11613 (goto-char region-start)
11614 (or (bolp) (goto-char (point-at-bol)))
11615 (setq region-start (point))
11616 (unless (or (org-kill-is-subtree-p
11617 (buffer-substring region-start region-end))
11618 (prog1 org-refile-active-region-within-subtree
11619 (let ((s (point-at-eol)))
11620 (org-toggle-heading)
11621 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11622 (user-error "The region is not a (sequence of) subtree(s)")))
11623 (if (equal goto '(16))
11624 (org-refile-goto-last-stored)
11625 (when (or
11626 (and (equal goto 2)
11627 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11628 (prog1
11629 (setq it (list (or org-clock-heading "running clock")
11630 (buffer-file-name
11631 (marker-buffer org-clock-hd-marker))
11633 (marker-position org-clock-hd-marker)))
11634 (setq goto nil)))
11635 (setq it (or rfloc
11636 (let (heading-text)
11637 (save-excursion
11638 (unless goto
11639 (org-back-to-heading t)
11640 (setq heading-text
11641 (nth 4 (org-heading-components))))
11643 (org-refile-get-location
11644 (cond (goto "Goto")
11645 (regionp (concat actionmsg " region to"))
11646 (t (concat actionmsg " subtree \""
11647 heading-text "\" to")))
11648 default-buffer
11649 (and (not (equal '(4) goto))
11650 org-refile-allow-creating-parent-nodes)
11651 goto))))))
11652 (setq file (nth 1 it)
11653 re (nth 2 it)
11654 pos (nth 3 it))
11655 (if (and (not goto)
11657 (equal (buffer-file-name) file)
11658 (if regionp
11659 (and (>= pos region-start)
11660 (<= pos region-end))
11661 (and (>= pos (point))
11662 (< pos (save-excursion
11663 (org-end-of-subtree t t))))))
11664 (error "Cannot refile to position inside the tree or region"))
11666 (setq nbuf (or (find-buffer-visiting file)
11667 (find-file-noselect file)))
11668 (if (and goto (not (equal goto 3)))
11669 (progn
11670 (org-pop-to-buffer-same-window nbuf)
11671 (goto-char pos)
11672 (org-show-context 'org-goto))
11673 (if regionp
11674 (progn
11675 (org-kill-new (buffer-substring region-start region-end))
11676 (org-save-markers-in-region region-start region-end))
11677 (org-copy-subtree 1 nil t))
11678 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11679 (find-file-noselect file)))
11680 (setq reversed (org-notes-order-reversed-p))
11681 (save-excursion
11682 (save-restriction
11683 (widen)
11684 (if pos
11685 (progn
11686 (goto-char pos)
11687 (looking-at org-outline-regexp)
11688 (setq level (org-get-valid-level (funcall outline-level) 1))
11689 (goto-char
11690 (if reversed
11691 (or (outline-next-heading) (point-max))
11692 (or (save-excursion (org-get-next-sibling))
11693 (org-end-of-subtree t t)
11694 (point-max)))))
11695 (setq level 1)
11696 (if (not reversed)
11697 (goto-char (point-max))
11698 (goto-char (point-min))
11699 (or (outline-next-heading) (goto-char (point-max)))))
11700 (if (not (bolp)) (newline))
11701 (org-paste-subtree level)
11702 (when org-log-refile
11703 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11704 (unless (eq org-log-refile 'note)
11705 (save-excursion (org-add-log-note))))
11706 (and org-auto-align-tags
11707 (let ((org-loop-over-headlines-in-active-region nil))
11708 (org-set-tags nil t)))
11709 (let ((bookmark-name (plist-get org-bookmark-names-plist
11710 :last-refile)))
11711 (when bookmark-name
11712 (with-demoted-errors
11713 (bookmark-set bookmark-name))))
11714 ;; If we are refiling for capture, make sure that the
11715 ;; last-capture pointers point here
11716 (when (org-bound-and-true-p org-refile-for-capture)
11717 (let ((bookmark-name (plist-get org-bookmark-names-plist
11718 :last-capture-marker)))
11719 (when bookmark-name
11720 (with-demoted-errors
11721 (bookmark-set bookmark-name))))
11722 (move-marker org-capture-last-stored-marker (point)))
11723 (if (fboundp 'deactivate-mark) (deactivate-mark))
11724 (run-hooks 'org-after-refile-insert-hook))))
11725 (unless org-refile-keep
11726 (if regionp
11727 (delete-region (point) (+ (point) (- region-end region-start)))
11728 (delete-region
11729 (and (org-back-to-heading t) (point))
11730 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11731 (when (featurep 'org-inlinetask)
11732 (org-inlinetask-remove-END-maybe))
11733 (setq org-markers-to-move nil)
11734 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11736 (defun org-refile-goto-last-stored ()
11737 "Go to the location where the last refile was stored."
11738 (interactive)
11739 (bookmark-jump "org-refile-last-stored")
11740 (message "This is the location of the last refile"))
11742 (defun org-refile--get-location (refloc tbl)
11743 "When user refile to REFLOC, find the associated target in TBL.
11744 Also check `org-refile-target-table'."
11745 (car (delq
11747 (mapcar
11748 (lambda (r) (or (assoc r tbl)
11749 (assoc r org-refile-target-table)))
11750 (list (replace-regexp-in-string "/$" "" refloc)
11751 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11753 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11754 no-exclude)
11755 "Prompt the user for a refile location, using PROMPT.
11756 PROMPT should not be suffixed with a colon and a space, because
11757 this function appends the default value from
11758 `org-refile-history' automatically, if that is not empty.
11759 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11760 this is used for the GOTO interface."
11761 (let ((org-refile-targets org-refile-targets)
11762 (org-refile-use-outline-path org-refile-use-outline-path)
11763 excluded-entries)
11764 (when (and (derived-mode-p 'org-mode)
11765 (not org-refile-use-cache)
11766 (not no-exclude))
11767 (org-map-tree
11768 (lambda()
11769 (setq excluded-entries
11770 (append excluded-entries (list (org-get-heading t t)))))))
11771 (setq org-refile-target-table
11772 (org-refile-get-targets default-buffer excluded-entries)))
11773 (unless org-refile-target-table
11774 (user-error "No refile targets"))
11775 (let* ((cbuf (current-buffer))
11776 (partial-completion-mode nil)
11777 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11778 (cfunc (if (and org-refile-use-outline-path
11779 org-outline-path-complete-in-steps)
11780 'org-olpath-completing-read
11781 'org-icompleting-read))
11782 (extra (if org-refile-use-outline-path "/" ""))
11783 (cbnex (concat (buffer-name) extra))
11784 (filename (and cfn (expand-file-name cfn)))
11785 (tbl (mapcar
11786 (lambda (x)
11787 (if (and (not (member org-refile-use-outline-path
11788 '(file full-file-path)))
11789 (not (equal filename (nth 1 x))))
11790 (cons (concat (car x) extra " ("
11791 (file-name-nondirectory (nth 1 x)) ")")
11792 (cdr x))
11793 (cons (concat (car x) extra) (cdr x))))
11794 org-refile-target-table))
11795 (completion-ignore-case t)
11796 cdef
11797 (prompt (concat prompt
11798 (or (and (car org-refile-history)
11799 (concat " (default " (car org-refile-history) ")"))
11800 (and (assoc cbnex tbl) (setq cdef cbnex)
11801 (concat " (default " cbnex ")"))) ": "))
11802 pa answ parent-target child parent old-hist)
11803 (setq old-hist org-refile-history)
11804 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11805 nil 'org-refile-history (or cdef (car org-refile-history))))
11806 (if (setq pa (org-refile--get-location answ tbl))
11807 (progn
11808 (org-refile-check-position pa)
11809 (when (or (not org-refile-history)
11810 (not (eq old-hist org-refile-history))
11811 (not (equal (car pa) (car org-refile-history))))
11812 (setq org-refile-history
11813 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11814 org-refile-history
11815 (cdr org-refile-history))))
11816 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11817 (pop org-refile-history)))
11819 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11820 (progn
11821 (setq parent (match-string 1 answ)
11822 child (match-string 2 answ))
11823 (setq parent-target (org-refile--get-location parent tbl))
11824 (when (and parent-target
11825 (or (eq new-nodes t)
11826 (and (eq new-nodes 'confirm)
11827 (y-or-n-p (format "Create new node \"%s\"? "
11828 child)))))
11829 (org-refile-new-child parent-target child)))
11830 (user-error "Invalid target location")))))
11832 (declare-function org-string-nw-p "org-macs" (s))
11833 (defun org-refile-check-position (refile-pointer)
11834 "Check if the refile pointer matches the headline to which it points."
11835 (let* ((file (nth 1 refile-pointer))
11836 (re (nth 2 refile-pointer))
11837 (pos (nth 3 refile-pointer))
11838 buffer)
11839 (if (and (not (markerp pos)) (not file))
11840 (if file
11841 (user-error "Please save the buffer to a file before refiling")
11842 (user-error "Please indicate a target file in the refile path"))
11843 (when (org-string-nw-p re)
11844 (setq buffer (if (markerp pos)
11845 (marker-buffer pos)
11846 (or (find-buffer-visiting file)
11847 (find-file-noselect file))))
11848 (with-current-buffer buffer
11849 (save-excursion
11850 (save-restriction
11851 (widen)
11852 (goto-char pos)
11853 (beginning-of-line 1)
11854 (unless (org-looking-at-p re)
11855 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11857 (defun org-refile-new-child (parent-target child)
11858 "Use refile target PARENT-TARGET to add new CHILD below it."
11859 (unless parent-target
11860 (error "Cannot find parent for new node"))
11861 (let ((file (nth 1 parent-target))
11862 (pos (nth 3 parent-target))
11863 level)
11864 (with-current-buffer (or (find-buffer-visiting file)
11865 (find-file-noselect file))
11866 (save-excursion
11867 (save-restriction
11868 (widen)
11869 (if pos
11870 (goto-char pos)
11871 (goto-char (point-max))
11872 (if (not (bolp)) (newline)))
11873 (when (looking-at org-outline-regexp)
11874 (setq level (funcall outline-level))
11875 (org-end-of-subtree t t))
11876 (org-back-over-empty-lines)
11877 (insert "\n" (make-string
11878 (if pos (org-get-valid-level level 1) 1) ?*)
11879 " " child "\n")
11880 (beginning-of-line 0)
11881 (list (concat (car parent-target) "/" child) file "" (point)))))))
11883 (defun org-olpath-completing-read (prompt collection &rest args)
11884 "Read an outline path like a file name."
11885 (let ((thetable collection)
11886 (org-completion-use-ido nil) ; does not work with ido.
11887 (org-completion-use-iswitchb nil)) ; or iswitchb
11888 (apply
11889 'org-icompleting-read prompt
11890 (lambda (string predicate &optional flag)
11891 (let (rtn r f (l (length string)))
11892 (cond
11893 ((eq flag nil)
11894 ;; try completion
11895 (try-completion string thetable))
11896 ((eq flag t)
11897 ;; all-completions
11898 (setq rtn (all-completions string thetable predicate))
11899 (mapcar
11900 (lambda (x)
11901 (setq r (substring x l))
11902 (if (string-match " ([^)]*)$" x)
11903 (setq f (match-string 0 x))
11904 (setq f ""))
11905 (if (string-match "/" r)
11906 (concat string (substring r 0 (match-end 0)) f)
11908 rtn))
11909 ((eq flag 'lambda)
11910 ;; exact match?
11911 (assoc string thetable)))))
11912 args)))
11914 ;;;; Dynamic blocks
11916 (defun org-find-dblock (name)
11917 "Find the first dynamic block with name NAME in the buffer.
11918 If not found, stay at current position and return nil."
11919 (let ((case-fold-search t) pos)
11920 (save-excursion
11921 (goto-char (point-min))
11922 (setq pos (and (re-search-forward
11923 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11924 (match-beginning 0))))
11925 (if pos (goto-char pos))
11926 pos))
11928 (defun org-create-dblock (plist)
11929 "Create a dynamic block section, with parameters taken from PLIST.
11930 PLIST must contain a :name entry which is used as name of the block."
11931 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11932 (end-of-line 1)
11933 (newline))
11934 (let ((col (current-column))
11935 (name (plist-get plist :name)))
11936 (insert "#+BEGIN: " name)
11937 (while plist
11938 (if (eq (car plist) :name)
11939 (setq plist (cddr plist))
11940 (insert " " (prin1-to-string (pop plist)))))
11941 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11942 (beginning-of-line -2)))
11944 (defun org-prepare-dblock ()
11945 "Prepare dynamic block for refresh.
11946 This empties the block, puts the cursor at the insert position and returns
11947 the property list including an extra property :name with the block name."
11948 (unless (looking-at org-dblock-start-re)
11949 (user-error "Not at a dynamic block"))
11950 (let* ((begdel (1+ (match-end 0)))
11951 (name (org-no-properties (match-string 1)))
11952 (params (append (list :name name)
11953 (read (concat "(" (match-string 3) ")")))))
11954 (save-excursion
11955 (beginning-of-line 1)
11956 (skip-chars-forward " \t")
11957 (setq params (plist-put params :indentation-column (current-column))))
11958 (unless (re-search-forward org-dblock-end-re nil t)
11959 (error "Dynamic block not terminated"))
11960 (setq params
11961 (append params
11962 (list :content (buffer-substring
11963 begdel (match-beginning 0)))))
11964 (delete-region begdel (match-beginning 0))
11965 (goto-char begdel)
11966 (open-line 1)
11967 params))
11969 (defun org-map-dblocks (&optional command)
11970 "Apply COMMAND to all dynamic blocks in the current buffer.
11971 If COMMAND is not given, use `org-update-dblock'."
11972 (let ((cmd (or command 'org-update-dblock)))
11973 (save-excursion
11974 (goto-char (point-min))
11975 (while (re-search-forward org-dblock-start-re nil t)
11976 (goto-char (match-beginning 0))
11977 (save-excursion
11978 (condition-case nil
11979 (funcall cmd)
11980 (error (message "Error during update of dynamic block"))))
11981 (unless (re-search-forward org-dblock-end-re nil t)
11982 (error "Dynamic block not terminated"))))))
11984 (defun org-dblock-update (&optional arg)
11985 "User command for updating dynamic blocks.
11986 Update the dynamic block at point. With prefix ARG, update all dynamic
11987 blocks in the buffer."
11988 (interactive "P")
11989 (if arg
11990 (org-update-all-dblocks)
11991 (or (looking-at org-dblock-start-re)
11992 (org-beginning-of-dblock))
11993 (org-update-dblock)))
11995 (defun org-update-dblock ()
11996 "Update the dynamic block at point.
11997 This means to empty the block, parse for parameters and then call
11998 the correct writing function."
11999 (interactive)
12000 (save-window-excursion
12001 (let* ((pos (point))
12002 (line (org-current-line))
12003 (params (org-prepare-dblock))
12004 (name (plist-get params :name))
12005 (indent (plist-get params :indentation-column))
12006 (cmd (intern (concat "org-dblock-write:" name))))
12007 (message "Updating dynamic block `%s' at line %d..." name line)
12008 (funcall cmd params)
12009 (message "Updating dynamic block `%s' at line %d...done" name line)
12010 (goto-char pos)
12011 (when (and indent (> indent 0))
12012 (setq indent (make-string indent ?\ ))
12013 (save-excursion
12014 (org-beginning-of-dblock)
12015 (forward-line 1)
12016 (while (not (looking-at org-dblock-end-re))
12017 (insert indent)
12018 (beginning-of-line 2))
12019 (when (looking-at org-dblock-end-re)
12020 (and (looking-at "[ \t]+")
12021 (replace-match ""))
12022 (insert indent)))))))
12024 (defun org-beginning-of-dblock ()
12025 "Find the beginning of the dynamic block at point.
12026 Error if there is no such block at point."
12027 (let ((pos (point))
12028 beg)
12029 (end-of-line 1)
12030 (if (and (re-search-backward org-dblock-start-re nil t)
12031 (setq beg (match-beginning 0))
12032 (re-search-forward org-dblock-end-re nil t)
12033 (> (match-end 0) pos))
12034 (goto-char beg)
12035 (goto-char pos)
12036 (error "Not in a dynamic block"))))
12038 (defun org-update-all-dblocks ()
12039 "Update all dynamic blocks in the buffer.
12040 This function can be used in a hook."
12041 (interactive)
12042 (when (derived-mode-p 'org-mode)
12043 (org-map-dblocks 'org-update-dblock)))
12046 ;;;; Completion
12048 (declare-function org-export-backend-name "org-export" (cl-x))
12049 (declare-function org-export-backend-options "org-export" (cl-x))
12050 (defun org-get-export-keywords ()
12051 "Return a list of all currently understood export keywords.
12052 Export keywords include options, block names, attributes and
12053 keywords relative to each registered export back-end."
12054 (let (keywords)
12055 (dolist (backend
12056 (org-bound-and-true-p org-export--registered-backends)
12057 (delq nil keywords))
12058 ;; Back-end name (for keywords, like #+LATEX:)
12059 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12060 (dolist (option-entry (org-export-backend-options backend))
12061 ;; Back-end options.
12062 (push (nth 1 option-entry) keywords)))))
12064 (defconst org-options-keywords
12065 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12066 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12067 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12068 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12069 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12071 (defcustom org-structure-template-alist
12072 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12073 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12074 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12075 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12076 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12077 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12078 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12079 "<literal style=\"latex\">\n?\n</literal>")
12080 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12081 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12082 "<literal style=\"html\">\n?\n</literal>")
12083 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12084 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12085 ("A" "#+ASCII: " "")
12086 ("i" "#+INDEX: ?" "#+INDEX: ?")
12087 ("I" "#+INCLUDE: %file ?"
12088 "<include file=%file markup=\"?\">"))
12089 "Structure completion elements.
12090 This is a list of abbreviation keys and values. The value gets inserted
12091 if you type `<' followed by the key and then press the completion key,
12092 usually `M-TAB'. %file will be replaced by a file name after prompting
12093 for the file using completion. The cursor will be placed at the position
12094 of the `?` in the template.
12095 There are two templates for each key, the first uses the original Org syntax,
12096 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12097 the default when the /org-mtags.el/ module has been loaded. See also the
12098 variable `org-mtags-prefer-muse-templates'."
12099 :group 'org-completion
12100 :type '(repeat
12101 (list
12102 (string :tag "Key")
12103 (string :tag "Template")
12104 (string :tag "Muse Template"))))
12106 (defun org-try-structure-completion ()
12107 "Try to complete a structure template before point.
12108 This looks for strings like \"<e\" on an otherwise empty line and
12109 expands them."
12110 (let ((l (buffer-substring (point-at-bol) (point)))
12112 (when (and (looking-at "[ \t]*$")
12113 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12114 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12115 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12116 (match-beginning 1)) a)
12117 t)))
12119 (defun org-complete-expand-structure-template (start cell)
12120 "Expand a structure template."
12121 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12122 (rpl (nth (if musep 2 1) cell))
12123 (ind ""))
12124 (delete-region start (point))
12125 (when (string-match "\\`#\\+" rpl)
12126 (cond
12127 ((bolp))
12128 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12129 (setq ind (buffer-substring (point-at-bol) (point))))
12130 (t (newline))))
12131 (setq start (point))
12132 (if (string-match "%file" rpl)
12133 (setq rpl (replace-match
12134 (concat
12135 "\""
12136 (save-match-data
12137 (abbreviate-file-name (read-file-name "Include file: ")))
12138 "\"")
12139 t t rpl)))
12140 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12141 (concat "\n" ind)))
12142 (insert rpl)
12143 (if (re-search-backward "\\?" start t) (delete-char 1))))
12145 ;;;; TODO, DEADLINE, Comments
12147 (defun org-toggle-comment ()
12148 "Change the COMMENT state of an entry."
12149 (interactive)
12150 (save-excursion
12151 (org-back-to-heading)
12152 (let (case-fold-search)
12153 (cond
12154 ((looking-at (format org-heading-keyword-regexp-format
12155 org-comment-string))
12156 (goto-char (match-end 1))
12157 (looking-at (concat " +" org-comment-string))
12158 (replace-match "" t t)
12159 (when (eolp) (insert " ")))
12160 ((looking-at org-outline-regexp)
12161 (goto-char (match-end 0))
12162 (insert org-comment-string " "))))))
12164 (defvar org-last-todo-state-is-todo nil
12165 "This is non-nil when the last TODO state change led to a TODO state.
12166 If the last change removed the TODO tag or switched to DONE, then
12167 this is nil.")
12169 (defvar org-setting-tags nil) ; dynamically skipped
12171 (defvar org-todo-setup-filter-hook nil
12172 "Hook for functions that pre-filter todo specs.
12173 Each function takes a todo spec and returns either nil or the spec
12174 transformed into canonical form." )
12176 (defvar org-todo-get-default-hook nil
12177 "Hook for functions that get a default item for todo.
12178 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12179 nil or a string to be used for the todo mark." )
12181 (defvar org-agenda-headline-snapshot-before-repeat)
12183 (defun org-current-effective-time ()
12184 "Return current time adjusted for `org-extend-today-until' variable."
12185 (let* ((ct (org-current-time))
12186 (dct (decode-time ct))
12187 (ct1
12188 (cond
12189 (org-use-last-clock-out-time-as-effective-time
12190 (or (org-clock-get-last-clock-out-time) ct))
12191 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12192 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12193 (t ct))))
12194 ct1))
12196 (defun org-todo-yesterday (&optional arg)
12197 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12198 (interactive "P")
12199 (if (eq major-mode 'org-agenda-mode)
12200 (apply 'org-agenda-todo-yesterday arg)
12201 (let* ((hour (third (decode-time
12202 (org-current-time))))
12203 (org-extend-today-until (1+ hour)))
12204 (org-todo arg))))
12206 (defvar org-block-entry-blocking ""
12207 "First entry preventing the TODO state change.")
12209 (defun org-cancel-repeater ()
12210 "Cancel a repeater by setting its numeric value to zero."
12211 (interactive)
12212 (save-excursion
12213 (org-back-to-heading t)
12214 (let ((bound1 (point))
12215 (bound0 (save-excursion (outline-next-heading) (point))))
12216 (when (re-search-forward
12217 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12218 org-deadline-time-regexp "\\)\\|\\("
12219 org-ts-regexp "\\)")
12220 bound0 t)
12221 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12222 (replace-match "0" t nil nil 1))))))
12224 (defun org-todo (&optional arg)
12225 "Change the TODO state of an item.
12226 The state of an item is given by a keyword at the start of the heading,
12227 like
12228 *** TODO Write paper
12229 *** DONE Call mom
12231 The different keywords are specified in the variable `org-todo-keywords'.
12232 By default the available states are \"TODO\" and \"DONE\".
12233 So for this example: when the item starts with TODO, it is changed to DONE.
12234 When it starts with DONE, the DONE is removed. And when neither TODO nor
12235 DONE are present, add TODO at the beginning of the heading.
12237 With \\[universal-argument] prefix arg, use completion to determine the new \
12238 state.
12239 With numeric prefix arg, switch to that state.
12240 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12241 keywords (nextset).
12242 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12243 With a numeric prefix arg of 0, inhibit note taking for the change.
12244 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12246 When called through ELisp, arg is also interpreted in the following way:
12247 'none -> empty state
12248 \"\"(empty string) -> switch to empty state
12249 'done -> switch to DONE
12250 'nextset -> switch to the next set of keywords
12251 'previousset -> switch to the previous set of keywords
12252 \"WAITING\" -> switch to the specified keyword, but only if it
12253 really is a member of `org-todo-keywords'."
12254 (interactive "P")
12255 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12256 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12257 'region-start-level 'region))
12258 org-loop-over-headlines-in-active-region)
12259 (org-map-entries
12260 `(org-todo ,arg)
12261 org-loop-over-headlines-in-active-region
12262 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12263 (if (equal arg '(16)) (setq arg 'nextset))
12264 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12265 (let ((org-blocker-hook org-blocker-hook)
12266 commentp
12267 case-fold-search)
12268 (when (equal arg '(64))
12269 (setq arg nil org-blocker-hook nil))
12270 (when (and org-blocker-hook
12271 (or org-inhibit-blocking
12272 (org-entry-get nil "NOBLOCKING")))
12273 (setq org-blocker-hook nil))
12274 (save-excursion
12275 (catch 'exit
12276 (org-back-to-heading t)
12277 (when (looking-at (concat "^\\*+ " org-comment-string))
12278 (org-toggle-comment)
12279 (setq commentp t))
12280 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12281 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12282 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12283 (let* ((match-data (match-data))
12284 (startpos (point-at-bol))
12285 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12286 (org-log-done org-log-done)
12287 (org-log-repeat org-log-repeat)
12288 (org-todo-log-states org-todo-log-states)
12289 (org-inhibit-logging
12290 (if (equal arg 0)
12291 (progn (setq arg nil) 'note) org-inhibit-logging))
12292 (this (match-string 1))
12293 (hl-pos (match-beginning 0))
12294 (head (org-get-todo-sequence-head this))
12295 (ass (assoc head org-todo-kwd-alist))
12296 (interpret (nth 1 ass))
12297 (done-word (nth 3 ass))
12298 (final-done-word (nth 4 ass))
12299 (org-last-state (or this ""))
12300 (completion-ignore-case t)
12301 (member (member this org-todo-keywords-1))
12302 (tail (cdr member))
12303 (org-state (cond
12304 ((and org-todo-key-trigger
12305 (or (and (equal arg '(4))
12306 (eq org-use-fast-todo-selection 'prefix))
12307 (and (not arg) org-use-fast-todo-selection
12308 (not (eq org-use-fast-todo-selection
12309 'prefix)))))
12310 ;; Use fast selection
12311 (org-fast-todo-selection))
12312 ((and (equal arg '(4))
12313 (or (not org-use-fast-todo-selection)
12314 (not org-todo-key-trigger)))
12315 ;; Read a state with completion
12316 (org-icompleting-read
12317 "State: " (mapcar 'list org-todo-keywords-1)
12318 nil t))
12319 ((eq arg 'right)
12320 (if this
12321 (if tail (car tail) nil)
12322 (car org-todo-keywords-1)))
12323 ((eq arg 'left)
12324 (if (equal member org-todo-keywords-1)
12326 (if this
12327 (nth (- (length org-todo-keywords-1)
12328 (length tail) 2)
12329 org-todo-keywords-1)
12330 (org-last org-todo-keywords-1))))
12331 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12332 (setq arg nil))) ; hack to fall back to cycling
12333 (arg
12334 ;; user or caller requests a specific state
12335 (cond
12336 ((equal arg "") nil)
12337 ((eq arg 'none) nil)
12338 ((eq arg 'done) (or done-word (car org-done-keywords)))
12339 ((eq arg 'nextset)
12340 (or (car (cdr (member head org-todo-heads)))
12341 (car org-todo-heads)))
12342 ((eq arg 'previousset)
12343 (let ((org-todo-heads (reverse org-todo-heads)))
12344 (or (car (cdr (member head org-todo-heads)))
12345 (car org-todo-heads))))
12346 ((car (member arg org-todo-keywords-1)))
12347 ((stringp arg)
12348 (user-error "State `%s' not valid in this file" arg))
12349 ((nth (1- (prefix-numeric-value arg))
12350 org-todo-keywords-1))))
12351 ((null member) (or head (car org-todo-keywords-1)))
12352 ((equal this final-done-word) nil) ;; -> make empty
12353 ((null tail) nil) ;; -> first entry
12354 ((memq interpret '(type priority))
12355 (if (eq this-command last-command)
12356 (car tail)
12357 (if (> (length tail) 0)
12358 (or done-word (car org-done-keywords))
12359 nil)))
12361 (car tail))))
12362 (org-state (or
12363 (run-hook-with-args-until-success
12364 'org-todo-get-default-hook org-state org-last-state)
12365 org-state))
12366 (next (if org-state (concat " " org-state " ") " "))
12367 (change-plist (list :type 'todo-state-change :from this :to org-state
12368 :position startpos))
12369 dolog now-done-p)
12370 (when org-blocker-hook
12371 (setq org-last-todo-state-is-todo
12372 (not (member this org-done-keywords)))
12373 (unless (save-excursion
12374 (save-match-data
12375 (org-with-wide-buffer
12376 (run-hook-with-args-until-failure
12377 'org-blocker-hook change-plist))))
12378 (if (org-called-interactively-p 'interactive)
12379 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12380 this org-state org-block-entry-blocking)
12381 ;; fail silently
12382 (message "TODO state change from %s to %s blocked (by \"%s\")"
12383 this org-state org-block-entry-blocking)
12384 (throw 'exit nil))))
12385 (store-match-data match-data)
12386 (replace-match next t t)
12387 (unless (pos-visible-in-window-p hl-pos)
12388 (message "TODO state changed to %s" (org-trim next)))
12389 (unless head
12390 (setq head (org-get-todo-sequence-head org-state)
12391 ass (assoc head org-todo-kwd-alist)
12392 interpret (nth 1 ass)
12393 done-word (nth 3 ass)
12394 final-done-word (nth 4 ass)))
12395 (when (memq arg '(nextset previousset))
12396 (message "Keyword-Set %d/%d: %s"
12397 (- (length org-todo-sets) -1
12398 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12399 (length org-todo-sets)
12400 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12401 (setq org-last-todo-state-is-todo
12402 (not (member org-state org-done-keywords)))
12403 (setq now-done-p (and (member org-state org-done-keywords)
12404 (not (member this org-done-keywords))))
12405 (and logging (org-local-logging logging))
12406 (when (and (or org-todo-log-states org-log-done)
12407 (not (eq org-inhibit-logging t))
12408 (not (memq arg '(nextset previousset))))
12409 ;; we need to look at recording a time and note
12410 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12411 (nth 2 (assoc this org-todo-log-states))))
12412 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12413 (setq dolog 'time))
12414 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12415 (and org-state
12416 (member org-state org-not-done-keywords)
12417 (not (member this org-not-done-keywords))))
12418 ;; This is now a todo state and was not one before
12419 ;; If there was a CLOSED time stamp, get rid of it.
12420 (org-add-planning-info nil nil 'closed))
12421 (when (and now-done-p org-log-done)
12422 ;; It is now done, and it was not done before
12423 (org-add-planning-info 'closed (org-current-effective-time))
12424 (if (and (not dolog) (eq 'note org-log-done))
12425 (org-add-log-setup 'done org-state this 'findpos 'note)))
12426 (when (and org-state dolog)
12427 ;; This is a non-nil state, and we need to log it
12428 (org-add-log-setup 'state org-state this 'findpos dolog)))
12429 ;; Fixup tag positioning
12430 (org-todo-trigger-tag-changes org-state)
12431 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12432 (when org-provide-todo-statistics
12433 (org-update-parent-todo-statistics))
12434 (run-hooks 'org-after-todo-state-change-hook)
12435 (if (and arg (not (member org-state org-done-keywords)))
12436 (setq head (org-get-todo-sequence-head org-state)))
12437 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12438 ;; Do we need to trigger a repeat?
12439 (when now-done-p
12440 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12441 ;; This is for the agenda, take a snapshot of the headline.
12442 (save-match-data
12443 (setq org-agenda-headline-snapshot-before-repeat
12444 (org-get-heading))))
12445 (org-auto-repeat-maybe org-state))
12446 ;; Fixup cursor location if close to the keyword
12447 (if (and (outline-on-heading-p)
12448 (not (bolp))
12449 (save-excursion (beginning-of-line 1)
12450 (looking-at org-todo-line-regexp))
12451 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12452 (progn
12453 (goto-char (or (match-end 2) (match-end 1)))
12454 (and (looking-at " ") (just-one-space))))
12455 (when org-trigger-hook
12456 (save-excursion
12457 (run-hook-with-args 'org-trigger-hook change-plist)))
12458 (when commentp (org-toggle-comment))))))))
12460 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12461 "Block turning an entry into a TODO, using the hierarchy.
12462 This checks whether the current task should be blocked from state
12463 changes. Such blocking occurs when:
12465 1. The task has children which are not all in a completed state.
12467 2. A task has a parent with the property :ORDERED:, and there
12468 are siblings prior to the current task with incomplete
12469 status.
12471 3. The parent of the task is blocked because it has siblings that should
12472 be done first, or is child of a block grandparent TODO entry."
12474 (if (not org-enforce-todo-dependencies)
12475 t ; if locally turned off don't block
12476 (catch 'dont-block
12477 ;; If this is not a todo state change, or if this entry is already DONE,
12478 ;; do not block
12479 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12480 (member (plist-get change-plist :from)
12481 (cons 'done org-done-keywords))
12482 (member (plist-get change-plist :to)
12483 (cons 'todo org-not-done-keywords))
12484 (not (plist-get change-plist :to)))
12485 (throw 'dont-block t))
12486 ;; If this task has children, and any are undone, it's blocked
12487 (save-excursion
12488 (org-back-to-heading t)
12489 (let ((this-level (funcall outline-level)))
12490 (outline-next-heading)
12491 (let ((child-level (funcall outline-level)))
12492 (while (and (not (eobp))
12493 (> child-level this-level))
12494 ;; this todo has children, check whether they are all
12495 ;; completed
12496 (if (and (not (org-entry-is-done-p))
12497 (org-entry-is-todo-p))
12498 (progn (setq org-block-entry-blocking (org-get-heading))
12499 (throw 'dont-block nil)))
12500 (outline-next-heading)
12501 (setq child-level (funcall outline-level))))))
12502 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12503 ;; any previous siblings are undone, it's blocked
12504 (save-excursion
12505 (org-back-to-heading t)
12506 (let* ((pos (point))
12507 (parent-pos (and (org-up-heading-safe) (point))))
12508 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12509 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12510 (forward-line 1)
12511 (re-search-forward org-not-done-heading-regexp pos t))
12512 (setq org-block-entry-blocking (match-string 0))
12513 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12514 ;; Search further up the hierarchy, to see if an ancestor is blocked
12515 (while t
12516 (goto-char parent-pos)
12517 (if (not (looking-at org-not-done-heading-regexp))
12518 (throw 'dont-block t)) ; do not block, parent is not a TODO
12519 (setq pos (point))
12520 (setq parent-pos (and (org-up-heading-safe) (point)))
12521 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12522 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12523 (forward-line 1)
12524 (re-search-forward org-not-done-heading-regexp pos t)
12525 (setq org-block-entry-blocking (org-get-heading)))
12526 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12528 (defcustom org-track-ordered-property-with-tag nil
12529 "Should the ORDERED property also be shown as a tag?
12530 The ORDERED property decides if an entry should require subtasks to be
12531 completed in sequence. Since a property is not very visible, setting
12532 this option means that toggling the ORDERED property with the command
12533 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12534 not relevant for the behavior, but it makes things more visible.
12536 Note that toggling the tag with tags commands will not change the property
12537 and therefore not influence behavior!
12539 This can be t, meaning the tag ORDERED should be used, It can also be a
12540 string to select a different tag for this task."
12541 :group 'org-todo
12542 :type '(choice
12543 (const :tag "No tracking" nil)
12544 (const :tag "Track with ORDERED tag" t)
12545 (string :tag "Use other tag")))
12547 (defun org-toggle-ordered-property ()
12548 "Toggle the ORDERED property of the current entry.
12549 For better visibility, you can track the value of this property with a tag.
12550 See variable `org-track-ordered-property-with-tag'."
12551 (interactive)
12552 (let* ((t1 org-track-ordered-property-with-tag)
12553 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12554 (save-excursion
12555 (org-back-to-heading)
12556 (if (org-entry-get nil "ORDERED")
12557 (progn
12558 (org-delete-property "ORDERED")
12559 (and tag (org-toggle-tag tag 'off))
12560 (message "Subtasks can be completed in arbitrary order"))
12561 (org-entry-put nil "ORDERED" "t")
12562 (and tag (org-toggle-tag tag 'on))
12563 (message "Subtasks must be completed in sequence")))))
12565 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12566 (defun org-block-todo-from-checkboxes (change-plist)
12567 "Block turning an entry into a TODO, using checkboxes.
12568 This checks whether the current task should be blocked from state
12569 changes because there are unchecked boxes in this entry."
12570 (if (not org-enforce-todo-checkbox-dependencies)
12571 t ; if locally turned off don't block
12572 (catch 'dont-block
12573 ;; If this is not a todo state change, or if this entry is already DONE,
12574 ;; do not block
12575 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12576 (member (plist-get change-plist :from)
12577 (cons 'done org-done-keywords))
12578 (member (plist-get change-plist :to)
12579 (cons 'todo org-not-done-keywords))
12580 (not (plist-get change-plist :to)))
12581 (throw 'dont-block t))
12582 ;; If this task has checkboxes that are not checked, it's blocked
12583 (save-excursion
12584 (org-back-to-heading t)
12585 (let ((beg (point)) end)
12586 (outline-next-heading)
12587 (setq end (point))
12588 (goto-char beg)
12589 (if (org-list-search-forward
12590 (concat (org-item-beginning-re)
12591 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12592 "\\[[- ]\\]")
12593 end t)
12594 (progn
12595 (if (boundp 'org-blocked-by-checkboxes)
12596 (setq org-blocked-by-checkboxes t))
12597 (throw 'dont-block nil)))))
12598 t))) ; do not block
12600 (defun org-entry-blocked-p ()
12601 "Is the current entry blocked?"
12602 (org-with-silent-modifications
12603 (if (org-entry-get nil "NOBLOCKING")
12604 nil ;; Never block this entry
12605 (not (run-hook-with-args-until-failure
12606 'org-blocker-hook
12607 (list :type 'todo-state-change
12608 :position (point)
12609 :from 'todo
12610 :to 'done))))))
12612 (defun org-update-statistics-cookies (all)
12613 "Update the statistics cookie, either from TODO or from checkboxes.
12614 This should be called with the cursor in a line with a statistics cookie."
12615 (interactive "P")
12616 (if all
12617 (progn
12618 (org-update-checkbox-count 'all)
12619 (org-map-entries 'org-update-parent-todo-statistics))
12620 (if (not (org-at-heading-p))
12621 (org-update-checkbox-count)
12622 (let ((pos (point-marker))
12623 end l1 l2)
12624 (ignore-errors (org-back-to-heading t))
12625 (if (not (org-at-heading-p))
12626 (org-update-checkbox-count)
12627 (setq l1 (org-outline-level))
12628 (setq end (save-excursion
12629 (outline-next-heading)
12630 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12631 (point)))
12632 (if (and (save-excursion
12633 (re-search-forward
12634 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12635 (not (save-excursion (re-search-forward
12636 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12637 (org-update-checkbox-count)
12638 (if (and l2 (> l2 l1))
12639 (progn
12640 (goto-char end)
12641 (org-update-parent-todo-statistics))
12642 (goto-char pos)
12643 (beginning-of-line 1)
12644 (while (re-search-forward
12645 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12646 (point-at-eol) t)
12647 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12648 (goto-char pos)
12649 (move-marker pos nil)))))
12651 (defvar org-entry-property-inherited-from) ;; defined below
12652 (defun org-update-parent-todo-statistics ()
12653 "Update any statistics cookie in the parent of the current headline.
12654 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12655 the entire subtree and this will travel up the hierarchy and update
12656 statistics everywhere."
12657 (let* ((prop (save-excursion (org-up-heading-safe)
12658 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12659 (recursive (or (not org-hierarchical-todo-statistics)
12660 (and prop (string-match "\\<recursive\\>" prop))))
12661 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12663 (first t)
12664 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12665 level ltoggle l1 new ndel
12666 (cnt-all 0) (cnt-done 0) is-percent kwd
12667 checkbox-beg ov ovs ove cookie-present)
12668 (catch 'exit
12669 (save-excursion
12670 (beginning-of-line 1)
12671 (setq ltoggle (funcall outline-level))
12672 ;; Three situations are to consider:
12674 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12675 ;; to the top-level ancestor on the headline;
12677 ;; 2. If parent has "recursive" property, repeat up to the
12678 ;; headline setting that property, taking inheritance into
12679 ;; account;
12681 ;; 3. Else, move up to direct parent and proceed only once.
12682 (while (and (setq level (org-up-heading-safe))
12683 (or recursive first)
12684 (>= (point) lim))
12685 (setq first nil cookie-present nil)
12686 (unless (and level
12687 (not (string-match
12688 "\\<checkbox\\>"
12689 (downcase (or (org-entry-get nil "COOKIE_DATA")
12690 "")))))
12691 (throw 'exit nil))
12692 (while (re-search-forward box-re (point-at-eol) t)
12693 (setq cnt-all 0 cnt-done 0 cookie-present t)
12694 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12695 (save-match-data
12696 (unless (outline-next-heading) (throw 'exit nil))
12697 (while (and (looking-at org-complex-heading-regexp)
12698 (> (setq l1 (length (match-string 1))) level))
12699 (setq kwd (and (or recursive (= l1 ltoggle))
12700 (match-string 2)))
12701 (if (or (eq org-provide-todo-statistics 'all-headlines)
12702 (and (eq org-provide-todo-statistics t)
12703 (or (member kwd org-done-keywords)))
12704 (and (listp org-provide-todo-statistics)
12705 (stringp (car org-provide-todo-statistics))
12706 (or (member kwd org-provide-todo-statistics)
12707 (member kwd org-done-keywords)))
12708 (and (listp org-provide-todo-statistics)
12709 (listp (car org-provide-todo-statistics))
12710 (or (member kwd (car org-provide-todo-statistics))
12711 (and (member kwd org-done-keywords)
12712 (member kwd (cadr org-provide-todo-statistics))))))
12713 (setq cnt-all (1+ cnt-all))
12714 (if (eq org-provide-todo-statistics t)
12715 (and kwd (setq cnt-all (1+ cnt-all)))))
12716 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12717 (member kwd org-done-keywords))
12718 (and (listp org-provide-todo-statistics)
12719 (listp (car org-provide-todo-statistics))
12720 (member kwd org-done-keywords)
12721 (member kwd (cadr org-provide-todo-statistics)))
12722 (and (listp org-provide-todo-statistics)
12723 (stringp (car org-provide-todo-statistics))
12724 (member kwd org-done-keywords)))
12725 (setq cnt-done (1+ cnt-done)))
12726 (outline-next-heading)))
12727 (setq new
12728 (if is-percent
12729 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12730 (format "[%d/%d]" cnt-done cnt-all))
12731 ndel (- (match-end 0) checkbox-beg))
12732 ;; handle overlays when updating cookie from column view
12733 (when (setq ov (car (overlays-at checkbox-beg)))
12734 (setq ovs (overlay-start ov) ove (overlay-end ov))
12735 (delete-overlay ov))
12736 (goto-char checkbox-beg)
12737 (insert new)
12738 (delete-region (point) (+ (point) ndel))
12739 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12740 (when ov (move-overlay ov ovs ove)))
12741 (when cookie-present
12742 (run-hook-with-args 'org-after-todo-statistics-hook
12743 cnt-done (- cnt-all cnt-done))))))
12744 (run-hooks 'org-todo-statistics-hook)))
12746 (defvar org-after-todo-statistics-hook nil
12747 "Hook that is called after a TODO statistics cookie has been updated.
12748 Each function is called with two arguments: the number of not-done entries
12749 and the number of done entries.
12751 For example, the following function, when added to this hook, will switch
12752 an entry to DONE when all children are done, and back to TODO when new
12753 entries are set to a TODO status. Note that this hook is only called
12754 when there is a statistics cookie in the headline!
12756 (defun org-summary-todo (n-done n-not-done)
12757 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12758 (let (org-log-done org-log-states) ; turn off logging
12759 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12762 (defvar org-todo-statistics-hook nil
12763 "Hook that is run whenever Org thinks TODO statistics should be updated.
12764 This hook runs even if there is no statistics cookie present, in which case
12765 `org-after-todo-statistics-hook' would not run.")
12767 (defun org-todo-trigger-tag-changes (state)
12768 "Apply the changes defined in `org-todo-state-tags-triggers'."
12769 (let ((l org-todo-state-tags-triggers)
12770 changes)
12771 (when (or (not state) (equal state ""))
12772 (setq changes (append changes (cdr (assoc "" l)))))
12773 (when (and (stringp state) (> (length state) 0))
12774 (setq changes (append changes (cdr (assoc state l)))))
12775 (when (member state org-not-done-keywords)
12776 (setq changes (append changes (cdr (assoc 'todo l)))))
12777 (when (member state org-done-keywords)
12778 (setq changes (append changes (cdr (assoc 'done l)))))
12779 (dolist (c changes)
12780 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12782 (defun org-local-logging (value)
12783 "Get logging settings from a property VALUE."
12784 (let* (words w a)
12785 ;; directly set the variables, they are already local.
12786 (setq org-log-done nil
12787 org-log-repeat nil
12788 org-todo-log-states nil)
12789 (setq words (org-split-string value))
12790 (while (setq w (pop words))
12791 (cond
12792 ((setq a (assoc w org-startup-options))
12793 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12794 (set (nth 1 a) (nth 2 a))))
12795 ((setq a (org-extract-log-state-settings w))
12796 (and (member (car a) org-todo-keywords-1)
12797 (push a org-todo-log-states)))))))
12799 (defun org-get-todo-sequence-head (kwd)
12800 "Return the head of the TODO sequence to which KWD belongs.
12801 If KWD is not set, check if there is a text property remembering the
12802 right sequence."
12803 (let (p)
12804 (cond
12805 ((not kwd)
12806 (or (get-text-property (point-at-bol) 'org-todo-head)
12807 (progn
12808 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12809 nil (point-at-eol)))
12810 (get-text-property p 'org-todo-head))))
12811 ((not (member kwd org-todo-keywords-1))
12812 (car org-todo-keywords-1))
12813 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12815 (defun org-fast-todo-selection ()
12816 "Fast TODO keyword selection with single keys.
12817 Returns the new TODO keyword, or nil if no state change should occur."
12818 (let* ((fulltable org-todo-key-alist)
12819 (done-keywords org-done-keywords) ;; needed for the faces.
12820 (maxlen (apply 'max (mapcar
12821 (lambda (x)
12822 (if (stringp (car x)) (string-width (car x)) 0))
12823 fulltable)))
12824 (expert nil)
12825 (fwidth (+ maxlen 3 1 3))
12826 (ncol (/ (- (window-width) 4) fwidth))
12827 tg cnt e c tbl
12828 groups ingroup)
12829 (save-excursion
12830 (save-window-excursion
12831 (if expert
12832 (set-buffer (get-buffer-create " *Org todo*"))
12833 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12834 (erase-buffer)
12835 (org-set-local 'org-done-keywords done-keywords)
12836 (setq tbl fulltable cnt 0)
12837 (while (setq e (pop tbl))
12838 (cond
12839 ((equal e '(:startgroup))
12840 (push '() groups) (setq ingroup t)
12841 (when (not (= cnt 0))
12842 (setq cnt 0)
12843 (insert "\n"))
12844 (insert "{ "))
12845 ((equal e '(:endgroup))
12846 (setq ingroup nil cnt 0)
12847 (insert "}\n"))
12848 ((equal e '(:newline))
12849 (when (not (= cnt 0))
12850 (setq cnt 0)
12851 (insert "\n")
12852 (setq e (car tbl))
12853 (while (equal (car tbl) '(:newline))
12854 (insert "\n")
12855 (setq tbl (cdr tbl)))))
12857 (setq tg (car e) c (cdr e))
12858 (if ingroup (push tg (car groups)))
12859 (setq tg (org-add-props tg nil 'face
12860 (org-get-todo-face tg)))
12861 (if (and (= cnt 0) (not ingroup)) (insert " "))
12862 (insert "[" c "] " tg (make-string
12863 (- fwidth 4 (length tg)) ?\ ))
12864 (when (= (setq cnt (1+ cnt)) ncol)
12865 (insert "\n")
12866 (if ingroup (insert " "))
12867 (setq cnt 0)))))
12868 (insert "\n")
12869 (goto-char (point-min))
12870 (if (not expert) (org-fit-window-to-buffer))
12871 (message "[a-z..]:Set [SPC]:clear")
12872 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12873 (cond
12874 ((or (= c ?\C-g)
12875 (and (= c ?q) (not (rassoc c fulltable))))
12876 (setq quit-flag t))
12877 ((= c ?\ ) nil)
12878 ((setq e (rassoc c fulltable) tg (car e))
12880 (t (setq quit-flag t)))))))
12882 (defun org-entry-is-todo-p ()
12883 (member (org-get-todo-state) org-not-done-keywords))
12885 (defun org-entry-is-done-p ()
12886 (member (org-get-todo-state) org-done-keywords))
12888 (defun org-get-todo-state ()
12889 "Return the TODO keyword of the current subtree."
12890 (save-excursion
12891 (org-back-to-heading t)
12892 (and (looking-at org-todo-line-regexp)
12893 (match-end 2)
12894 (match-string 2))))
12896 (defun org-at-date-range-p (&optional inactive-ok)
12897 "Is the cursor inside a date range?"
12898 (interactive)
12899 (save-excursion
12900 (catch 'exit
12901 (let ((pos (point)))
12902 (skip-chars-backward "^[<\r\n")
12903 (skip-chars-backward "<[")
12904 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12905 (>= (match-end 0) pos)
12906 (throw 'exit t))
12907 (skip-chars-backward "^<[\r\n")
12908 (skip-chars-backward "<[")
12909 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12910 (>= (match-end 0) pos)
12911 (throw 'exit t)))
12912 nil)))
12914 (defun org-get-repeat (&optional tagline)
12915 "Check if there is a deadline/schedule with repeater in this entry."
12916 (save-match-data
12917 (save-excursion
12918 (org-back-to-heading t)
12919 (and (re-search-forward (if tagline
12920 (concat tagline "\\s-*" org-repeat-re)
12921 org-repeat-re)
12922 (org-entry-end-position) t)
12923 (match-string-no-properties 1)))))
12925 (defvar org-last-changed-timestamp)
12926 (defvar org-last-inserted-timestamp)
12927 (defvar org-log-post-message)
12928 (defvar org-log-note-purpose)
12929 (defvar org-log-note-how)
12930 (defvar org-log-note-extra)
12931 (defun org-auto-repeat-maybe (done-word)
12932 "Check if the current headline contains a repeated deadline/schedule.
12933 If yes, set TODO state back to what it was and change the base date
12934 of repeating deadline/scheduled time stamps to new date.
12935 This function is run automatically after each state change to a DONE state."
12936 ;; last-state is dynamically scoped into this function
12937 (let* ((repeat (org-get-repeat))
12938 (aa (assoc org-last-state org-todo-kwd-alist))
12939 (interpret (nth 1 aa))
12940 (head (nth 2 aa))
12941 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12942 (msg "Entry repeats: ")
12943 (org-log-done nil)
12944 (org-todo-log-states nil)
12945 re type n what ts time to-state)
12946 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12947 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12948 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12949 org-todo-repeat-to-state))
12950 (unless (and to-state (member to-state org-todo-keywords-1))
12951 (setq to-state (if (eq interpret 'type) org-last-state head)))
12952 (org-todo to-state)
12953 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12954 (org-entry-put nil "LAST_REPEAT" (format-time-string
12955 (org-time-stamp-format t t))))
12956 (when org-log-repeat
12957 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12958 (memq 'org-add-log-note post-command-hook))
12959 ;; OK, we are already setup for some record
12960 (if (eq org-log-repeat 'note)
12961 ;; make sure we take a note, not only a time stamp
12962 (setq org-log-note-how 'note))
12963 ;; Set up for taking a record
12964 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12965 org-last-state
12966 'findpos org-log-repeat)))
12967 (org-back-to-heading t)
12968 (org-add-planning-info nil nil 'closed)
12969 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12970 org-deadline-time-regexp "\\)\\|\\("
12971 org-ts-regexp "\\)"))
12972 (while (re-search-forward
12973 re (save-excursion (outline-next-heading) (point)) t)
12974 (setq type (if (match-end 1) org-scheduled-string
12975 (if (match-end 3) org-deadline-string "Plain:"))
12976 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12977 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12978 (setq n (string-to-number (match-string 2 ts))
12979 what (match-string 3 ts))
12980 (if (equal what "w") (setq n (* n 7) what "d"))
12981 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12982 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12983 ;; Preparation, see if we need to modify the start date for the change
12984 (when (match-end 1)
12985 (setq time (save-match-data (org-time-string-to-time ts)))
12986 (cond
12987 ((equal (match-string 1 ts) ".")
12988 ;; Shift starting date to today
12989 (org-timestamp-change
12990 (- (org-today) (time-to-days time))
12991 'day))
12992 ((equal (match-string 1 ts) "+")
12993 (let ((nshiftmax 10) (nshift 0))
12994 (while (or (= nshift 0)
12995 (<= (time-to-days time)
12996 (time-to-days (current-time))))
12997 (when (= (incf nshift) nshiftmax)
12998 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12999 (error "Abort")))
13000 (org-timestamp-change n (cdr (assoc what whata)))
13001 (org-at-timestamp-p t)
13002 (setq ts (match-string 1))
13003 (setq time (save-match-data (org-time-string-to-time ts)))))
13004 (org-timestamp-change (- n) (cdr (assoc what whata)))
13005 ;; rematch, so that we have everything in place for the real shift
13006 (org-at-timestamp-p t)
13007 (setq ts (match-string 1))
13008 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13009 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13010 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13011 (setq org-log-post-message msg)
13012 (message "%s" msg))))
13014 (defun org-show-todo-tree (arg)
13015 "Make a compact tree which shows all headlines marked with TODO.
13016 The tree will show the lines where the regexp matches, and all higher
13017 headlines above the match.
13018 With a \\[universal-argument] prefix, prompt for a regexp to match.
13019 With a numeric prefix N, construct a sparse tree for the Nth element
13020 of `org-todo-keywords-1'."
13021 (interactive "P")
13022 (let ((case-fold-search nil)
13023 (kwd-re
13024 (cond ((null arg) org-not-done-regexp)
13025 ((equal arg '(4))
13026 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13027 (mapcar 'list org-todo-keywords-1))))
13028 (concat "\\("
13029 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13030 "\\)\\>")))
13031 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13032 (regexp-quote (nth (1- (prefix-numeric-value arg))
13033 org-todo-keywords-1)))
13034 (t (user-error "Invalid prefix argument: %s" arg)))))
13035 (message "%d TODO entries found"
13036 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13038 (defun org-deadline (arg &optional time)
13039 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13040 With one universal prefix argument, remove any deadline from the item.
13041 With two universal prefix arguments, prompt for a warning delay.
13042 With argument TIME, set the deadline at the corresponding date. TIME
13043 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13044 (interactive "P")
13045 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13046 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13047 'region-start-level 'region))
13048 org-loop-over-headlines-in-active-region)
13049 (org-map-entries
13050 `(org-deadline ',arg ,time)
13051 org-loop-over-headlines-in-active-region
13052 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13053 (let* ((old-date (org-entry-get nil "DEADLINE"))
13054 (old-date-time (if old-date (org-time-string-to-time old-date)))
13055 (repeater (and old-date
13056 (string-match
13057 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13058 old-date)
13059 (match-string 1 old-date))))
13060 (cond
13061 ((equal arg '(4))
13062 (when (and old-date org-log-redeadline)
13063 (org-add-log-setup 'deldeadline nil old-date 'findpos
13064 org-log-redeadline))
13065 (org-remove-timestamp-with-keyword org-deadline-string)
13066 (message "Item no longer has a deadline."))
13067 ((equal arg '(16))
13068 (save-excursion
13069 (org-back-to-heading t)
13070 (if (re-search-forward
13071 org-deadline-time-regexp
13072 (save-excursion (outline-next-heading) (point)) t)
13073 (let* ((rpl0 (match-string 1))
13074 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13075 (replace-match
13076 (concat org-deadline-string
13077 " <" rpl
13078 (format " -%dd"
13079 (abs
13080 (- (time-to-days
13081 (save-match-data
13082 (org-read-date nil t nil "Warn starting from" old-date-time)))
13083 (time-to-days old-date-time))))
13084 ">") t t))
13085 (user-error "No deadline information to update"))))
13087 (org-add-planning-info 'deadline time 'closed)
13088 (when (and old-date org-log-redeadline
13089 (not (equal old-date
13090 (substring org-last-inserted-timestamp 1 -1))))
13091 (org-add-log-setup 'redeadline nil old-date 'findpos
13092 org-log-redeadline))
13093 (when repeater
13094 (save-excursion
13095 (org-back-to-heading t)
13096 (when (re-search-forward (concat org-deadline-string " "
13097 org-last-inserted-timestamp)
13098 (save-excursion
13099 (outline-next-heading) (point)) t)
13100 (goto-char (1- (match-end 0)))
13101 (insert " " repeater)
13102 (setq org-last-inserted-timestamp
13103 (concat (substring org-last-inserted-timestamp 0 -1)
13104 " " repeater
13105 (substring org-last-inserted-timestamp -1))))))
13106 (message "Deadline on %s" org-last-inserted-timestamp))))))
13108 (defun org-schedule (arg &optional time)
13109 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13110 With one universal prefix argument, remove any scheduling date from the item.
13111 With two universal prefix arguments, prompt for a delay cookie.
13112 With argument TIME, scheduled at the corresponding date. TIME can
13113 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13114 (interactive "P")
13115 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13116 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13117 'region-start-level 'region))
13118 org-loop-over-headlines-in-active-region)
13119 (org-map-entries
13120 `(org-schedule ',arg ,time)
13121 org-loop-over-headlines-in-active-region
13122 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13123 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13124 (old-date-time (if old-date (org-time-string-to-time old-date)))
13125 (repeater (and old-date
13126 (string-match
13127 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13128 old-date)
13129 (match-string 1 old-date))))
13130 (cond
13131 ((equal arg '(4))
13132 (progn
13133 (when (and old-date org-log-reschedule)
13134 (org-add-log-setup 'delschedule nil old-date 'findpos
13135 org-log-reschedule))
13136 (org-remove-timestamp-with-keyword org-scheduled-string)
13137 (message "Item is no longer scheduled.")))
13138 ((equal arg '(16))
13139 (save-excursion
13140 (org-back-to-heading t)
13141 (if (re-search-forward
13142 org-scheduled-time-regexp
13143 (save-excursion (outline-next-heading) (point)) t)
13144 (let* ((rpl0 (match-string 1))
13145 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13146 (replace-match
13147 (concat org-scheduled-string
13148 " <" rpl
13149 (format " -%dd"
13150 (abs
13151 (- (time-to-days
13152 (save-match-data
13153 (org-read-date nil t nil "Delay until" old-date-time)))
13154 (time-to-days old-date-time))))
13155 ">") t t))
13156 (user-error "No scheduled information to update"))))
13158 (org-add-planning-info 'scheduled time 'closed)
13159 (when (and old-date org-log-reschedule
13160 (not (equal old-date
13161 (substring org-last-inserted-timestamp 1 -1))))
13162 (org-add-log-setup 'reschedule nil old-date 'findpos
13163 org-log-reschedule))
13164 (when repeater
13165 (save-excursion
13166 (org-back-to-heading t)
13167 (when (re-search-forward (concat org-scheduled-string " "
13168 org-last-inserted-timestamp)
13169 (save-excursion
13170 (outline-next-heading) (point)) t)
13171 (goto-char (1- (match-end 0)))
13172 (insert " " repeater)
13173 (setq org-last-inserted-timestamp
13174 (concat (substring org-last-inserted-timestamp 0 -1)
13175 " " repeater
13176 (substring org-last-inserted-timestamp -1))))))
13177 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13179 (defun org-get-scheduled-time (pom &optional inherit)
13180 "Get the scheduled time as a time tuple, of a format suitable
13181 for calling org-schedule with, or if there is no scheduling,
13182 returns nil."
13183 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13184 (when time
13185 (apply 'encode-time (org-parse-time-string time)))))
13187 (defun org-get-deadline-time (pom &optional inherit)
13188 "Get the deadline as a time tuple, of a format suitable for
13189 calling org-deadline with, or if there is no scheduling, returns
13190 nil."
13191 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13192 (when time
13193 (apply 'encode-time (org-parse-time-string time)))))
13195 (defun org-remove-timestamp-with-keyword (keyword)
13196 "Remove all time stamps with KEYWORD in the current entry."
13197 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13198 beg)
13199 (save-excursion
13200 (org-back-to-heading t)
13201 (setq beg (point))
13202 (outline-next-heading)
13203 (while (re-search-backward re beg t)
13204 (replace-match "")
13205 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13206 (equal (char-before) ?\ ))
13207 (backward-delete-char 1)
13208 (if (string-match "^[ \t]*$" (buffer-substring
13209 (point-at-bol) (point-at-eol)))
13210 (delete-region (point-at-bol)
13211 (min (point-max) (1+ (point-at-eol))))))))))
13213 (defvar org-time-was-given) ; dynamically scoped parameter
13214 (defvar org-end-time-was-given) ; dynamically scoped parameter
13216 (defun org-add-planning-info (what &optional time &rest remove)
13217 "Insert new timestamp with keyword in the line directly after the headline.
13218 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13219 If non is given, the user is prompted for a date.
13220 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13221 be removed."
13222 (interactive)
13223 (let (org-time-was-given org-end-time-was-given ts
13224 end default-time default-input)
13226 (catch 'exit
13227 (when (and (memq what '(scheduled deadline))
13228 (or (not time)
13229 (and (stringp time)
13230 (string-match "^[-+]+[0-9]" time))))
13231 ;; Try to get a default date/time from existing timestamp
13232 (save-excursion
13233 (org-back-to-heading t)
13234 (setq end (save-excursion (outline-next-heading) (point)))
13235 (when (re-search-forward (if (eq what 'scheduled)
13236 org-scheduled-time-regexp
13237 org-deadline-time-regexp)
13238 end t)
13239 (setq ts (match-string 1)
13240 default-time
13241 (apply 'encode-time (org-parse-time-string ts))
13242 default-input (and ts (org-get-compact-tod ts))))))
13243 (when what
13244 (setq time
13245 (if (stringp time)
13246 ;; This is a string (relative or absolute), set proper date
13247 (apply 'encode-time
13248 (org-read-date-analyze
13249 time default-time (decode-time default-time)))
13250 ;; If necessary, get the time from the user
13251 (or time (org-read-date nil 'to-time nil nil
13252 default-time default-input)))))
13254 (when (and org-insert-labeled-timestamps-at-point
13255 (member what '(scheduled deadline)))
13256 (insert
13257 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13258 (org-insert-time-stamp time org-time-was-given
13259 nil nil nil (list org-end-time-was-given))
13260 (setq what nil))
13261 (save-excursion
13262 (save-restriction
13263 (let (col list elt ts buffer-invisibility-spec)
13264 (org-back-to-heading t)
13265 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13266 (goto-char (match-end 1))
13267 (setq col (current-column))
13268 (goto-char (match-end 0))
13269 (if (eobp) (insert "\n") (forward-char 1))
13270 (when (and (not what)
13271 (not (looking-at
13272 (concat "[ \t]*"
13273 org-keyword-time-not-clock-regexp))))
13274 ;; Nothing to add, nothing to remove...... :-)
13275 (throw 'exit nil))
13276 (if (and (not (looking-at org-outline-regexp))
13277 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13278 "[^\r\n]*"))
13279 (not (equal (match-string 1) org-clock-string)))
13280 (narrow-to-region (match-beginning 0) (match-end 0))
13281 (insert-before-markers "\n")
13282 (backward-char 1)
13283 (narrow-to-region (point) (point))
13284 (and org-adapt-indentation (org-indent-to-column col)))
13285 ;; Check if we have to remove something.
13286 (setq list (cons what remove))
13287 (while list
13288 (setq elt (pop list))
13289 (when (or (and (eq elt 'scheduled)
13290 (re-search-forward org-scheduled-time-regexp nil t))
13291 (and (eq elt 'deadline)
13292 (re-search-forward org-deadline-time-regexp nil t))
13293 (and (eq elt 'closed)
13294 (re-search-forward org-closed-time-regexp nil t)))
13295 (replace-match "")
13296 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13297 (and (looking-at "[ \t]+") (replace-match ""))
13298 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13299 (when what
13300 (insert
13301 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13302 (cond ((eq what 'scheduled) org-scheduled-string)
13303 ((eq what 'deadline) org-deadline-string)
13304 ((eq what 'closed) org-closed-string))
13305 " ")
13306 (setq ts (org-insert-time-stamp
13307 time
13308 (or org-time-was-given
13309 (and (eq what 'closed) org-log-done-with-time))
13310 (eq what 'closed)
13311 nil nil (list org-end-time-was-given)))
13312 (insert
13313 (if (not (or (bolp) (eq (char-before) ?\ )
13314 (memq (char-after) '(32 10))
13315 (eobp))) " " ""))
13316 (end-of-line 1))
13317 (goto-char (point-min))
13318 (widen)
13319 (if (and (looking-at "[ \t]*\n")
13320 (equal (char-before) ?\n))
13321 (delete-region (1- (point)) (point-at-eol)))
13322 ts))))))
13324 (defvar org-log-note-marker (make-marker))
13325 (defvar org-log-note-purpose nil)
13326 (defvar org-log-note-state nil)
13327 (defvar org-log-note-previous-state nil)
13328 (defvar org-log-note-how nil)
13329 (defvar org-log-note-extra nil)
13330 (defvar org-log-note-window-configuration nil)
13331 (defvar org-log-note-return-to (make-marker))
13332 (defvar org-log-note-effective-time nil
13333 "Remembered current time so that dynamically scoped
13334 `org-extend-today-until' affects tha timestamps in state change
13335 log")
13337 (defvar org-log-post-message nil
13338 "Message to be displayed after a log note has been stored.
13339 The auto-repeater uses this.")
13341 (defun org-add-note ()
13342 "Add a note to the current entry.
13343 This is done in the same way as adding a state change note."
13344 (interactive)
13345 (org-add-log-setup 'note nil nil 'findpos nil))
13347 (defvar org-property-end-re)
13348 (defun org-add-log-setup (&optional purpose state prev-state
13349 findpos how extra)
13350 "Set up the post command hook to take a note.
13351 If this is about to TODO state change, the new state is expected in STATE.
13352 When FINDPOS is non-nil, find the correct position for the note in
13353 the current entry. If not, assume that it can be inserted at point.
13354 HOW is an indicator what kind of note should be created.
13355 EXTRA is additional text that will be inserted into the notes buffer."
13356 (let* ((org-log-into-drawer (org-log-into-drawer))
13357 (drawer (cond ((stringp org-log-into-drawer)
13358 org-log-into-drawer)
13359 (org-log-into-drawer "LOGBOOK"))))
13360 (save-restriction
13361 (save-excursion
13362 (when findpos
13363 (org-back-to-heading t)
13364 (narrow-to-region (point) (save-excursion
13365 (outline-next-heading) (point)))
13366 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13367 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13368 "[^\r\n]*\\)?"))
13369 (goto-char (match-end 0))
13370 (cond
13371 (drawer
13372 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13373 nil t)
13374 (progn
13375 (goto-char (match-end 0))
13376 (or org-log-states-order-reversed
13377 (and (re-search-forward org-property-end-re nil t)
13378 (goto-char (1- (match-beginning 0))))))
13379 (insert "\n:" drawer ":\n:END:")
13380 (beginning-of-line 0)
13381 (org-indent-line)
13382 (beginning-of-line 2)
13383 (org-indent-line)
13384 (end-of-line 0)))
13385 ((and org-log-state-notes-insert-after-drawers
13386 (save-excursion
13387 (forward-line) (looking-at org-drawer-regexp)))
13388 (forward-line)
13389 (while (looking-at org-drawer-regexp)
13390 (goto-char (match-end 0))
13391 (re-search-forward org-property-end-re (point-max) t)
13392 (forward-line))
13393 (forward-line -1)))
13394 (unless org-log-states-order-reversed
13395 (and (= (char-after) ?\n) (forward-char 1))
13396 (org-skip-over-state-notes)
13397 (skip-chars-backward " \t\n\r")))
13398 (move-marker org-log-note-marker (point))
13399 (setq org-log-note-purpose purpose
13400 org-log-note-state state
13401 org-log-note-previous-state prev-state
13402 org-log-note-how how
13403 org-log-note-extra extra
13404 org-log-note-effective-time (org-current-effective-time))
13405 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13407 (defun org-skip-over-state-notes ()
13408 "Skip past the list of State notes in an entry."
13409 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13410 (when (ignore-errors (goto-char (org-in-item-p)))
13411 (let* ((struct (org-list-struct))
13412 (prevs (org-list-prevs-alist struct)))
13413 (while (looking-at "[ \t]*- State")
13414 (goto-char (or (org-list-get-next-item (point) struct prevs)
13415 (org-list-get-item-end (point) struct)))))))
13417 (defun org-add-log-note (&optional purpose)
13418 "Pop up a window for taking a note, and add this note later at point."
13419 (remove-hook 'post-command-hook 'org-add-log-note)
13420 (setq org-log-note-window-configuration (current-window-configuration))
13421 (delete-other-windows)
13422 (move-marker org-log-note-return-to (point))
13423 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13424 (goto-char org-log-note-marker)
13425 (org-switch-to-buffer-other-window "*Org Note*")
13426 (erase-buffer)
13427 (if (memq org-log-note-how '(time state))
13428 (let (current-prefix-arg) (org-store-log-note))
13429 (let ((org-inhibit-startup t)) (org-mode))
13430 (insert (format "# Insert note for %s.
13431 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13432 (cond
13433 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13434 ((eq org-log-note-purpose 'done) "closed todo item")
13435 ((eq org-log-note-purpose 'state)
13436 (format "state change from \"%s\" to \"%s\""
13437 (or org-log-note-previous-state "")
13438 (or org-log-note-state "")))
13439 ((eq org-log-note-purpose 'reschedule)
13440 "rescheduling")
13441 ((eq org-log-note-purpose 'delschedule)
13442 "no longer scheduled")
13443 ((eq org-log-note-purpose 'redeadline)
13444 "changing deadline")
13445 ((eq org-log-note-purpose 'deldeadline)
13446 "removing deadline")
13447 ((eq org-log-note-purpose 'refile)
13448 "refiling")
13449 ((eq org-log-note-purpose 'note)
13450 "this entry")
13451 (t (error "This should not happen")))))
13452 (if org-log-note-extra (insert org-log-note-extra))
13453 (org-set-local 'org-finish-function 'org-store-log-note)
13454 (run-hooks 'org-log-buffer-setup-hook)))
13456 (defvar org-note-abort nil) ; dynamically scoped
13457 (defun org-store-log-note ()
13458 "Finish taking a log note, and insert it to where it belongs."
13459 (let ((txt (buffer-string)))
13460 (kill-buffer (current-buffer))
13461 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13462 lines ind bul)
13463 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13464 (setq txt (replace-match "" t t txt)))
13465 (if (string-match "\\s-+\\'" txt)
13466 (setq txt (replace-match "" t t txt)))
13467 (setq lines (org-split-string txt "\n"))
13468 (when (and note (string-match "\\S-" note))
13469 (setq note
13470 (org-replace-escapes
13471 note
13472 (list (cons "%u" (user-login-name))
13473 (cons "%U" user-full-name)
13474 (cons "%t" (format-time-string
13475 (org-time-stamp-format 'long 'inactive)
13476 org-log-note-effective-time))
13477 (cons "%T" (format-time-string
13478 (org-time-stamp-format 'long nil)
13479 org-log-note-effective-time))
13480 (cons "%d" (format-time-string
13481 (org-time-stamp-format nil 'inactive)
13482 org-log-note-effective-time))
13483 (cons "%D" (format-time-string
13484 (org-time-stamp-format nil nil)
13485 org-log-note-effective-time))
13486 (cons "%s" (if org-log-note-state
13487 (concat "\"" org-log-note-state "\"")
13488 ""))
13489 (cons "%S" (if org-log-note-previous-state
13490 (concat "\"" org-log-note-previous-state "\"")
13491 "\"\"")))))
13492 (if lines (setq note (concat note " \\\\")))
13493 (push note lines))
13494 (when (or current-prefix-arg org-note-abort)
13495 (when org-log-into-drawer
13496 (org-remove-empty-drawer-at org-log-note-marker))
13497 (setq lines nil))
13498 (when lines
13499 (with-current-buffer (marker-buffer org-log-note-marker)
13500 (save-excursion
13501 (goto-char org-log-note-marker)
13502 (move-marker org-log-note-marker nil)
13503 (end-of-line 1)
13504 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13505 (setq ind (save-excursion
13506 (if (ignore-errors (goto-char (org-in-item-p)))
13507 (let ((struct (org-list-struct)))
13508 (org-list-get-ind
13509 (org-list-get-top-point struct) struct))
13510 (skip-chars-backward " \r\t\n")
13511 (cond
13512 ((and (org-at-heading-p)
13513 org-adapt-indentation)
13514 (1+ (org-current-level)))
13515 ((org-at-heading-p) 0)
13516 (t (org-get-indentation))))))
13517 (setq bul (org-list-bullet-string "-"))
13518 (org-indent-line-to ind)
13519 (insert bul (pop lines))
13520 (let ((ind-body (+ (length bul) ind)))
13521 (while lines
13522 (insert "\n")
13523 (org-indent-line-to ind-body)
13524 (insert (pop lines))))
13525 (message "Note stored")
13526 (org-back-to-heading t)
13527 (org-cycle-hide-drawers 'children))
13528 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13529 ;; from within `org-add-log-note' because `buffer-undo-list'
13530 ;; is then modified outside of `org-with-remote-undo'.
13531 (when (eq this-command 'org-agenda-todo)
13532 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13533 ;; Don't add undo information when called from `org-agenda-todo'
13534 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13535 (set-window-configuration org-log-note-window-configuration)
13536 (with-current-buffer (marker-buffer org-log-note-return-to)
13537 (goto-char org-log-note-return-to))
13538 (move-marker org-log-note-return-to nil)
13539 (and org-log-post-message (message "%s" org-log-post-message))))
13541 (defun org-remove-empty-drawer-at (pos)
13542 "Remove an empty drawer at position POS.
13543 POS may also be a marker."
13544 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13545 (org-with-wide-buffer
13546 (goto-char pos)
13547 (let ((drawer (org-element-at-point)))
13548 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13549 (not (org-element-property :contents-begin drawer)))
13550 (delete-region (org-element-property :begin drawer)
13551 (progn (goto-char (org-element-property :end drawer))
13552 (skip-chars-backward " \r\t\n")
13553 (forward-line)
13554 (point))))))))
13556 (defvar org-ts-type nil)
13557 (defun org-sparse-tree (&optional arg type)
13558 "Create a sparse tree, prompt for the details.
13559 This command can create sparse trees. You first need to select the type
13560 of match used to create the tree:
13562 t Show all TODO entries.
13563 T Show entries with a specific TODO keyword.
13564 m Show entries selected by a tags/property match.
13565 p Enter a property name and its value (both with completion on existing
13566 names/values) and show entries with that property.
13567 r Show entries matching a regular expression (`/' can be used as well).
13568 b Show deadlines and scheduled items before a date.
13569 a Show deadlines and scheduled items after a date.
13570 d Show deadlines due within `org-deadline-warning-days'.
13571 D Show deadlines and scheduled items between a date range."
13572 (interactive "P")
13573 (let (ans kwd value ts-type)
13574 (setq type (or type org-sparse-tree-default-date-type))
13575 (setq org-ts-type type)
13576 (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"
13577 (cond ((eq type 'all) "all timestamps")
13578 ((eq type 'scheduled) "only scheduled")
13579 ((eq type 'deadline) "only deadline")
13580 ((eq type 'active) "only active timestamps")
13581 ((eq type 'inactive) "only inactive timestamps")
13582 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13583 ((eq type 'closed) "with a closed time-stamp")
13584 (t "scheduled/deadline")))
13585 (setq ans (read-char-exclusive))
13586 (cond
13587 ((equal ans ?c)
13588 (org-sparse-tree
13589 arg (cadr (member type '(scheduled-or-deadline
13590 all scheduled deadline active inactive closed)))))
13591 ((equal ans ?d)
13592 (call-interactively 'org-check-deadlines))
13593 ((equal ans ?b)
13594 (call-interactively 'org-check-before-date))
13595 ((equal ans ?a)
13596 (call-interactively 'org-check-after-date))
13597 ((equal ans ?D)
13598 (call-interactively 'org-check-dates-range))
13599 ((equal ans ?t)
13600 (call-interactively 'org-show-todo-tree))
13601 ((equal ans ?T)
13602 (org-show-todo-tree '(4)))
13603 ((member ans '(?T ?m))
13604 (call-interactively 'org-match-sparse-tree))
13605 ((member ans '(?p ?P))
13606 (setq kwd (org-icompleting-read "Property: "
13607 (mapcar 'list (org-buffer-property-keys))))
13608 (setq value (org-icompleting-read "Value: "
13609 (mapcar 'list (org-property-values kwd))))
13610 (unless (string-match "\\`{.*}\\'" value)
13611 (setq value (concat "\"" value "\"")))
13612 (org-match-sparse-tree arg (concat kwd "=" value)))
13613 ((member ans '(?r ?R ?/))
13614 (call-interactively 'org-occur))
13615 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13617 (defvar org-occur-highlights nil
13618 "List of overlays used for occur matches.")
13619 (make-variable-buffer-local 'org-occur-highlights)
13620 (defvar org-occur-parameters nil
13621 "Parameters of the active org-occur calls.
13622 This is a list, each call to org-occur pushes as cons cell,
13623 containing the regular expression and the callback, onto the list.
13624 The list can contain several entries if `org-occur' has been called
13625 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13626 will only contain one set of parameters. When the highlights are
13627 removed (for example with `C-c C-c', or with the next edit (depending
13628 on `org-remove-highlights-with-change'), this variable is emptied
13629 as well.")
13630 (make-variable-buffer-local 'org-occur-parameters)
13632 (defun org-occur (regexp &optional keep-previous callback)
13633 "Make a compact tree which shows all matches of REGEXP.
13634 The tree will show the lines where the regexp matches, and all higher
13635 headlines above the match. It will also show the heading after the match,
13636 to make sure editing the matching entry is easy.
13637 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13638 call to `org-occur' will be kept, to allow stacking of calls to this
13639 command.
13640 If CALLBACK is non-nil, it is a function which is called to confirm
13641 that the match should indeed be shown."
13642 (interactive "sRegexp: \nP")
13643 (when (equal regexp "")
13644 (user-error "Regexp cannot be empty"))
13645 (unless keep-previous
13646 (org-remove-occur-highlights nil nil t))
13647 (push (cons regexp callback) org-occur-parameters)
13648 (let ((cnt 0))
13649 (save-excursion
13650 (goto-char (point-min))
13651 (if (or (not keep-previous) ; do not want to keep
13652 (not org-occur-highlights)) ; no previous matches
13653 ;; hide everything
13654 (org-overview))
13655 (while (re-search-forward regexp nil t)
13656 (when (or (not callback)
13657 (save-match-data (funcall callback)))
13658 (setq cnt (1+ cnt))
13659 (when org-highlight-sparse-tree-matches
13660 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13661 (org-show-context 'occur-tree))))
13662 (when org-remove-highlights-with-change
13663 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13664 nil 'local))
13665 (unless org-sparse-tree-open-archived-trees
13666 (org-hide-archived-subtrees (point-min) (point-max)))
13667 (run-hooks 'org-occur-hook)
13668 (if (org-called-interactively-p 'interactive)
13669 (message "%d match(es) for regexp %s" cnt regexp))
13670 cnt))
13672 (defun org-occur-next-match (&optional n reset)
13673 "Function for `next-error-function' to find sparse tree matches.
13674 N is the number of matches to move, when negative move backwards.
13675 RESET is entirely ignored - this function always goes back to the
13676 starting point when no match is found."
13677 (let* ((limit (if (< n 0) (point-min) (point-max)))
13678 (search-func (if (< n 0)
13679 'previous-single-char-property-change
13680 'next-single-char-property-change))
13681 (n (abs n))
13682 (pos (point))
13684 (catch 'exit
13685 (while (setq p1 (funcall search-func (point) 'org-type))
13686 (when (equal p1 limit)
13687 (goto-char pos)
13688 (error "No more matches"))
13689 (when (equal (get-char-property p1 'org-type) 'org-occur)
13690 (setq n (1- n))
13691 (when (= n 0)
13692 (goto-char p1)
13693 (throw 'exit (point))))
13694 (goto-char p1))
13695 (goto-char p1)
13696 (error "No more matches"))))
13698 (defun org-show-context (&optional key)
13699 "Make sure point and context are visible.
13700 How much context is shown depends upon the variables
13701 `org-show-hierarchy-above', `org-show-following-heading',
13702 `org-show-entry-below' and `org-show-siblings'."
13703 (let ((heading-p (org-at-heading-p t))
13704 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13705 (following-p (org-get-alist-option org-show-following-heading key))
13706 (entry-p (org-get-alist-option org-show-entry-below key))
13707 (siblings-p (org-get-alist-option org-show-siblings key)))
13708 ;; Show heading or entry text
13709 (if (and heading-p (not entry-p))
13710 (org-flag-heading nil) ; only show the heading
13711 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13712 (org-show-hidden-entry))) ; show entire entry
13713 (when following-p
13714 ;; Show next sibling, or heading below text
13715 (save-excursion
13716 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13717 (org-flag-heading nil))))
13718 (when siblings-p (org-show-siblings))
13719 (when hierarchy-p
13720 ;; show all higher headings, possibly with siblings
13721 (save-excursion
13722 (while (and (condition-case nil
13723 (progn (org-up-heading-all 1) t)
13724 (error nil))
13725 (not (bobp)))
13726 (org-flag-heading nil)
13727 (when siblings-p (org-show-siblings)))))
13728 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13730 (defvar org-reveal-start-hook nil
13731 "Hook run before revealing a location.")
13733 (defun org-reveal (&optional siblings)
13734 "Show current entry, hierarchy above it, and the following headline.
13735 This can be used to show a consistent set of context around locations
13736 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13737 not t for the search context.
13739 With optional argument SIBLINGS, on each level of the hierarchy all
13740 siblings are shown. This repairs the tree structure to what it would
13741 look like when opened with hierarchical calls to `org-cycle'.
13742 With double optional argument \\[universal-argument] \\[universal-argument], \
13743 go to the parent and show the
13744 entire tree."
13745 (interactive "P")
13746 (run-hooks 'org-reveal-start-hook)
13747 (let ((org-show-hierarchy-above t)
13748 (org-show-following-heading t)
13749 (org-show-siblings (if siblings t org-show-siblings)))
13750 (org-show-context nil))
13751 (when (equal siblings '(16))
13752 (save-excursion
13753 (when (org-up-heading-safe)
13754 (org-show-subtree)
13755 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13757 (defun org-highlight-new-match (beg end)
13758 "Highlight from BEG to END and mark the highlight is an occur headline."
13759 (let ((ov (make-overlay beg end)))
13760 (overlay-put ov 'face 'secondary-selection)
13761 (overlay-put ov 'org-type 'org-occur)
13762 (push ov org-occur-highlights)))
13764 (defun org-remove-occur-highlights (&optional beg end noremove)
13765 "Remove the occur highlights from the buffer.
13766 BEG and END are ignored. If NOREMOVE is nil, remove this function
13767 from the `before-change-functions' in the current buffer."
13768 (interactive)
13769 (unless org-inhibit-highlight-removal
13770 (mapc 'delete-overlay org-occur-highlights)
13771 (setq org-occur-highlights nil)
13772 (setq org-occur-parameters nil)
13773 (unless noremove
13774 (remove-hook 'before-change-functions
13775 'org-remove-occur-highlights 'local))))
13777 ;;;; Priorities
13779 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13780 "Regular expression matching the priority indicator.")
13782 (defvar org-remove-priority-next-time nil)
13784 (defun org-priority-up ()
13785 "Increase the priority of the current item."
13786 (interactive)
13787 (org-priority 'up))
13789 (defun org-priority-down ()
13790 "Decrease the priority of the current item."
13791 (interactive)
13792 (org-priority 'down))
13794 (defun org-priority (&optional action show)
13795 "Change the priority of an item.
13796 ACTION can be `set', `up', `down', or a character."
13797 (interactive "P")
13798 (if (equal action '(4))
13799 (org-show-priority)
13800 (unless org-enable-priority-commands
13801 (user-error "Priority commands are disabled"))
13802 (setq action (or action 'set))
13803 (let (current new news have remove)
13804 (save-excursion
13805 (org-back-to-heading t)
13806 (if (looking-at org-priority-regexp)
13807 (setq current (string-to-char (match-string 2))
13808 have t))
13809 (cond
13810 ((eq action 'remove)
13811 (setq remove t new ?\ ))
13812 ((or (eq action 'set)
13813 (if (featurep 'xemacs) (characterp action) (integerp action)))
13814 (if (not (eq action 'set))
13815 (setq new action)
13816 (message "Priority %c-%c, SPC to remove: "
13817 org-highest-priority org-lowest-priority)
13818 (save-match-data
13819 (setq new (read-char-exclusive))))
13820 (if (and (= (upcase org-highest-priority) org-highest-priority)
13821 (= (upcase org-lowest-priority) org-lowest-priority))
13822 (setq new (upcase new)))
13823 (cond ((equal new ?\ ) (setq remove t))
13824 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13825 (user-error "Priority must be between `%c' and `%c'"
13826 org-highest-priority org-lowest-priority))))
13827 ((eq action 'up)
13828 (setq new (if have
13829 (1- current) ; normal cycling
13830 ;; last priority was empty
13831 (if (eq last-command this-command)
13832 org-lowest-priority ; wrap around empty to lowest
13833 ;; default
13834 (if org-priority-start-cycle-with-default
13835 org-default-priority
13836 (1- org-default-priority))))))
13837 ((eq action 'down)
13838 (setq new (if have
13839 (1+ current) ; normal cycling
13840 ;; last priority was empty
13841 (if (eq last-command this-command)
13842 org-highest-priority ; wrap around empty to highest
13843 ;; default
13844 (if org-priority-start-cycle-with-default
13845 org-default-priority
13846 (1+ org-default-priority))))))
13847 (t (user-error "Invalid action")))
13848 (if (or (< (upcase new) org-highest-priority)
13849 (> (upcase new) org-lowest-priority))
13850 (if (and (memq action '(up down))
13851 (not have) (not (eq last-command this-command)))
13852 ;; `new' is from default priority
13853 (error
13854 "The default can not be set, see `org-default-priority' why")
13855 ;; normal cycling: `new' is beyond highest/lowest priority
13856 ;; and is wrapped around to the empty priority
13857 (setq remove t)))
13858 (setq news (format "%c" new))
13859 (if have
13860 (if remove
13861 (replace-match "" t t nil 1)
13862 (replace-match news t t nil 2))
13863 (if remove
13864 (user-error "No priority cookie found in line")
13865 (let ((case-fold-search nil))
13866 (looking-at org-todo-line-regexp))
13867 (if (match-end 2)
13868 (progn
13869 (goto-char (match-end 2))
13870 (insert " [#" news "]"))
13871 (goto-char (match-beginning 3))
13872 (insert "[#" news "] "))))
13873 (org-set-tags nil 'align))
13874 (if remove
13875 (message "Priority removed")
13876 (message "Priority of current item set to %s" news)))))
13878 (defun org-show-priority ()
13879 "Show the priority of the current item.
13880 This priority is composed of the main priority given with the [#A] cookies,
13881 and by additional input from the age of a schedules or deadline entry."
13882 (interactive)
13883 (let ((pri (if (eq major-mode 'org-agenda-mode)
13884 (org-get-at-bol 'priority)
13885 (save-excursion
13886 (save-match-data
13887 (beginning-of-line)
13888 (and (looking-at org-heading-regexp)
13889 (org-get-priority (match-string 0))))))))
13890 (message "Priority is %d" (if pri pri -1000))))
13892 (defun org-get-priority (s)
13893 "Find priority cookie and return priority."
13894 (save-match-data
13895 (if (functionp org-get-priority-function)
13896 (funcall org-get-priority-function)
13897 (if (not (string-match org-priority-regexp s))
13898 (* 1000 (- org-lowest-priority org-default-priority))
13899 (* 1000 (- org-lowest-priority
13900 (string-to-char (match-string 2 s))))))))
13902 ;;;; Tags
13904 (defvar org-agenda-archives-mode)
13905 (defvar org-map-continue-from nil
13906 "Position from where mapping should continue.
13907 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13909 (defvar org-scanner-tags nil
13910 "The current tag list while the tags scanner is running.")
13911 (defvar org-trust-scanner-tags nil
13912 "Should `org-get-tags-at' use the tags for the scanner.
13913 This is for internal dynamical scoping only.
13914 When this is non-nil, the function `org-get-tags-at' will return the value
13915 of `org-scanner-tags' instead of building the list by itself. This
13916 can lead to large speed-ups when the tags scanner is used in a file with
13917 many entries, and when the list of tags is retrieved, for example to
13918 obtain a list of properties. Building the tags list for each entry in such
13919 a file becomes an N^2 operation - but with this variable set, it scales
13920 as N.")
13922 (defun org-scan-tags (action matcher todo-only &optional start-level)
13923 "Sca headline tags with inheritance and produce output ACTION.
13925 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13926 or `agenda' to produce an entry list for an agenda view. It can also be
13927 a Lisp form or a function that should be called at each matched headline, in
13928 this case the return value is a list of all return values from these calls.
13930 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13931 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13932 only lines with a not-done TODO keyword are included in the output.
13933 This should be the same variable that was scoped into
13934 and set by `org-make-tags-matcher' when it constructed MATCHER.
13936 START-LEVEL can be a string with asterisks, reducing the scope to
13937 headlines matching this string."
13938 (require 'org-agenda)
13939 (let* ((re (concat "^"
13940 (if start-level
13941 ;; Get the correct level to match
13942 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13943 org-outline-regexp)
13944 " *\\(\\<\\("
13945 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13946 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13947 (props (list 'face 'default
13948 'done-face 'org-agenda-done
13949 'undone-face 'default
13950 'mouse-face 'highlight
13951 'org-not-done-regexp org-not-done-regexp
13952 'org-todo-regexp org-todo-regexp
13953 'org-complex-heading-regexp org-complex-heading-regexp
13954 'help-echo
13955 (format "mouse-2 or RET jump to org file %s"
13956 (abbreviate-file-name
13957 (or (buffer-file-name (buffer-base-buffer))
13958 (buffer-name (buffer-base-buffer)))))))
13959 (org-map-continue-from nil)
13960 lspos tags tags-list
13961 (tags-alist (list (cons 0 org-file-tags)))
13962 (llast 0) rtn rtn1 level category i txt
13963 todo marker entry priority)
13964 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13965 (setq action (list 'lambda nil action)))
13966 (save-excursion
13967 (goto-char (point-min))
13968 (when (eq action 'sparse-tree)
13969 (org-overview)
13970 (org-remove-occur-highlights))
13971 (while (let (case-fold-search)
13972 (re-search-forward re nil t))
13973 (setq org-map-continue-from nil)
13974 (catch :skip
13975 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13976 tags (if (match-end 4) (org-match-string-no-properties 4)))
13977 (goto-char (setq lspos (match-beginning 0)))
13978 (setq level (org-reduced-level (org-outline-level))
13979 category (org-get-category))
13980 (setq i llast llast level)
13981 ;; remove tag lists from same and sublevels
13982 (while (>= i level)
13983 (when (setq entry (assoc i tags-alist))
13984 (setq tags-alist (delete entry tags-alist)))
13985 (setq i (1- i)))
13986 ;; add the next tags
13987 (when tags
13988 (setq tags (org-split-string tags ":")
13989 tags-alist
13990 (cons (cons level tags) tags-alist)))
13991 ;; compile tags for current headline
13992 (setq tags-list
13993 (if org-use-tag-inheritance
13994 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13995 tags)
13996 org-scanner-tags tags-list)
13997 (when org-use-tag-inheritance
13998 (setcdr (car tags-alist)
13999 (mapcar (lambda (x)
14000 (setq x (copy-sequence x))
14001 (org-add-prop-inherited x))
14002 (cdar tags-alist))))
14003 (when (and tags org-use-tag-inheritance
14004 (or (not (eq t org-use-tag-inheritance))
14005 org-tags-exclude-from-inheritance))
14006 ;; selective inheritance, remove uninherited ones
14007 (setcdr (car tags-alist)
14008 (org-remove-uninherited-tags (cdar tags-alist))))
14009 (when (and
14011 ;; eval matcher only when the todo condition is OK
14012 (and (or (not todo-only) (member todo org-not-done-keywords))
14013 (let ((case-fold-search t) (org-trust-scanner-tags t))
14014 (eval matcher)))
14016 ;; Call the skipper, but return t if it does not skip,
14017 ;; so that the `and' form continues evaluating
14018 (progn
14019 (unless (eq action 'sparse-tree) (org-agenda-skip))
14022 ;; Check if timestamps are deselecting this entry
14023 (or (not todo-only)
14024 (and (member todo org-not-done-keywords)
14025 (or (not org-agenda-tags-todo-honor-ignore-options)
14026 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14028 ;; select this headline
14029 (cond
14030 ((eq action 'sparse-tree)
14031 (and org-highlight-sparse-tree-matches
14032 (org-get-heading) (match-end 0)
14033 (org-highlight-new-match
14034 (match-beginning 1) (match-end 1)))
14035 (org-show-context 'tags-tree))
14036 ((eq action 'agenda)
14037 (setq txt (org-agenda-format-item
14039 (concat
14040 (if (eq org-tags-match-list-sublevels 'indented)
14041 (make-string (1- level) ?.) "")
14042 (org-get-heading))
14043 level category
14044 tags-list)
14045 priority (org-get-priority txt))
14046 (goto-char lspos)
14047 (setq marker (org-agenda-new-marker))
14048 (org-add-props txt props
14049 'org-marker marker 'org-hd-marker marker 'org-category category
14050 'todo-state todo
14051 'priority priority 'type "tagsmatch")
14052 (push txt rtn))
14053 ((functionp action)
14054 (setq org-map-continue-from nil)
14055 (save-excursion
14056 (setq rtn1 (funcall action))
14057 (push rtn1 rtn)))
14058 (t (user-error "Invalid action")))
14060 ;; if we are to skip sublevels, jump to end of subtree
14061 (unless org-tags-match-list-sublevels
14062 (org-end-of-subtree t)
14063 (backward-char 1))))
14064 ;; Get the correct position from where to continue
14065 (if org-map-continue-from
14066 (goto-char org-map-continue-from)
14067 (and (= (point) lspos) (end-of-line 1)))))
14068 (when (and (eq action 'sparse-tree)
14069 (not org-sparse-tree-open-archived-trees))
14070 (org-hide-archived-subtrees (point-min) (point-max)))
14071 (nreverse rtn)))
14073 (defun org-remove-uninherited-tags (tags)
14074 "Remove all tags that are not inherited from the list TAGS."
14075 (cond
14076 ((eq org-use-tag-inheritance t)
14077 (if org-tags-exclude-from-inheritance
14078 (org-delete-all org-tags-exclude-from-inheritance tags)
14079 tags))
14080 ((not org-use-tag-inheritance) nil)
14081 ((stringp org-use-tag-inheritance)
14082 (delq nil (mapcar
14083 (lambda (x)
14084 (if (and (string-match org-use-tag-inheritance x)
14085 (not (member x org-tags-exclude-from-inheritance)))
14086 x nil))
14087 tags)))
14088 ((listp org-use-tag-inheritance)
14089 (delq nil (mapcar
14090 (lambda (x)
14091 (if (member x org-use-tag-inheritance) x nil))
14092 tags)))))
14094 (defun org-match-sparse-tree (&optional todo-only match)
14095 "Create a sparse tree according to tags string MATCH.
14096 MATCH can contain positive and negative selection of tags, like
14097 \"+WORK+URGENT-WITHBOSS\".
14098 If optional argument TODO-ONLY is non-nil, only select lines that are
14099 also TODO lines."
14100 (interactive "P")
14101 (org-agenda-prepare-buffers (list (current-buffer)))
14102 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14104 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14106 (defvar org-cached-props nil)
14107 (defun org-cached-entry-get (pom property)
14108 (if (or (eq t org-use-property-inheritance)
14109 (and (stringp org-use-property-inheritance)
14110 (string-match org-use-property-inheritance property))
14111 (and (listp org-use-property-inheritance)
14112 (member property org-use-property-inheritance)))
14113 ;; Caching is not possible, check it directly
14114 (org-entry-get pom property 'inherit)
14115 ;; Get all properties, so that we can do complicated checks easily
14116 (cdr (assoc property (or org-cached-props
14117 (setq org-cached-props
14118 (org-entry-properties pom)))))))
14120 (defun org-global-tags-completion-table (&optional files)
14121 "Return the list of all tags in all agenda buffer/files.
14122 Optional FILES argument is a list of files which can be used
14123 instead of the agenda files."
14124 (save-excursion
14125 (org-uniquify
14126 (delq nil
14127 (apply 'append
14128 (mapcar
14129 (lambda (file)
14130 (set-buffer (find-file-noselect file))
14131 (append (org-get-buffer-tags)
14132 (mapcar (lambda (x) (if (stringp (car-safe x))
14133 (list (car-safe x)) nil))
14134 org-tag-alist)))
14135 (if (and files (car files))
14136 files
14137 (org-agenda-files))))))))
14139 (defun org-make-tags-matcher (match)
14140 "Create the TAGS/TODO matcher form for the selection string MATCH.
14142 The variable `todo-only' is scoped dynamically into this function.
14143 It will be set to t if the matcher restricts matching to TODO entries,
14144 otherwise will not be touched.
14146 Returns a cons of the selection string MATCH and the constructed
14147 lisp form implementing the matcher. The matcher is to be evaluated
14148 at an Org entry, with point on the headline, and returns t if the
14149 entry matches the selection string MATCH. The returned lisp form
14150 references two variables with information about the entry, which
14151 must be bound around the form's evaluation: todo, the TODO keyword
14152 at the entry (or nil of none); and tags-list, the list of all tags
14153 at the entry including inherited ones. Additionally, the category
14154 of the entry (if any) must be specified as the text property
14155 'org-category on the headline.
14157 See also `org-scan-tags'.
14159 (declare (special todo-only))
14160 (unless (boundp 'todo-only)
14161 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14162 (unless match
14163 ;; Get a new match request, with completion against the global
14164 ;; tags table and the local tags in current buffer
14165 (let ((org-last-tags-completion-table
14166 (org-uniquify
14167 (delq nil (append (org-get-buffer-tags)
14168 (org-global-tags-completion-table))))))
14169 (setq match (org-completing-read-no-i
14170 "Match: " 'org-tags-completion-function nil nil nil
14171 'org-tags-history))))
14173 ;; Parse the string and create a lisp form
14174 (let ((match0 match)
14175 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14176 minus tag mm
14177 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14178 orterms term orlist re-p str-p level-p level-op time-p
14179 prop-p pn pv po gv rest (start 0) (ss 0))
14180 ;; Expand group tags
14181 (setq match (org-tags-expand match))
14183 ;; Check if there is a TODO part of this match, which would be the
14184 ;; part after a "/". TO make sure that this slash is not part of
14185 ;; a property value to be matched against, we also check that there
14186 ;; is no " after that slash.
14187 ;; First, find the last slash
14188 (while (string-match "/+" match ss)
14189 (setq start (match-beginning 0) ss (match-end 0)))
14190 (if (and (string-match "/+" match start)
14191 (not (save-match-data (string-match "\"" match start))))
14192 ;; match contains also a todo-matching request
14193 (progn
14194 (setq tagsmatch (substring match 0 (match-beginning 0))
14195 todomatch (substring match (match-end 0)))
14196 (if (string-match "^!" todomatch)
14197 (setq todo-only t todomatch (substring todomatch 1)))
14198 (if (string-match "^\\s-*$" todomatch)
14199 (setq todomatch nil)))
14200 ;; only matching tags
14201 (setq tagsmatch match todomatch nil))
14203 ;; Make the tags matcher
14204 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14205 (setq tagsmatcher t)
14206 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14207 (while (setq term (pop orterms))
14208 (while (and (equal (substring term -1) "\\") orterms)
14209 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14210 (while (string-match re term)
14211 (setq rest (substring term (match-end 0))
14212 minus (and (match-end 1)
14213 (equal (match-string 1 term) "-"))
14214 tag (save-match-data (replace-regexp-in-string
14215 "\\\\-" "-"
14216 (match-string 2 term)))
14217 re-p (equal (string-to-char tag) ?{)
14218 level-p (match-end 4)
14219 prop-p (match-end 5)
14220 mm (cond
14221 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14222 (level-p
14223 (setq level-op (org-op-to-function (match-string 3 term)))
14224 `(,level-op level ,(string-to-number
14225 (match-string 4 term))))
14226 (prop-p
14227 (setq pn (match-string 5 term)
14228 po (match-string 6 term)
14229 pv (match-string 7 term)
14230 re-p (equal (string-to-char pv) ?{)
14231 str-p (equal (string-to-char pv) ?\")
14232 time-p (save-match-data
14233 (string-match "^\"[[<].*[]>]\"$" pv))
14234 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14235 (if time-p (setq pv (org-matcher-time pv)))
14236 (setq po (org-op-to-function po (if time-p 'time str-p)))
14237 (cond
14238 ((equal pn "CATEGORY")
14239 (setq gv '(get-text-property (point) 'org-category)))
14240 ((equal pn "TODO")
14241 (setq gv 'todo))
14243 (setq gv `(org-cached-entry-get nil ,pn))))
14244 (if re-p
14245 (if (eq po 'org<>)
14246 `(not (string-match ,pv (or ,gv "")))
14247 `(string-match ,pv (or ,gv "")))
14248 (if str-p
14249 `(,po (or ,gv "") ,pv)
14250 `(,po (string-to-number (or ,gv ""))
14251 ,(string-to-number pv) ))))
14252 (t `(member ,tag tags-list)))
14253 mm (if minus (list 'not mm) mm)
14254 term rest)
14255 (push mm tagsmatcher))
14256 (push (if (> (length tagsmatcher) 1)
14257 (cons 'and tagsmatcher)
14258 (car tagsmatcher))
14259 orlist)
14260 (setq tagsmatcher nil))
14261 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14262 (setq tagsmatcher
14263 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14264 ;; Make the todo matcher
14265 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14266 (setq todomatcher t)
14267 (setq orterms (org-split-string todomatch "|") orlist nil)
14268 (while (setq term (pop orterms))
14269 (while (string-match re term)
14270 (setq minus (and (match-end 1)
14271 (equal (match-string 1 term) "-"))
14272 kwd (match-string 2 term)
14273 re-p (equal (string-to-char kwd) ?{)
14274 term (substring term (match-end 0))
14275 mm (if re-p
14276 `(string-match ,(substring kwd 1 -1) todo)
14277 (list 'equal 'todo kwd))
14278 mm (if minus (list 'not mm) mm))
14279 (push mm todomatcher))
14280 (push (if (> (length todomatcher) 1)
14281 (cons 'and todomatcher)
14282 (car todomatcher))
14283 orlist)
14284 (setq todomatcher nil))
14285 (setq todomatcher (if (> (length orlist) 1)
14286 (cons 'or orlist) (car orlist))))
14288 ;; Return the string and lisp forms of the matcher
14289 (setq matcher (if todomatcher
14290 (list 'and tagsmatcher todomatcher)
14291 tagsmatcher))
14292 (when todo-only
14293 (setq matcher (list 'and '(member todo org-not-done-keywords)
14294 matcher)))
14295 (cons match0 matcher)))
14297 (defun org-tags-expand (match &optional single-as-list downcased)
14298 "Expand group tags in MATCH.
14300 This replaces every group tag in MATCH with a regexp tag search.
14301 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14302 will be replaced like this:
14304 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14305 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14306 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14308 Replacing by a regexp preserves the structure of the match.
14309 E.g., this expansion
14311 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14313 will match anything tagged with \"Lab\" and \"Home\", or tagged
14314 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14316 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14317 assumed to be a single group tag, and the function will return
14318 the list of tags in this group.
14320 When DOWNCASE is non-nil, expand downcased TAGS."
14321 (if org-group-tags
14322 (let* ((case-fold-search t)
14323 (stable org-mode-syntax-table)
14324 (tal (or org-tag-groups-alist-for-agenda
14325 org-tag-groups-alist))
14326 (tal (if downcased
14327 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14328 (tml (mapcar 'car tal))
14329 (rtnmatch match) rpl)
14330 ;; @ and _ are allowed as word-components in tags
14331 (modify-syntax-entry ?@ "w" stable)
14332 (modify-syntax-entry ?_ "w" stable)
14333 (while (and tml
14334 (with-syntax-table stable
14335 (string-match
14336 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14337 (regexp-opt tml) "\\>\\)") rtnmatch)))
14338 (let* ((dir (match-string 1 rtnmatch))
14339 (tag (match-string 2 rtnmatch))
14340 (tag (if downcased (downcase tag) tag)))
14341 (setq tml (delete tag tml))
14342 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14343 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14344 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14345 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14346 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14347 (if single-as-list
14348 (or (reverse rpl) (list rtnmatch))
14349 rtnmatch))
14350 (if single-as-list (list (if downcased (downcase match) match))
14351 match)))
14353 (defun org-op-to-function (op &optional stringp)
14354 "Turn an operator into the appropriate function."
14355 (setq op
14356 (cond
14357 ((equal op "<" ) '(< string< org-time<))
14358 ((equal op ">" ) '(> org-string> org-time>))
14359 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14360 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14361 ((member op '("=" "==")) '(= string= org-time=))
14362 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14363 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14365 (defun org<> (a b) (not (= a b)))
14366 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14367 (defun org-string>= (a b) (not (string< a b)))
14368 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14369 (defun org-string<> (a b) (not (string= a b)))
14370 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14371 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14372 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14373 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14374 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14375 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14376 (defun org-2ft (s)
14377 "Convert S to a floating point time.
14378 If S is already a number, just return it. If it is a string, parse
14379 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14380 (cond
14381 ((numberp s) s)
14382 ((stringp s)
14383 (condition-case nil
14384 (float-time (apply 'encode-time (org-parse-time-string s)))
14385 (error 0.)))
14386 (t 0.)))
14388 (defun org-time-today ()
14389 "Time in seconds today at 0:00.
14390 Returns the float number of seconds since the beginning of the
14391 epoch to the beginning of today (00:00)."
14392 (float-time (apply 'encode-time
14393 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14395 (defun org-matcher-time (s)
14396 "Interpret a time comparison value."
14397 (save-match-data
14398 (cond
14399 ((string= s "<now>") (float-time))
14400 ((string= s "<today>") (org-time-today))
14401 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14402 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14403 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14404 (+ (org-time-today)
14405 (* (string-to-number (match-string 1 s))
14406 (cdr (assoc (match-string 2 s)
14407 '(("d" . 86400.0) ("w" . 604800.0)
14408 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14409 (t (org-2ft s)))))
14411 (defun org-match-any-p (re list)
14412 "Does re match any element of list?"
14413 (setq list (mapcar (lambda (x) (string-match re x)) list))
14414 (delq nil list))
14416 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14417 (defvar org-tags-overlay (make-overlay 1 1))
14418 (org-detach-overlay org-tags-overlay)
14420 (defun org-get-local-tags-at (&optional pos)
14421 "Get a list of tags defined in the current headline."
14422 (org-get-tags-at pos 'local))
14424 (defun org-get-local-tags ()
14425 "Get a list of tags defined in the current headline."
14426 (org-get-tags-at nil 'local))
14428 (defun org-get-tags-at (&optional pos local)
14429 "Get a list of all headline tags applicable at POS.
14430 POS defaults to point. If tags are inherited, the list contains
14431 the targets in the same sequence as the headlines appear, i.e.
14432 the tags of the current headline come last.
14433 When LOCAL is non-nil, only return tags from the current headline,
14434 ignore inherited ones."
14435 (interactive)
14436 (if (and org-trust-scanner-tags
14437 (or (not pos) (equal pos (point)))
14438 (not local))
14439 org-scanner-tags
14440 (let (tags ltags lastpos parent)
14441 (save-excursion
14442 (save-restriction
14443 (widen)
14444 (goto-char (or pos (point)))
14445 (save-match-data
14446 (catch 'done
14447 (condition-case nil
14448 (progn
14449 (org-back-to-heading t)
14450 (while (not (equal lastpos (point)))
14451 (setq lastpos (point))
14452 (when (looking-at
14453 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14454 (setq ltags (org-split-string
14455 (org-match-string-no-properties 1) ":"))
14456 (when parent
14457 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14458 (setq tags (append
14459 (if parent
14460 (org-remove-uninherited-tags ltags)
14461 ltags)
14462 tags)))
14463 (or org-use-tag-inheritance (throw 'done t))
14464 (if local (throw 'done t))
14465 (or (org-up-heading-safe) (error nil))
14466 (setq parent t)))
14467 (error nil)))))
14468 (if local
14469 tags
14470 (reverse (delete-dups
14471 (reverse (append
14472 (org-remove-uninherited-tags
14473 org-file-tags) tags)))))))))
14475 (defun org-add-prop-inherited (s)
14476 (add-text-properties 0 (length s) '(inherited t) s)
14479 (defun org-toggle-tag (tag &optional onoff)
14480 "Toggle the tag TAG for the current line.
14481 If ONOFF is `on' or `off', don't toggle but set to this state."
14482 (let (res current)
14483 (save-excursion
14484 (org-back-to-heading t)
14485 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14486 (point-at-eol) t)
14487 (progn
14488 (setq current (match-string 1))
14489 (replace-match ""))
14490 (setq current ""))
14491 (setq current (nreverse (org-split-string current ":")))
14492 (cond
14493 ((eq onoff 'on)
14494 (setq res t)
14495 (or (member tag current) (push tag current)))
14496 ((eq onoff 'off)
14497 (or (not (member tag current)) (setq current (delete tag current))))
14498 (t (if (member tag current)
14499 (setq current (delete tag current))
14500 (setq res t)
14501 (push tag current))))
14502 (end-of-line 1)
14503 (if current
14504 (progn
14505 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14506 (org-set-tags nil t))
14507 (delete-horizontal-space))
14508 (run-hooks 'org-after-tags-change-hook))
14509 res))
14511 (defun org-align-tags-here (to-col)
14512 ;; Assumes that this is a headline
14513 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14514 (beginning-of-line 1)
14515 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14516 (< pos (match-beginning 2)))
14517 (progn
14518 (setq tags-l (- (match-end 2) (match-beginning 2)))
14519 (goto-char (match-beginning 1))
14520 (insert " ")
14521 (delete-region (point) (1+ (match-beginning 2)))
14522 (setq ncol (max (current-column)
14523 (1+ col)
14524 (if (> to-col 0)
14525 to-col
14526 (- (abs to-col) tags-l))))
14527 (setq p (point))
14528 (insert (make-string (- ncol (current-column)) ?\ ))
14529 (setq ncol (current-column))
14530 (when indent-tabs-mode (tabify p (point-at-eol)))
14531 (org-move-to-column (min ncol col) t nil t))
14532 (goto-char pos))))
14534 (defun org-set-tags-command (&optional arg just-align)
14535 "Call the set-tags command for the current entry."
14536 (interactive "P")
14537 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14538 (org-set-tags arg just-align)
14539 (save-excursion
14540 (unless (and (org-region-active-p)
14541 org-loop-over-headlines-in-active-region)
14542 (org-back-to-heading t))
14543 (org-set-tags arg just-align))))
14545 (defun org-set-tags-to (data)
14546 "Set the tags of the current entry to DATA, replacing the current tags.
14547 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14548 If DATA is nil or the empty string, any tags will be removed."
14549 (interactive "sTags: ")
14550 (setq data
14551 (cond
14552 ((eq data nil) "")
14553 ((equal data "") "")
14554 ((stringp data)
14555 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14556 ":"))
14557 ((listp data)
14558 (concat ":" (mapconcat 'identity data ":") ":"))))
14559 (when data
14560 (save-excursion
14561 (org-back-to-heading t)
14562 (when (looking-at org-complex-heading-regexp)
14563 (if (match-end 5)
14564 (progn
14565 (goto-char (match-beginning 5))
14566 (insert data)
14567 (delete-region (point) (point-at-eol))
14568 (org-set-tags nil 'align))
14569 (goto-char (point-at-eol))
14570 (insert " " data)
14571 (org-set-tags nil 'align)))
14572 (beginning-of-line 1)
14573 (if (looking-at ".*?\\([ \t]+\\)$")
14574 (delete-region (match-beginning 1) (match-end 1))))))
14576 (defun org-align-all-tags ()
14577 "Align the tags i all headings."
14578 (interactive)
14579 (save-excursion
14580 (or (ignore-errors (org-back-to-heading t))
14581 (outline-next-heading))
14582 (if (org-at-heading-p)
14583 (org-set-tags t)
14584 (message "No headings"))))
14586 (defvar org-indent-indentation-per-level)
14587 (defun org-set-tags (&optional arg just-align)
14588 "Set the tags for the current headline.
14589 With prefix ARG, realign all tags in headings in the current buffer.
14590 When JUST-ALIGN is non-nil, only align tags.
14591 When JUST-ALIGN is 'ignore-column, align tags without trying to set
14592 the column by ignoring invisible text."
14593 (interactive "P")
14594 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14595 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14596 'region-start-level 'region))
14597 org-loop-over-headlines-in-active-region)
14598 (org-map-entries
14599 ;; We don't use ARG and JUST-ALIGN here because these args
14600 ;; are not useful when looping over headlines.
14601 `(org-set-tags)
14602 org-loop-over-headlines-in-active-region
14603 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14604 (let* ((re org-outline-regexp-bol)
14605 (current (unless arg (org-get-tags-string)))
14606 (col (current-column))
14607 (org-setting-tags t)
14608 table current-tags inherited-tags ; computed below when needed
14609 tags p0 c0 c1 rpl di tc level)
14610 (if arg
14611 (save-excursion
14612 (goto-char (point-min))
14613 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14614 (while (re-search-forward re nil t)
14615 (org-set-tags nil t)
14616 (end-of-line 1)))
14617 (message "All tags realigned to column %d" org-tags-column))
14618 (if just-align
14619 (setq tags current)
14620 ;; Get a new set of tags from the user
14621 (save-excursion
14622 (setq table (append org-tag-persistent-alist
14623 (or org-tag-alist (org-get-buffer-tags))
14624 (and
14625 org-complete-tags-always-offer-all-agenda-tags
14626 (org-global-tags-completion-table
14627 (org-agenda-files))))
14628 org-last-tags-completion-table table
14629 current-tags (org-split-string current ":")
14630 inherited-tags (nreverse
14631 (nthcdr (length current-tags)
14632 (nreverse (org-get-tags-at))))
14633 tags
14634 (if (or (eq t org-use-fast-tag-selection)
14635 (and org-use-fast-tag-selection
14636 (delq nil (mapcar 'cdr table))))
14637 (org-fast-tag-selection
14638 current-tags inherited-tags table
14639 (if org-fast-tag-selection-include-todo
14640 org-todo-key-alist))
14641 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14642 (org-trim
14643 (org-icompleting-read "Tags: "
14644 'org-tags-completion-function
14645 nil nil current 'org-tags-history))))))
14646 (while (string-match "[-+&]+" tags)
14647 ;; No boolean logic, just a list
14648 (setq tags (replace-match ":" t t tags))))
14650 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14652 (if org-tags-sort-function
14653 (setq tags (mapconcat 'identity
14654 (sort (org-split-string
14655 tags (org-re "[^[:alnum:]_@#%]+"))
14656 org-tags-sort-function) ":")))
14658 (if (string-match "\\`[\t ]*\\'" tags)
14659 (setq tags "")
14660 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14661 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14663 ;; Insert new tags at the correct column
14664 (beginning-of-line 1)
14665 (setq level (or (and (looking-at org-outline-regexp)
14666 (- (match-end 0) (point) 1))
14668 (cond
14669 ((and (equal current "") (equal tags "")))
14670 ((re-search-forward
14671 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14672 (point-at-eol) t)
14673 (if (equal tags "")
14674 (setq rpl "")
14675 (goto-char (match-beginning 0))
14676 (setq c0 (current-column)
14677 ;; compute offset for the case of org-indent-mode active
14678 di (if (org-bound-and-true-p org-indent-mode)
14679 (* (1- org-indent-indentation-per-level) (1- level))
14681 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14682 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14683 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14684 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14685 (replace-match rpl t t)
14686 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14687 tags)
14688 (t (error "Tags alignment failed")))
14689 (org-move-to-column col nil nil (not (eq just-align 'ignore-column)))
14690 (unless just-align
14691 (run-hooks 'org-after-tags-change-hook))))))
14693 (defun org-change-tag-in-region (beg end tag off)
14694 "Add or remove TAG for each entry in the region.
14695 This works in the agenda, and also in an org-mode buffer."
14696 (interactive
14697 (list (region-beginning) (region-end)
14698 (let ((org-last-tags-completion-table
14699 (if (derived-mode-p 'org-mode)
14700 (org-uniquify
14701 (delq nil (append (org-get-buffer-tags)
14702 (org-global-tags-completion-table))))
14703 (org-global-tags-completion-table))))
14704 (org-icompleting-read
14705 "Tag: " 'org-tags-completion-function nil nil nil
14706 'org-tags-history))
14707 (progn
14708 (message "[s]et or [r]emove? ")
14709 (equal (read-char-exclusive) ?r))))
14710 (if (fboundp 'deactivate-mark) (deactivate-mark))
14711 (let ((agendap (equal major-mode 'org-agenda-mode))
14712 l1 l2 m buf pos newhead (cnt 0))
14713 (goto-char end)
14714 (setq l2 (1- (org-current-line)))
14715 (goto-char beg)
14716 (setq l1 (org-current-line))
14717 (loop for l from l1 to l2 do
14718 (org-goto-line l)
14719 (setq m (get-text-property (point) 'org-hd-marker))
14720 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14721 (and agendap m))
14722 (setq buf (if agendap (marker-buffer m) (current-buffer))
14723 pos (if agendap m (point)))
14724 (with-current-buffer buf
14725 (save-excursion
14726 (save-restriction
14727 (goto-char pos)
14728 (setq cnt (1+ cnt))
14729 (org-toggle-tag tag (if off 'off 'on))
14730 (setq newhead (org-get-heading)))))
14731 (and agendap (org-agenda-change-all-lines newhead m))))
14732 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14734 (defun org-tags-completion-function (string predicate &optional flag)
14735 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14736 (confirm (lambda (x) (stringp (car x)))))
14737 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14738 (setq s1 (match-string 1 string)
14739 s2 (match-string 2 string))
14740 (setq s1 "" s2 string))
14741 (cond
14742 ((eq flag nil)
14743 ;; try completion
14744 (setq rtn (try-completion s2 ctable confirm))
14745 (if (stringp rtn)
14746 (setq rtn
14747 (concat s1 s2 (substring rtn (length s2))
14748 (if (and org-add-colon-after-tag-completion
14749 (assoc rtn ctable))
14750 ":" ""))))
14751 rtn)
14752 ((eq flag t)
14753 ;; all-completions
14754 (all-completions s2 ctable confirm))
14755 ((eq flag 'lambda)
14756 ;; exact match?
14757 (assoc s2 ctable)))))
14759 (defun org-fast-tag-insert (kwd tags face &optional end)
14760 "Insert KDW, and the TAGS, the latter with face FACE.
14761 Also insert END."
14762 (insert (format "%-12s" (concat kwd ":"))
14763 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14764 (or end "")))
14766 (defun org-fast-tag-show-exit (flag)
14767 (save-excursion
14768 (org-goto-line 3)
14769 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14770 (replace-match ""))
14771 (when flag
14772 (end-of-line 1)
14773 (org-move-to-column (- (window-width) 19) t)
14774 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14776 (defun org-set-current-tags-overlay (current prefix)
14777 "Add an overlay to CURRENT tag with PREFIX."
14778 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14779 (if (featurep 'xemacs)
14780 (org-overlay-display org-tags-overlay (concat prefix s)
14781 'secondary-selection)
14782 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14783 (org-overlay-display org-tags-overlay (concat prefix s)))))
14785 (defvar org-last-tag-selection-key nil)
14786 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14787 "Fast tag selection with single keys.
14788 CURRENT is the current list of tags in the headline, INHERITED is the
14789 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14790 possibly with grouping information. TODO-TABLE is a similar table with
14791 TODO keywords, should these have keys assigned to them.
14792 If the keys are nil, a-z are automatically assigned.
14793 Returns the new tags string, or nil to not change the current settings."
14794 (let* ((fulltable (append table todo-table))
14795 (maxlen (apply 'max (mapcar
14796 (lambda (x)
14797 (if (stringp (car x)) (string-width (car x)) 0))
14798 fulltable)))
14799 (buf (current-buffer))
14800 (expert (eq org-fast-tag-selection-single-key 'expert))
14801 (buffer-tags nil)
14802 (fwidth (+ maxlen 3 1 3))
14803 (ncol (/ (- (window-width) 4) fwidth))
14804 (i-face 'org-done)
14805 (c-face 'org-todo)
14806 tg cnt e c char c1 c2 ntable tbl rtn
14807 ov-start ov-end ov-prefix
14808 (exit-after-next org-fast-tag-selection-single-key)
14809 (done-keywords org-done-keywords)
14810 groups ingroup)
14811 (save-excursion
14812 (beginning-of-line 1)
14813 (if (looking-at
14814 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14815 (setq ov-start (match-beginning 1)
14816 ov-end (match-end 1)
14817 ov-prefix "")
14818 (setq ov-start (1- (point-at-eol))
14819 ov-end (1+ ov-start))
14820 (skip-chars-forward "^\n\r")
14821 (setq ov-prefix
14822 (concat
14823 (buffer-substring (1- (point)) (point))
14824 (if (> (current-column) org-tags-column)
14826 (make-string (- org-tags-column (current-column)) ?\ ))))))
14827 (move-overlay org-tags-overlay ov-start ov-end)
14828 (save-window-excursion
14829 (if expert
14830 (set-buffer (get-buffer-create " *Org tags*"))
14831 (delete-other-windows)
14832 (split-window-vertically)
14833 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14834 (erase-buffer)
14835 (org-set-local 'org-done-keywords done-keywords)
14836 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14837 (org-fast-tag-insert "Current" current c-face "\n\n")
14838 (org-fast-tag-show-exit exit-after-next)
14839 (org-set-current-tags-overlay current ov-prefix)
14840 (setq tbl fulltable char ?a cnt 0)
14841 (while (setq e (pop tbl))
14842 (cond
14843 ((equal (car e) :startgroup)
14844 (push '() groups) (setq ingroup t)
14845 (when (not (= cnt 0))
14846 (setq cnt 0)
14847 (insert "\n"))
14848 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14849 ((equal (car e) :endgroup)
14850 (setq ingroup nil cnt 0)
14851 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14852 ((equal e '(:newline))
14853 (when (not (= cnt 0))
14854 (setq cnt 0)
14855 (insert "\n")
14856 (setq e (car tbl))
14857 (while (equal (car tbl) '(:newline))
14858 (insert "\n")
14859 (setq tbl (cdr tbl)))))
14860 ((equal e '(:grouptags)) nil)
14862 (setq tg (copy-sequence (car e)) c2 nil)
14863 (if (cdr e)
14864 (setq c (cdr e))
14865 ;; automatically assign a character.
14866 (setq c1 (string-to-char
14867 (downcase (substring
14868 tg (if (= (string-to-char tg) ?@) 1 0)))))
14869 (if (or (rassoc c1 ntable) (rassoc c1 table))
14870 (while (or (rassoc char ntable) (rassoc char table))
14871 (setq char (1+ char)))
14872 (setq c2 c1))
14873 (setq c (or c2 char)))
14874 (if ingroup (push tg (car groups)))
14875 (setq tg (org-add-props tg nil 'face
14876 (cond
14877 ((not (assoc tg table))
14878 (org-get-todo-face tg))
14879 ((member tg current) c-face)
14880 ((member tg inherited) i-face))))
14881 (if (equal (caar tbl) :grouptags)
14882 (org-add-props tg nil 'face 'org-tag-group))
14883 (if (and (= cnt 0) (not ingroup)) (insert " "))
14884 (insert "[" c "] " tg (make-string
14885 (- fwidth 4 (length tg)) ?\ ))
14886 (push (cons tg c) ntable)
14887 (when (= (setq cnt (1+ cnt)) ncol)
14888 (insert "\n")
14889 (if ingroup (insert " "))
14890 (setq cnt 0)))))
14891 (setq ntable (nreverse ntable))
14892 (insert "\n")
14893 (goto-char (point-min))
14894 (if (not expert) (org-fit-window-to-buffer))
14895 (setq rtn
14896 (catch 'exit
14897 (while t
14898 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14899 (if (not groups) "no " "")
14900 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14901 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14902 (setq org-last-tag-selection-key c)
14903 (cond
14904 ((= c ?\r) (throw 'exit t))
14905 ((= c ?!)
14906 (setq groups (not groups))
14907 (goto-char (point-min))
14908 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14909 ((= c ?\C-c)
14910 (if (not expert)
14911 (org-fast-tag-show-exit
14912 (setq exit-after-next (not exit-after-next)))
14913 (setq expert nil)
14914 (delete-other-windows)
14915 (set-window-buffer (split-window-vertically) " *Org tags*")
14916 (org-switch-to-buffer-other-window " *Org tags*")
14917 (org-fit-window-to-buffer)))
14918 ((or (= c ?\C-g)
14919 (and (= c ?q) (not (rassoc c ntable))))
14920 (org-detach-overlay org-tags-overlay)
14921 (setq quit-flag t))
14922 ((= c ?\ )
14923 (setq current nil)
14924 (if exit-after-next (setq exit-after-next 'now)))
14925 ((= c ?\t)
14926 (condition-case nil
14927 (setq tg (org-icompleting-read
14928 "Tag: "
14929 (or buffer-tags
14930 (with-current-buffer buf
14931 (org-get-buffer-tags)))))
14932 (quit (setq tg "")))
14933 (when (string-match "\\S-" tg)
14934 (add-to-list 'buffer-tags (list tg))
14935 (if (member tg current)
14936 (setq current (delete tg current))
14937 (push tg current)))
14938 (if exit-after-next (setq exit-after-next 'now)))
14939 ((setq e (rassoc c todo-table) tg (car e))
14940 (with-current-buffer buf
14941 (save-excursion (org-todo tg)))
14942 (if exit-after-next (setq exit-after-next 'now)))
14943 ((setq e (rassoc c ntable) tg (car e))
14944 (if (member tg current)
14945 (setq current (delete tg current))
14946 (loop for g in groups do
14947 (if (member tg g)
14948 (mapc (lambda (x)
14949 (setq current (delete x current)))
14950 g)))
14951 (push tg current))
14952 (if exit-after-next (setq exit-after-next 'now))))
14954 ;; Create a sorted list
14955 (setq current
14956 (sort current
14957 (lambda (a b)
14958 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14959 (if (eq exit-after-next 'now) (throw 'exit t))
14960 (goto-char (point-min))
14961 (beginning-of-line 2)
14962 (delete-region (point) (point-at-eol))
14963 (org-fast-tag-insert "Current" current c-face)
14964 (org-set-current-tags-overlay current ov-prefix)
14965 (while (re-search-forward
14966 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14967 (setq tg (match-string 1))
14968 (add-text-properties
14969 (match-beginning 1) (match-end 1)
14970 (list 'face
14971 (cond
14972 ((member tg current) c-face)
14973 ((member tg inherited) i-face)
14974 (t (get-text-property (match-beginning 1) 'face))))))
14975 (goto-char (point-min)))))
14976 (org-detach-overlay org-tags-overlay)
14977 (if rtn
14978 (mapconcat 'identity current ":")
14979 nil))))
14981 (defun org-get-tags-string ()
14982 "Get the TAGS string in the current headline."
14983 (unless (org-at-heading-p t)
14984 (user-error "Not on a heading"))
14985 (save-excursion
14986 (beginning-of-line 1)
14987 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14988 (org-match-string-no-properties 1)
14989 "")))
14991 (defun org-get-tags ()
14992 "Get the list of tags specified in the current headline."
14993 (org-split-string (org-get-tags-string) ":"))
14995 (defun org-get-buffer-tags ()
14996 "Get a table of all tags used in the buffer, for completion."
14997 (let (tags)
14998 (save-excursion
14999 (goto-char (point-min))
15000 (while (re-search-forward
15001 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
15002 (when (equal (char-after (point-at-bol 0)) ?*)
15003 (mapc (lambda (x) (add-to-list 'tags x))
15004 (org-split-string (org-match-string-no-properties 1) ":")))))
15005 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
15006 (mapcar 'list tags)))
15008 ;;;; The mapping API
15010 (defun org-map-entries (func &optional match scope &rest skip)
15011 "Call FUNC at each headline selected by MATCH in SCOPE.
15013 FUNC is a function or a lisp form. The function will be called without
15014 arguments, with the cursor positioned at the beginning of the headline.
15015 The return values of all calls to the function will be collected and
15016 returned as a list.
15018 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15019 does not need to preserve point. After evaluation, the cursor will be
15020 moved to the end of the line (presumably of the headline of the
15021 processed entry) and search continues from there. Under some
15022 circumstances, this may not produce the wanted results. For example,
15023 if you have removed (e.g. archived) the current (sub)tree it could
15024 mean that the next entry will be skipped entirely. In such cases, you
15025 can specify the position from where search should continue by making
15026 FUNC set the variable `org-map-continue-from' to the desired buffer
15027 position.
15029 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15030 Only headlines that are matched by this query will be considered during
15031 the iteration. When MATCH is nil or t, all headlines will be
15032 visited by the iteration.
15034 SCOPE determines the scope of this command. It can be any of:
15036 nil The current buffer, respecting the restriction if any
15037 tree The subtree started with the entry at point
15038 region The entries within the active region, if any
15039 region-start-level
15040 The entries within the active region, but only those at
15041 the same level than the first one.
15042 file The current buffer, without restriction
15043 file-with-archives
15044 The current buffer, and any archives associated with it
15045 agenda All agenda files
15046 agenda-with-archives
15047 All agenda files with any archive files associated with them
15048 \(file1 file2 ...)
15049 If this is a list, all files in the list will be scanned
15051 The remaining args are treated as settings for the skipping facilities of
15052 the scanner. The following items can be given here:
15054 archive skip trees with the archive tag
15055 comment skip trees with the COMMENT keyword
15056 function or Emacs Lisp form:
15057 will be used as value for `org-agenda-skip-function', so
15058 whenever the function returns a position, FUNC will not be
15059 called for that entry and search will continue from the
15060 position returned
15062 If your function needs to retrieve the tags including inherited tags
15063 at the *current* entry, you can use the value of the variable
15064 `org-scanner-tags' which will be much faster than getting the value
15065 with `org-get-tags-at'. If your function gets properties with
15066 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15067 to t around the call to `org-entry-properties' to get the same speedup.
15068 Note that if your function moves around to retrieve tags and properties at
15069 a *different* entry, you cannot use these techniques."
15070 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15071 (not (org-region-active-p)))
15072 (let* ((org-agenda-archives-mode nil) ; just to make sure
15073 (org-agenda-skip-archived-trees (memq 'archive skip))
15074 (org-agenda-skip-comment-trees (memq 'comment skip))
15075 (org-agenda-skip-function
15076 (car (org-delete-all '(comment archive) skip)))
15077 (org-tags-match-list-sublevels t)
15078 (start-level (eq scope 'region-start-level))
15079 matcher file res
15080 org-todo-keywords-for-agenda
15081 org-done-keywords-for-agenda
15082 org-todo-keyword-alist-for-agenda
15083 org-tag-alist-for-agenda
15084 todo-only)
15086 (cond
15087 ((eq match t) (setq matcher t))
15088 ((eq match nil) (setq matcher t))
15089 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15091 (save-excursion
15092 (save-restriction
15093 (cond ((eq scope 'tree)
15094 (org-back-to-heading t)
15095 (org-narrow-to-subtree)
15096 (setq scope nil))
15097 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15098 (org-region-active-p))
15099 ;; If needed, set start-level to a string like "2"
15100 (when start-level
15101 (save-excursion
15102 (goto-char (region-beginning))
15103 (unless (org-at-heading-p) (outline-next-heading))
15104 (setq start-level (org-current-level))))
15105 (narrow-to-region (region-beginning)
15106 (save-excursion
15107 (goto-char (region-end))
15108 (unless (and (bolp) (org-at-heading-p))
15109 (outline-next-heading))
15110 (point)))
15111 (setq scope nil)))
15113 (if (not scope)
15114 (progn
15115 (org-agenda-prepare-buffers
15116 (list (buffer-file-name (current-buffer))))
15117 (setq res (org-scan-tags func matcher todo-only start-level)))
15118 ;; Get the right scope
15119 (cond
15120 ((and scope (listp scope) (symbolp (car scope)))
15121 (setq scope (eval scope)))
15122 ((eq scope 'agenda)
15123 (setq scope (org-agenda-files t)))
15124 ((eq scope 'agenda-with-archives)
15125 (setq scope (org-agenda-files t))
15126 (setq scope (org-add-archive-files scope)))
15127 ((eq scope 'file)
15128 (setq scope (list (buffer-file-name))))
15129 ((eq scope 'file-with-archives)
15130 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15131 (org-agenda-prepare-buffers scope)
15132 (while (setq file (pop scope))
15133 (with-current-buffer (org-find-base-buffer-visiting file)
15134 (save-excursion
15135 (save-restriction
15136 (widen)
15137 (goto-char (point-min))
15138 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15139 res)))
15141 ;;;; Properties
15143 ;;; Setting and retrieving properties
15145 (defconst org-special-properties
15146 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15147 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15148 "The special properties valid in Org-mode.
15150 These are properties that are not defined in the property drawer,
15151 but in some other way.")
15153 (defconst org-default-properties
15154 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15155 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15156 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15157 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15158 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15159 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15160 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15161 "Some properties that are used by Org-mode for various purposes.
15162 Being in this list makes sure that they are offered for completion.")
15164 (defun org-property-action ()
15165 "Do an action on properties."
15166 (interactive)
15167 (let (c)
15168 (org-at-property-p)
15169 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15170 (setq c (read-char-exclusive))
15171 (cond
15172 ((equal c ?s)
15173 (call-interactively 'org-set-property))
15174 ((equal c ?d)
15175 (call-interactively 'org-delete-property))
15176 ((equal c ?D)
15177 (call-interactively 'org-delete-property-globally))
15178 ((equal c ?c)
15179 (call-interactively 'org-compute-property-at-point))
15180 (t (user-error "No such property action %c" c)))))
15182 (defun org-inc-effort ()
15183 "Increment the value of the effort property in the current entry."
15184 (interactive)
15185 (org-set-effort nil t))
15187 (defvar org-clock-effort) ;; Defined in org-clock.el
15188 (defvar org-clock-current-task) ;; Defined in org-clock.el
15189 (defun org-set-effort (&optional value increment)
15190 "Set the effort property of the current entry.
15191 With numerical prefix arg, use the nth allowed value, 0 stands for the
15192 10th allowed value.
15194 When INCREMENT is non-nil, set the property to the next allowed value."
15195 (interactive "P")
15196 (if (equal value 0) (setq value 10))
15197 (let* ((completion-ignore-case t)
15198 (prop org-effort-property)
15199 (cur (org-entry-get nil prop))
15200 (allowed (org-property-get-allowed-values nil prop 'table))
15201 (existing (mapcar 'list (org-property-values prop)))
15202 (heading (nth 4 (org-heading-components)))
15204 (val (cond
15205 ((stringp value) value)
15206 ((and allowed (integerp value))
15207 (or (car (nth (1- value) allowed))
15208 (car (org-last allowed))))
15209 ((and allowed increment)
15210 (or (caadr (member (list cur) allowed))
15211 (user-error "Allowed effort values are not set")))
15212 (allowed
15213 (message "Select 1-9,0, [RET%s]: %s"
15214 (if cur (concat "=" cur) "")
15215 (mapconcat 'car allowed " "))
15216 (setq rpl (read-char-exclusive))
15217 (if (equal rpl ?\r)
15219 (setq rpl (- rpl ?0))
15220 (if (equal rpl 0) (setq rpl 10))
15221 (if (and (> rpl 0) (<= rpl (length allowed)))
15222 (car (nth (1- rpl) allowed))
15223 (org-completing-read "Effort: " allowed nil))))
15225 (let (org-completion-use-ido org-completion-use-iswitchb)
15226 (org-completing-read
15227 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15228 (concat "[" cur "]") "")
15229 ": ")
15230 existing nil nil "" nil cur))))))
15231 (unless (equal (org-entry-get nil prop) val)
15232 (org-entry-put nil prop val))
15233 (save-excursion
15234 (org-back-to-heading t)
15235 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15236 (when (string= heading org-clock-current-task)
15237 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15238 (org-clock-update-mode-line))
15239 (message "%s is now %s" prop val)))
15241 (defun org-at-property-p ()
15242 "Is cursor inside a property drawer?"
15243 (save-excursion
15244 (when (equal 'node-property (car (org-element-at-point)))
15245 (beginning-of-line 1)
15246 (looking-at org-property-re))))
15248 (defun org-get-property-block (&optional beg end force)
15249 "Return the (beg . end) range of the body of the property drawer.
15250 BEG and END are the beginning and end of the current subtree, or of
15251 the part before the first headline. If they are not given, they will
15252 be found. If the drawer does not exist and FORCE is non-nil, create
15253 the drawer."
15254 (catch 'exit
15255 (save-excursion
15256 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15257 (progn (org-back-to-heading t) (point))))
15258 (end (or end (and (not (outline-next-heading)) (point-max))
15259 (point))))
15260 (goto-char beg)
15261 (if (re-search-forward org-property-start-re end t)
15262 (setq beg (1+ (match-end 0)))
15263 (if force
15264 (save-excursion
15265 (org-insert-property-drawer)
15266 (setq end (progn (outline-next-heading) (point))))
15267 (throw 'exit nil))
15268 (goto-char beg)
15269 (if (re-search-forward org-property-start-re end t)
15270 (setq beg (1+ (match-end 0)))))
15271 (if (re-search-forward org-property-end-re end t)
15272 (setq end (match-beginning 0))
15273 (or force (throw 'exit nil))
15274 (goto-char beg)
15275 (setq end beg)
15276 (org-indent-line)
15277 (insert ":END:\n"))
15278 (cons beg end)))))
15280 (defun org-entry-properties (&optional pom which specific)
15281 "Get all properties of the entry at point-or-marker POM.
15282 This includes the TODO keyword, the tags, time strings for deadline,
15283 scheduled, and clocking, and any additional properties defined in the
15284 entry. The return value is an alist, keys may occur multiple times
15285 if the property key was used several times.
15286 POM may also be nil, in which case the current entry is used.
15287 If WHICH is nil or `all', get all properties. If WHICH is
15288 `special' or `standard', only get that subclass. If WHICH
15289 is a string only get exactly this property. SPECIFIC can be a string, the
15290 specific property we are interested in. Specifying it can speed
15291 things up because then unnecessary parsing is avoided."
15292 (setq which (or which 'all))
15293 (org-with-wide-buffer
15294 (org-with-point-at pom
15295 (let ((clockstr (substring org-clock-string 0 -1))
15296 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15297 (case-fold-search nil)
15298 beg end range props sum-props key key1 value string clocksum clocksumt)
15299 (when (and (derived-mode-p 'org-mode)
15300 (ignore-errors (org-back-to-heading t)))
15301 (setq beg (point))
15302 (setq sum-props (get-text-property (point) 'org-summaries))
15303 (setq clocksum (get-text-property (point) :org-clock-minutes)
15304 clocksumt (get-text-property (point) :org-clock-minutes-today))
15305 (outline-next-heading)
15306 (setq end (point))
15307 (when (memq which '(all special))
15308 ;; Get the special properties, like TODO and tags
15309 (goto-char beg)
15310 (when (and (or (not specific) (string= specific "TODO"))
15311 (looking-at org-todo-line-regexp) (match-end 2))
15312 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15313 (when (and (or (not specific) (string= specific "PRIORITY"))
15314 (looking-at org-priority-regexp))
15315 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15316 (when (or (not specific) (string= specific "FILE"))
15317 (push (cons "FILE" buffer-file-name) props))
15318 (when (and (or (not specific) (string= specific "TAGS"))
15319 (setq value (org-get-tags-string))
15320 (string-match "\\S-" value))
15321 (push (cons "TAGS" value) props))
15322 (when (and (or (not specific) (string= specific "ALLTAGS"))
15323 (setq value (org-get-tags-at)))
15324 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15325 ":"))
15326 props))
15327 (when (or (not specific) (string= specific "BLOCKED"))
15328 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15329 (when (or (not specific)
15330 (member specific
15331 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15332 "TIMESTAMP" "TIMESTAMP_IA")))
15333 (catch 'match
15334 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15335 (setq key (if (match-end 1)
15336 (substring (org-match-string-no-properties 1)
15337 0 -1))
15338 string (if (equal key clockstr)
15339 (org-trim
15340 (buffer-substring-no-properties
15341 (match-beginning 3) (goto-char
15342 (point-at-eol))))
15343 (substring (org-match-string-no-properties 3)
15344 1 -1)))
15345 ;; Get the correct property name from the key. This is
15346 ;; necessary if the user has configured time keywords.
15347 (setq key1 (concat key ":"))
15348 (cond
15349 ((not key)
15350 (setq key
15351 (if (= (char-after (match-beginning 3)) ?\[)
15352 "TIMESTAMP_IA" "TIMESTAMP")))
15353 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15354 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15355 ((equal key1 org-closed-string) (setq key "CLOSED"))
15356 ((equal key1 org-clock-string) (setq key "CLOCK")))
15357 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15358 (progn
15359 (push (cons key string) props)
15360 ;; no need to search further if match is found
15361 (throw 'match t))
15362 (when (or (equal key "CLOCK") (not (assoc key props)))
15363 (push (cons key string) props)))))))
15365 (when (memq which '(all standard))
15366 ;; Get the standard properties, like :PROP: ...
15367 (setq range (org-get-property-block beg end))
15368 (when range
15369 (goto-char (car range))
15370 (while (re-search-forward org-property-re
15371 (cdr range) t)
15372 (setq key (org-match-string-no-properties 2)
15373 value (org-trim (or (org-match-string-no-properties 3) "")))
15374 (unless (member key excluded)
15375 (push (cons key (or value "")) props)))))
15376 (if clocksum
15377 (push (cons "CLOCKSUM"
15378 (org-columns-number-to-string (/ (float clocksum) 60.)
15379 'add_times))
15380 props))
15381 (if clocksumt
15382 (push (cons "CLOCKSUM_T"
15383 (org-columns-number-to-string (/ (float clocksumt) 60.)
15384 'add_times))
15385 props))
15386 (unless (assoc "CATEGORY" props)
15387 (push (cons "CATEGORY" (org-get-category)) props))
15388 (append sum-props (nreverse props)))))))
15390 (defun org-entry-get (pom property &optional inherit literal-nil)
15391 "Get value of PROPERTY for entry or content at point-or-marker POM.
15392 If INHERIT is non-nil and the entry does not have the property,
15393 then also check higher levels of the hierarchy.
15394 If INHERIT is the symbol `selective', use inheritance only if the setting
15395 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15396 If the property is present but empty, the return value is the empty string.
15397 If the property is not present at all, nil is returned.
15399 Return the value as a string.
15401 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15402 do not interpret it as the list atom nil. This is used for inheritance
15403 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15404 (org-with-point-at pom
15405 (if (and inherit (if (eq inherit 'selective)
15406 (org-property-inherit-p property)
15408 (org-entry-get-with-inheritance property literal-nil)
15409 (if (member property org-special-properties)
15410 ;; We need a special property. Use `org-entry-properties'
15411 ;; to retrieve it, but specify the wanted property
15412 (cdr (assoc property (org-entry-properties nil 'special property)))
15413 (org-with-wide-buffer
15414 (let ((range (org-get-property-block)))
15415 (when (and range (not (eq (car range) (cdr range))))
15416 (let* ((props
15417 (list (or (assoc property org-file-properties)
15418 (assoc property org-global-properties)
15419 (assoc property org-global-properties-fixed))))
15420 (ap (lambda (key)
15421 (when (re-search-forward
15422 (org-re-property key) (cdr range) t)
15423 (setq props
15424 (org-update-property-plist
15426 (if (match-end 3)
15427 (org-match-string-no-properties 3) "")
15428 props)))))
15429 val)
15430 (goto-char (car range))
15431 (funcall ap property)
15432 (goto-char (car range))
15433 (while (funcall ap (concat property "+")))
15434 (setq val (cdr (assoc property props)))
15435 (when val (if literal-nil val (org-not-nil val)))))))))))
15437 (defun org-property-or-variable-value (var &optional inherit)
15438 "Check if there is a property fixing the value of VAR.
15439 If yes, return this value. If not, return the current value of the variable."
15440 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15441 (if (and prop (stringp prop) (string-match "\\S-" prop))
15442 (read prop)
15443 (symbol-value var))))
15445 (defun org-entry-delete (pom property)
15446 "Delete the property PROPERTY from entry at point-or-marker POM."
15447 (unless (member property org-special-properties)
15448 (org-with-point-at pom
15449 (let ((range (org-get-property-block)))
15450 (if (and range
15451 (goto-char (car range))
15452 (re-search-forward
15453 (org-re-property property)
15454 (cdr range) t))
15455 (progn
15456 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15457 (org-remove-empty-drawer-at (car range))
15459 nil)))))
15461 ;; Multi-values properties are properties that contain multiple values
15462 ;; These values are assumed to be single words, separated by whitespace.
15463 (defun org-entry-add-to-multivalued-property (pom property value)
15464 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15465 (let* ((old (org-entry-get pom property))
15466 (values (and old (org-split-string old "[ \t]"))))
15467 (setq value (org-entry-protect-space value))
15468 (unless (member value values)
15469 (setq values (append values (list value)))
15470 (org-entry-put pom property
15471 (mapconcat 'identity values " ")))))
15473 (defun org-entry-remove-from-multivalued-property (pom property value)
15474 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15475 (let* ((old (org-entry-get pom property))
15476 (values (and old (org-split-string old "[ \t]"))))
15477 (setq value (org-entry-protect-space value))
15478 (when (member value values)
15479 (setq values (delete value values))
15480 (org-entry-put pom property
15481 (mapconcat 'identity values " ")))))
15483 (defun org-entry-member-in-multivalued-property (pom property value)
15484 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15485 (let* ((old (org-entry-get pom property))
15486 (values (and old (org-split-string old "[ \t]"))))
15487 (setq value (org-entry-protect-space value))
15488 (member value values)))
15490 (defun org-entry-get-multivalued-property (pom property)
15491 "Return a list of values in a multivalued property."
15492 (let* ((value (org-entry-get pom property))
15493 (values (and value (org-split-string value "[ \t]"))))
15494 (mapcar 'org-entry-restore-space values)))
15496 (defun org-entry-put-multivalued-property (pom property &rest values)
15497 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15498 VALUES should be a list of strings. Spaces will be protected."
15499 (org-entry-put pom property
15500 (mapconcat 'org-entry-protect-space values " "))
15501 (let* ((value (org-entry-get pom property))
15502 (values (and value (org-split-string value "[ \t]"))))
15503 (mapcar 'org-entry-restore-space values)))
15505 (defun org-entry-protect-space (s)
15506 "Protect spaces and newline in string S."
15507 (while (string-match " " s)
15508 (setq s (replace-match "%20" t t s)))
15509 (while (string-match "\n" s)
15510 (setq s (replace-match "%0A" t t s)))
15513 (defun org-entry-restore-space (s)
15514 "Restore spaces and newline in string S."
15515 (while (string-match "%20" s)
15516 (setq s (replace-match " " t t s)))
15517 (while (string-match "%0A" s)
15518 (setq s (replace-match "\n" t t s)))
15521 (defvar org-entry-property-inherited-from (make-marker)
15522 "Marker pointing to the entry from where a property was inherited.
15523 Each call to `org-entry-get-with-inheritance' will set this marker to the
15524 location of the entry where the inheritance search matched. If there was
15525 no match, the marker will point nowhere.
15526 Note that also `org-entry-get' calls this function, if the INHERIT flag
15527 is set.")
15529 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15530 "Get PROPERTY of entry or content at point, search higher levels if needed.
15531 The search will stop at the first ancestor which has the property defined.
15532 If the value found is \"nil\", return nil to show that the property
15533 should be considered as undefined (this is the meaning of nil here).
15534 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15535 (move-marker org-entry-property-inherited-from nil)
15536 (let (tmp)
15537 (save-excursion
15538 (save-restriction
15539 (widen)
15540 (catch 'ex
15541 (while t
15542 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15543 (or (ignore-errors (org-back-to-heading t))
15544 (goto-char (point-min)))
15545 (move-marker org-entry-property-inherited-from (point))
15546 (throw 'ex tmp))
15547 (or (ignore-errors (org-up-heading-safe))
15548 (throw 'ex nil))))))
15549 (setq tmp (or tmp
15550 (cdr (assoc property org-file-properties))
15551 (cdr (assoc property org-global-properties))
15552 (cdr (assoc property org-global-properties-fixed))))
15553 (if literal-nil tmp (org-not-nil tmp))))
15555 (defvar org-property-changed-functions nil
15556 "Hook called when the value of a property has changed.
15557 Each hook function should accept two arguments, the name of the property
15558 and the new value.")
15560 (defun org-entry-put (pom property value)
15561 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15562 If the value is `nil', it is converted to the empty string.
15563 If it is not a string, an error is raised."
15564 (cond ((null value) (setq value ""))
15565 ((not (stringp value))
15566 (error "Properties values should be strings.")))
15567 (org-with-point-at pom
15568 (org-back-to-heading t)
15569 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15570 range)
15571 (cond
15572 ((equal property "TODO")
15573 (when (and (string-match "\\S-" value)
15574 (not (member value org-todo-keywords-1)))
15575 (user-error "\"%s\" is not a valid TODO state" value))
15576 (if (or (not value)
15577 (not (string-match "\\S-" value)))
15578 (setq value 'none))
15579 (org-todo value)
15580 (org-set-tags nil 'align))
15581 ((equal property "PRIORITY")
15582 (org-priority (if (and value (string-match "\\S-" value))
15583 (string-to-char value) ?\ ))
15584 (org-set-tags nil 'align))
15585 ((equal property "CLOCKSUM")
15586 (if (not (re-search-forward
15587 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15588 (error "Cannot find a clock log")
15589 (goto-char (- (match-end 1) 2))
15590 (cond
15591 ((eq value 'earlier) (org-timestamp-down))
15592 ((eq value 'later) (org-timestamp-up)))
15593 (org-clock-sum-current-item)))
15594 ((equal property "SCHEDULED")
15595 (if (re-search-forward org-scheduled-time-regexp end t)
15596 (cond
15597 ((eq value 'earlier) (org-timestamp-change -1 'day))
15598 ((eq value 'later) (org-timestamp-change 1 'day))
15599 (t (call-interactively 'org-schedule)))
15600 (call-interactively 'org-schedule)))
15601 ((equal property "DEADLINE")
15602 (if (re-search-forward org-deadline-time-regexp end t)
15603 (cond
15604 ((eq value 'earlier) (org-timestamp-change -1 'day))
15605 ((eq value 'later) (org-timestamp-change 1 'day))
15606 (t (call-interactively 'org-deadline)))
15607 (call-interactively 'org-deadline)))
15608 ((member property org-special-properties)
15609 (error "The %s property can not yet be set with `org-entry-put'"
15610 property))
15611 (t ; a non-special property
15612 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15613 (setq range (org-get-property-block beg end 'force))
15614 (goto-char (car range))
15615 (if (re-search-forward
15616 (org-re-property property) (cdr range) t)
15617 (progn
15618 (delete-region (match-beginning 0) (match-end 0))
15619 (goto-char (match-beginning 0)))
15620 (goto-char (cdr range))
15621 (insert "\n")
15622 (backward-char 1)
15623 (org-indent-line))
15624 (insert ":" property ":")
15625 (and value (insert " " value))
15626 (org-indent-line)))))
15627 (run-hook-with-args 'org-property-changed-functions property value)))
15629 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15630 "Get all property keys in the current buffer.
15631 With INCLUDE-SPECIALS, also list the special properties that reflect things
15632 like tags and TODO state.
15633 With INCLUDE-DEFAULTS, also include properties that has special meaning
15634 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15635 and others.
15636 With INCLUDE-COLUMNS, also include property names given in COLUMN
15637 formats in the current buffer."
15638 (let (rtn range cfmt s p)
15639 (save-excursion
15640 (save-restriction
15641 (widen)
15642 (goto-char (point-min))
15643 (while (re-search-forward org-property-start-re nil t)
15644 (setq range (org-get-property-block))
15645 (goto-char (car range))
15646 (while (re-search-forward org-property-re
15647 (cdr range) t)
15648 (add-to-list 'rtn (org-match-string-no-properties 2)))
15649 (outline-next-heading))))
15651 (when include-specials
15652 (setq rtn (append org-special-properties rtn)))
15654 (when include-defaults
15655 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15656 (add-to-list 'rtn org-effort-property))
15658 (when include-columns
15659 (save-excursion
15660 (save-restriction
15661 (widen)
15662 (goto-char (point-min))
15663 (while (re-search-forward
15664 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15665 nil t)
15666 (setq cfmt (match-string 2) s 0)
15667 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15668 cfmt s)
15669 (setq s (match-end 0)
15670 p (match-string 1 cfmt))
15671 (unless (or (equal p "ITEM")
15672 (member p org-special-properties))
15673 (add-to-list 'rtn (match-string 1 cfmt))))))))
15675 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15677 (defun org-property-values (key)
15678 "Return a list of all values of property KEY in the current buffer."
15679 (save-excursion
15680 (save-restriction
15681 (widen)
15682 (goto-char (point-min))
15683 (let ((re (org-re-property key))
15684 values)
15685 (while (re-search-forward re nil t)
15686 (add-to-list 'values (org-trim (match-string 3))))
15687 (delete "" values)))))
15689 (defun org-insert-property-drawer ()
15690 "Insert a property drawer into the current entry."
15691 (org-back-to-heading t)
15692 (looking-at org-outline-regexp)
15693 (let ((indent (if org-adapt-indentation
15694 (- (match-end 0) (match-beginning 0))
15696 (beg (point))
15697 (re (concat "^[ \t]*" org-keyword-time-regexp))
15698 end hiddenp)
15699 (outline-next-heading)
15700 (setq end (point))
15701 (goto-char beg)
15702 (while (re-search-forward re end t))
15703 (setq hiddenp (outline-invisible-p))
15704 (end-of-line 1)
15705 (and (equal (char-after) ?\n) (forward-char 1))
15706 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15707 (if (member (match-string 1) '("CLOCK:" ":END:"))
15708 ;; just skip this line
15709 (beginning-of-line 2)
15710 ;; Drawer start, find the end
15711 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15712 (beginning-of-line 1)))
15713 (org-skip-over-state-notes)
15714 (skip-chars-backward " \t\n\r")
15715 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15716 (forward-char 1))
15717 (goto-char (point-at-eol))
15718 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15719 (beginning-of-line 0)
15720 (org-indent-to-column indent)
15721 (beginning-of-line 2)
15722 (org-indent-to-column indent)
15723 (beginning-of-line 0)
15724 (if hiddenp
15725 (save-excursion
15726 (org-back-to-heading t)
15727 (hide-entry))
15728 (org-flag-drawer t))))
15730 (defun org-insert-drawer (&optional arg drawer)
15731 "Insert a drawer at point.
15733 Optional argument DRAWER, when non-nil, is a string representing
15734 drawer's name. Otherwise, the user is prompted for a name.
15736 If a region is active, insert the drawer around that region
15737 instead.
15739 Point is left between drawer's boundaries."
15740 (interactive "P")
15741 (let* ((drawer (if arg "PROPERTIES"
15742 (or drawer (read-from-minibuffer "Drawer: ")))))
15743 (cond
15744 ;; With C-u, fall back on `org-insert-property-drawer'
15745 (arg (org-insert-property-drawer))
15747 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15748 (user-error "Invalid drawer name"))
15749 ;; With an active region, insert a drawer at point.
15750 ((not (org-region-active-p))
15751 (progn
15752 (unless (bolp) (insert "\n"))
15753 (insert (format ":%s:\n\n:END:\n" drawer))
15754 (forward-line -2)))
15755 ;; Otherwise, insert the drawer at point
15757 (let ((rbeg (region-beginning))
15758 (rend (copy-marker (region-end))))
15759 (unwind-protect
15760 (progn
15761 (goto-char rbeg)
15762 (beginning-of-line)
15763 (when (save-excursion
15764 (re-search-forward org-outline-regexp-bol rend t))
15765 (user-error "Drawers cannot contain headlines"))
15766 ;; Position point at the beginning of the first
15767 ;; non-blank line in region. Insert drawer's opening
15768 ;; there, then indent it.
15769 (org-skip-whitespace)
15770 (beginning-of-line)
15771 (insert ":" drawer ":\n")
15772 (forward-line -1)
15773 (indent-for-tab-command)
15774 ;; Move point to the beginning of the first blank line
15775 ;; after the last non-blank line in region. Insert
15776 ;; drawer's closing, then indent it.
15777 (goto-char rend)
15778 (skip-chars-backward " \r\t\n")
15779 (insert "\n:END:")
15780 (deactivate-mark t)
15781 (indent-for-tab-command)
15782 (unless (eolp) (insert "\n")))
15783 ;; Clear marker, whatever the outcome of insertion is.
15784 (set-marker rend nil)))))))
15786 (defvar org-property-set-functions-alist nil
15787 "Property set function alist.
15788 Each entry should have the following format:
15790 (PROPERTY . READ-FUNCTION)
15792 The read function will be called with the same argument as
15793 `org-completing-read'.")
15795 (defun org-set-property-function (property)
15796 "Get the function that should be used to set PROPERTY.
15797 This is computed according to `org-property-set-functions-alist'."
15798 (or (cdr (assoc property org-property-set-functions-alist))
15799 'org-completing-read))
15801 (defun org-read-property-value (property)
15802 "Read PROPERTY value from user."
15803 (let* ((completion-ignore-case t)
15804 (allowed (org-property-get-allowed-values nil property 'table))
15805 (cur (org-entry-get nil property))
15806 (prompt (concat property " value"
15807 (if (and cur (string-match "\\S-" cur))
15808 (concat " [" cur "]") "") ": "))
15809 (set-function (org-set-property-function property))
15810 (val (if allowed
15811 (funcall set-function prompt allowed nil
15812 (not (get-text-property 0 'org-unrestricted
15813 (caar allowed))))
15814 (let (org-completion-use-ido org-completion-use-iswitchb)
15815 (funcall set-function prompt
15816 (mapcar 'list (org-property-values property))
15817 nil nil "" nil cur)))))
15818 (if (equal val "")
15820 val)))
15822 (defvar org-last-set-property nil)
15823 (defvar org-last-set-property-value nil)
15824 (defun org-read-property-name ()
15825 "Read a property name."
15826 (let* ((completion-ignore-case t)
15827 (keys (org-buffer-property-keys nil t t))
15828 (default-prop (or (save-excursion
15829 (save-match-data
15830 (beginning-of-line)
15831 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15832 (null (string= (match-string 1) "END"))
15833 (match-string 1))))
15834 org-last-set-property))
15835 (property (org-icompleting-read
15836 (concat "Property"
15837 (if default-prop (concat " [" default-prop "]") "")
15838 ": ")
15839 (mapcar 'list keys)
15840 nil nil nil nil
15841 default-prop)))
15842 (if (member property keys)
15843 property
15844 (or (cdr (assoc (downcase property)
15845 (mapcar (lambda (x) (cons (downcase x) x))
15846 keys)))
15847 property))))
15849 (defun org-set-property-and-value (use-last)
15850 "Allow to set [PROPERTY]: [value] direction from prompt.
15851 When use-default, don't even ask, just use the last
15852 \"[PROPERTY]: [value]\" string from the history."
15853 (interactive "P")
15854 (let* ((completion-ignore-case t)
15855 (pv (or (and use-last org-last-set-property-value)
15856 (org-completing-read
15857 "Enter a \"[Property]: [value]\" pair: "
15858 nil nil nil nil nil
15859 org-last-set-property-value)))
15860 prop val)
15861 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15862 (setq prop (match-string 1 pv)
15863 val (match-string 2 pv))
15864 (org-set-property prop val))))
15866 (defun org-set-property (property value)
15867 "In the current entry, set PROPERTY to VALUE.
15868 When called interactively, this will prompt for a property name, offering
15869 completion on existing and default properties. And then it will prompt
15870 for a value, offering completion either on allowed values (via an inherited
15871 xxx_ALL property) or on existing values in other instances of this property
15872 in the current file."
15873 (interactive (list nil nil))
15874 (let* ((property (or property (org-read-property-name)))
15875 (value (or value (org-read-property-value property)))
15876 (fn (cdr (assoc property org-properties-postprocess-alist))))
15877 (setq org-last-set-property property)
15878 (setq org-last-set-property-value (concat property ": " value))
15879 ;; Possibly postprocess the inserted value:
15880 (when fn (setq value (funcall fn value)))
15881 (unless (equal (org-entry-get nil property) value)
15882 (org-entry-put nil property value))))
15884 (defun org-delete-property (property)
15885 "In the current entry, delete PROPERTY."
15886 (interactive
15887 (let* ((completion-ignore-case t)
15888 (prop (org-icompleting-read "Property: "
15889 (org-entry-properties nil 'standard))))
15890 (list prop)))
15891 (message "Property %s %s" property
15892 (if (org-entry-delete nil property)
15893 "deleted"
15894 "was not present in the entry")))
15896 (defun org-delete-property-globally (property)
15897 "Remove PROPERTY globally, from all entries."
15898 (interactive
15899 (let* ((completion-ignore-case t)
15900 (prop (org-icompleting-read
15901 "Globally remove property: "
15902 (mapcar 'list (org-buffer-property-keys)))))
15903 (list prop)))
15904 (save-excursion
15905 (save-restriction
15906 (widen)
15907 (goto-char (point-min))
15908 (let ((cnt 0))
15909 (while (re-search-forward
15910 (org-re-property property)
15911 nil t)
15912 (setq cnt (1+ cnt))
15913 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15914 (message "Property \"%s\" removed from %d entries" property cnt)))))
15916 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15918 (defun org-compute-property-at-point ()
15919 "Compute the property at point.
15920 This looks for an enclosing column format, extracts the operator and
15921 then applies it to the property in the column format's scope."
15922 (interactive)
15923 (unless (org-at-property-p)
15924 (user-error "Not at a property"))
15925 (let ((prop (org-match-string-no-properties 2)))
15926 (org-columns-get-format-and-top-level)
15927 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15928 (user-error "No operator defined for property %s" prop))
15929 (org-columns-compute prop)))
15931 (defvar org-property-allowed-value-functions nil
15932 "Hook for functions supplying allowed values for a specific property.
15933 The functions must take a single argument, the name of the property, and
15934 return a flat list of allowed values. If \":ETC\" is one of
15935 the values, this means that these values are intended as defaults for
15936 completion, but that other values should be allowed too.
15937 The functions must return nil if they are not responsible for this
15938 property.")
15940 (defun org-property-get-allowed-values (pom property &optional table)
15941 "Get allowed values for the property PROPERTY.
15942 When TABLE is non-nil, return an alist that can directly be used for
15943 completion."
15944 (let (vals)
15945 (cond
15946 ((equal property "TODO")
15947 (setq vals (org-with-point-at pom
15948 (append org-todo-keywords-1 '("")))))
15949 ((equal property "PRIORITY")
15950 (let ((n org-lowest-priority))
15951 (while (>= n org-highest-priority)
15952 (push (char-to-string n) vals)
15953 (setq n (1- n)))))
15954 ((member property org-special-properties))
15955 ((setq vals (run-hook-with-args-until-success
15956 'org-property-allowed-value-functions property)))
15958 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15959 (when (and vals (string-match "\\S-" vals))
15960 (setq vals (car (read-from-string (concat "(" vals ")"))))
15961 (setq vals (mapcar (lambda (x)
15962 (cond ((stringp x) x)
15963 ((numberp x) (number-to-string x))
15964 ((symbolp x) (symbol-name x))
15965 (t "???")))
15966 vals)))))
15967 (when (member ":ETC" vals)
15968 (setq vals (remove ":ETC" vals))
15969 (org-add-props (car vals) '(org-unrestricted t)))
15970 (if table (mapcar 'list vals) vals)))
15972 (defun org-property-previous-allowed-value (&optional previous)
15973 "Switch to the next allowed value for this property."
15974 (interactive)
15975 (org-property-next-allowed-value t))
15977 (defun org-property-next-allowed-value (&optional previous)
15978 "Switch to the next allowed value for this property."
15979 (interactive)
15980 (unless (org-at-property-p)
15981 (user-error "Not at a property"))
15982 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15983 (key (match-string 2))
15984 (value (match-string 3))
15985 (allowed (or (org-property-get-allowed-values (point) key)
15986 (and (member value '("[ ]" "[-]" "[X]"))
15987 '("[ ]" "[X]"))))
15988 (heading (save-match-data (nth 4 (org-heading-components))))
15989 nval)
15990 (unless allowed
15991 (user-error "Allowed values for this property have not been defined"))
15992 (if previous (setq allowed (reverse allowed)))
15993 (if (member value allowed)
15994 (setq nval (car (cdr (member value allowed)))))
15995 (setq nval (or nval (car allowed)))
15996 (if (equal nval value)
15997 (user-error "Only one allowed value for this property"))
15998 (org-at-property-p)
15999 (replace-match (concat " :" key ": " nval) t t)
16000 (org-indent-line)
16001 (beginning-of-line 1)
16002 (skip-chars-forward " \t")
16003 (when (equal prop org-effort-property)
16004 (save-excursion
16005 (org-back-to-heading t)
16006 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
16007 (when (string= org-clock-current-task heading)
16008 (setq org-clock-effort nval)
16009 (org-clock-update-mode-line)))
16010 (run-hook-with-args 'org-property-changed-functions key nval)))
16012 (defun org-find-olp (path &optional this-buffer)
16013 "Return a marker pointing to the entry at outline path OLP.
16014 If anything goes wrong, throw an error.
16015 You can wrap this call to catch the error like this:
16017 (condition-case msg
16018 (org-mobile-locate-entry (match-string 4))
16019 (error (nth 1 msg)))
16021 The return value will then be either a string with the error message,
16022 or a marker if everything is OK.
16024 If THIS-BUFFER is set, the outline path does not contain a file,
16025 only headings."
16026 (let* ((file (if this-buffer buffer-file-name (pop path)))
16027 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16028 (level 1)
16029 (lmin 1)
16030 (lmax 1)
16031 limit re end found pos heading cnt flevel)
16032 (unless buffer (error "File not found :%s" file))
16033 (with-current-buffer buffer
16034 (save-excursion
16035 (save-restriction
16036 (widen)
16037 (setq limit (point-max))
16038 (goto-char (point-min))
16039 (while (setq heading (pop path))
16040 (setq re (format org-complex-heading-regexp-format
16041 (regexp-quote heading)))
16042 (setq cnt 0 pos (point))
16043 (while (re-search-forward re end t)
16044 (setq level (- (match-end 1) (match-beginning 1)))
16045 (if (and (>= level lmin) (<= level lmax))
16046 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16047 (when (= cnt 0) (error "Heading not found on level %d: %s"
16048 lmax heading))
16049 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16050 lmax heading))
16051 (goto-char found)
16052 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16053 (setq end (save-excursion (org-end-of-subtree t t))))
16054 (when (org-at-heading-p)
16055 (point-marker)))))))
16057 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16058 "Find node HEADING in BUFFER.
16059 Return a marker to the heading if it was found, or nil if not.
16060 If POS-ONLY is set, return just the position instead of a marker.
16062 The heading text must match exact, but it may have a TODO keyword,
16063 a priority cookie and tags in the standard locations."
16064 (with-current-buffer (or buffer (current-buffer))
16065 (save-excursion
16066 (save-restriction
16067 (widen)
16068 (goto-char (point-min))
16069 (let (case-fold-search)
16070 (if (re-search-forward
16071 (format org-complex-heading-regexp-format
16072 (regexp-quote heading)) nil t)
16073 (if pos-only
16074 (match-beginning 0)
16075 (move-marker (make-marker) (match-beginning 0)))))))))
16077 (defun org-find-exact-heading-in-directory (heading &optional dir)
16078 "Find Org node headline HEADING in all .org files in directory DIR.
16079 When the target headline is found, return a marker to this location."
16080 (let ((files (directory-files (or dir default-directory)
16081 nil "\\`[^.#].*\\.org\\'"))
16082 file visiting m buffer)
16083 (catch 'found
16084 (while (setq file (pop files))
16085 (message "trying %s" file)
16086 (setq visiting (org-find-base-buffer-visiting file))
16087 (setq buffer (or visiting (find-file-noselect file)))
16088 (setq m (org-find-exact-headline-in-buffer
16089 heading buffer))
16090 (when (and (not m) (not visiting)) (kill-buffer buffer))
16091 (and m (throw 'found m))))))
16093 (defun org-find-entry-with-id (ident)
16094 "Locate the entry that contains the ID property with exact value IDENT.
16095 IDENT can be a string, a symbol or a number, this function will search for
16096 the string representation of it.
16097 Return the position where this entry starts, or nil if there is no such entry."
16098 (interactive "sID: ")
16099 (let ((id (cond
16100 ((stringp ident) ident)
16101 ((symbol-name ident) (symbol-name ident))
16102 ((numberp ident) (number-to-string ident))
16103 (t (error "IDENT %s must be a string, symbol or number" ident))))
16104 (case-fold-search nil))
16105 (save-excursion
16106 (save-restriction
16107 (widen)
16108 (goto-char (point-min))
16109 (when (re-search-forward
16110 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16111 nil t)
16112 (org-back-to-heading t)
16113 (point))))))
16115 ;;;; Timestamps
16117 (defvar org-last-changed-timestamp nil)
16118 (defvar org-last-inserted-timestamp nil
16119 "The last time stamp inserted with `org-insert-time-stamp'.")
16120 (defvar org-ts-what) ; dynamically scoped parameter
16122 (defun org-time-stamp (arg &optional inactive)
16123 "Prompt for a date/time and insert a time stamp.
16124 If the user specifies a time like HH:MM or if this command is
16125 called with at least one prefix argument, the time stamp contains
16126 the date and the time. Otherwise, only the date is be included.
16128 All parts of a date not specified by the user is filled in from
16129 the current date/time. So if you just press return without
16130 typing anything, the time stamp will represent the current
16131 date/time.
16133 If there is already a timestamp at the cursor, it will be
16134 modified.
16136 With two universal prefix arguments, insert an active timestamp
16137 with the current time without prompting the user.
16139 When called from lisp, the timestamp is inactive if INACTIVE is
16140 non-nil."
16141 (interactive "P")
16142 (let* ((ts nil)
16143 (default-time
16144 ;; Default time is either today, or, when entering a range,
16145 ;; the range start.
16146 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16147 (save-excursion
16148 (re-search-backward
16149 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16150 (- (point) 20) t)))
16151 (apply 'encode-time (org-parse-time-string (match-string 1)))
16152 (current-time)))
16153 (default-input (and ts (org-get-compact-tod ts)))
16154 (repeater (save-excursion
16155 (save-match-data
16156 (beginning-of-line)
16157 (when (re-search-forward
16158 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16159 (save-excursion (progn (end-of-line) (point))) t)
16160 (match-string 0)))))
16161 org-time-was-given org-end-time-was-given time)
16162 (cond
16163 ((and (org-at-timestamp-p t)
16164 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16165 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16166 (insert "--")
16167 (setq time (let ((this-command this-command))
16168 (org-read-date arg 'totime nil nil
16169 default-time default-input inactive)))
16170 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16171 ((org-at-timestamp-p t)
16172 (setq time (let ((this-command this-command))
16173 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16174 (when (org-at-timestamp-p t) ; just to get the match data
16175 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16176 (replace-match "")
16177 (setq org-last-changed-timestamp
16178 (org-insert-time-stamp
16179 time (or org-time-was-given arg)
16180 inactive nil nil (list org-end-time-was-given)))
16181 (when repeater (goto-char (1- (point))) (insert " " repeater)
16182 (setq org-last-changed-timestamp
16183 (concat (substring org-last-inserted-timestamp 0 -1)
16184 " " repeater ">"))))
16185 (message "Timestamp updated"))
16186 ((equal arg '(16))
16187 (org-insert-time-stamp (current-time) t inactive))
16189 (setq time (let ((this-command this-command))
16190 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16191 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16192 nil nil (list org-end-time-was-given))))))
16194 ;; FIXME: can we use this for something else, like computing time differences?
16195 (defun org-get-compact-tod (s)
16196 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16197 (let* ((t1 (match-string 1 s))
16198 (h1 (string-to-number (match-string 2 s)))
16199 (m1 (string-to-number (match-string 3 s)))
16200 (t2 (and (match-end 4) (match-string 5 s)))
16201 (h2 (and t2 (string-to-number (match-string 6 s))))
16202 (m2 (and t2 (string-to-number (match-string 7 s))))
16203 dh dm)
16204 (if (not t2)
16206 (setq dh (- h2 h1) dm (- m2 m1))
16207 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16208 (concat t1 "+" (number-to-string dh)
16209 (and (/= 0 dm) (format ":%02d" dm)))))))
16211 (defun org-time-stamp-inactive (&optional arg)
16212 "Insert an inactive time stamp.
16213 An inactive time stamp is enclosed in square brackets instead of angle
16214 brackets. It is inactive in the sense that it does not trigger agenda entries,
16215 does not link to the calendar and cannot be changed with the S-cursor keys.
16216 So these are more for recording a certain time/date."
16217 (interactive "P")
16218 (org-time-stamp arg 'inactive))
16220 (defvar org-date-ovl (make-overlay 1 1))
16221 (overlay-put org-date-ovl 'face 'org-date-selected)
16222 (org-detach-overlay org-date-ovl)
16224 (defvar org-ans1) ; dynamically scoped parameter
16225 (defvar org-ans2) ; dynamically scoped parameter
16227 (defvar org-plain-time-of-day-regexp) ; defined below
16229 (defvar org-overriding-default-time nil) ; dynamically scoped
16230 (defvar org-read-date-overlay nil)
16231 (defvar org-dcst nil) ; dynamically scoped
16232 (defvar org-read-date-history nil)
16233 (defvar org-read-date-final-answer nil)
16234 (defvar org-read-date-analyze-futurep nil)
16235 (defvar org-read-date-analyze-forced-year nil)
16236 (defvar org-read-date-inactive)
16238 (defvar org-read-date-minibuffer-local-map
16239 (let* ((org-replace-disputed-keys nil)
16240 (map (make-sparse-keymap)))
16241 (set-keymap-parent map minibuffer-local-map)
16242 (org-defkey map (kbd ".")
16243 (lambda () (interactive)
16244 ;; Are we at the beginning of the prompt?
16245 (if (looking-back "^[^:]+: ")
16246 (org-eval-in-calendar '(calendar-goto-today))
16247 (insert "."))))
16248 (org-defkey map (kbd "C-.")
16249 (lambda () (interactive)
16250 (org-eval-in-calendar '(calendar-goto-today))))
16251 (org-defkey map [(meta shift left)]
16252 (lambda () (interactive)
16253 (org-eval-in-calendar '(calendar-backward-month 1))))
16254 (org-defkey map [(meta shift right)]
16255 (lambda () (interactive)
16256 (org-eval-in-calendar '(calendar-forward-month 1))))
16257 (org-defkey map [(meta shift up)]
16258 (lambda () (interactive)
16259 (org-eval-in-calendar '(calendar-backward-year 1))))
16260 (org-defkey map [(meta shift down)]
16261 (lambda () (interactive)
16262 (org-eval-in-calendar '(calendar-forward-year 1))))
16263 (org-defkey map [?\e (shift left)]
16264 (lambda () (interactive)
16265 (org-eval-in-calendar '(calendar-backward-month 1))))
16266 (org-defkey map [?\e (shift right)]
16267 (lambda () (interactive)
16268 (org-eval-in-calendar '(calendar-forward-month 1))))
16269 (org-defkey map [?\e (shift up)]
16270 (lambda () (interactive)
16271 (org-eval-in-calendar '(calendar-backward-year 1))))
16272 (org-defkey map [?\e (shift down)]
16273 (lambda () (interactive)
16274 (org-eval-in-calendar '(calendar-forward-year 1))))
16275 (org-defkey map [(shift up)]
16276 (lambda () (interactive)
16277 (org-eval-in-calendar '(calendar-backward-week 1))))
16278 (org-defkey map [(shift down)]
16279 (lambda () (interactive)
16280 (org-eval-in-calendar '(calendar-forward-week 1))))
16281 (org-defkey map [(shift left)]
16282 (lambda () (interactive)
16283 (org-eval-in-calendar '(calendar-backward-day 1))))
16284 (org-defkey map [(shift right)]
16285 (lambda () (interactive)
16286 (org-eval-in-calendar '(calendar-forward-day 1))))
16287 (org-defkey map "!"
16288 (lambda () (interactive)
16289 (org-eval-in-calendar '(diary-view-entries))
16290 (message "")))
16291 (org-defkey map ">"
16292 (lambda () (interactive)
16293 (org-eval-in-calendar '(scroll-calendar-left 1))))
16294 (org-defkey map "<"
16295 (lambda () (interactive)
16296 (org-eval-in-calendar '(scroll-calendar-right 1))))
16297 (org-defkey map "\C-v"
16298 (lambda () (interactive)
16299 (org-eval-in-calendar
16300 '(calendar-scroll-left-three-months 1))))
16301 (org-defkey map "\M-v"
16302 (lambda () (interactive)
16303 (org-eval-in-calendar
16304 '(calendar-scroll-right-three-months 1))))
16305 map)
16306 "Keymap for minibuffer commands when using `org-read-date'.")
16308 (defvar org-def)
16309 (defvar org-defdecode)
16310 (defvar org-with-time)
16312 (defun org-read-date (&optional org-with-time to-time from-string prompt
16313 default-time default-input inactive)
16314 "Read a date, possibly a time, and make things smooth for the user.
16315 The prompt will suggest to enter an ISO date, but you can also enter anything
16316 which will at least partially be understood by `parse-time-string'.
16317 Unrecognized parts of the date will default to the current day, month, year,
16318 hour and minute. If this command is called to replace a timestamp at point,
16319 or to enter the second timestamp of a range, the default time is taken
16320 from the existing stamp. Furthermore, the command prefers the future,
16321 so if you are giving a date where the year is not given, and the day-month
16322 combination is already past in the current year, it will assume you
16323 mean next year. For details, see the manual. A few examples:
16325 3-2-5 --> 2003-02-05
16326 feb 15 --> currentyear-02-15
16327 2/15 --> currentyear-02-15
16328 sep 12 9 --> 2009-09-12
16329 12:45 --> today 12:45
16330 22 sept 0:34 --> currentyear-09-22 0:34
16331 12 --> currentyear-currentmonth-12
16332 Fri --> nearest Friday after today
16333 -Tue --> last Tuesday
16334 etc.
16336 Furthermore you can specify a relative date by giving, as the *first* thing
16337 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16338 change in days weeks, months, years.
16339 With a single plus or minus, the date is relative to today. With a double
16340 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16341 +4d --> four days from today
16342 +4 --> same as above
16343 +2w --> two weeks from today
16344 ++5 --> five days from default date
16346 The function understands only English month and weekday abbreviations.
16348 While prompting, a calendar is popped up - you can also select the
16349 date with the mouse (button 1). The calendar shows a period of three
16350 months. To scroll it to other months, use the keys `>' and `<'.
16351 If you don't like the calendar, turn it off with
16352 \(setq org-read-date-popup-calendar nil)
16354 With optional argument TO-TIME, the date will immediately be converted
16355 to an internal time.
16356 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16357 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16358 still enter a time, and this function will inform the calling routine
16359 about this change. The calling routine may then choose to change the
16360 format used to insert the time stamp into the buffer to include the time.
16361 With optional argument FROM-STRING, read from this string instead from
16362 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16363 the time/date that is used for everything that is not specified by the
16364 user."
16365 (require 'parse-time)
16366 (let* ((org-time-stamp-rounding-minutes
16367 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16368 (org-dcst org-display-custom-times)
16369 (ct (org-current-time))
16370 (org-def (or org-overriding-default-time default-time ct))
16371 (org-defdecode (decode-time org-def))
16372 (dummy (progn
16373 (when (< (nth 2 org-defdecode) org-extend-today-until)
16374 (setcar (nthcdr 2 org-defdecode) -1)
16375 (setcar (nthcdr 1 org-defdecode) 59)
16376 (setq org-def (apply 'encode-time org-defdecode)
16377 org-defdecode (decode-time org-def)))))
16378 (mouse-autoselect-window nil) ; Don't let the mouse jump
16379 (calendar-frame-setup nil)
16380 (calendar-setup nil)
16381 (calendar-move-hook nil)
16382 (calendar-view-diary-initially-flag nil)
16383 (calendar-view-holidays-initially-flag nil)
16384 (timestr (format-time-string
16385 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16386 (prompt (concat (if prompt (concat prompt " ") "")
16387 (format "Date+time [%s]: " timestr)))
16388 ans (org-ans0 "") org-ans1 org-ans2 final)
16390 (cond
16391 (from-string (setq ans from-string))
16392 (org-read-date-popup-calendar
16393 (save-excursion
16394 (save-window-excursion
16395 (calendar)
16396 (org-eval-in-calendar '(setq cursor-type nil) t)
16397 (unwind-protect
16398 (progn
16399 (calendar-forward-day (- (time-to-days org-def)
16400 (calendar-absolute-from-gregorian
16401 (calendar-current-date))))
16402 (org-eval-in-calendar nil t)
16403 (let* ((old-map (current-local-map))
16404 (map (copy-keymap calendar-mode-map))
16405 (minibuffer-local-map
16406 (copy-keymap org-read-date-minibuffer-local-map)))
16407 (org-defkey map (kbd "RET") 'org-calendar-select)
16408 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16409 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16410 (unwind-protect
16411 (progn
16412 (use-local-map map)
16413 (setq org-read-date-inactive inactive)
16414 (add-hook 'post-command-hook 'org-read-date-display)
16415 (setq org-ans0 (read-string prompt default-input
16416 'org-read-date-history nil))
16417 ;; org-ans0: from prompt
16418 ;; org-ans1: from mouse click
16419 ;; org-ans2: from calendar motion
16420 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16421 (remove-hook 'post-command-hook 'org-read-date-display)
16422 (use-local-map old-map)
16423 (when org-read-date-overlay
16424 (delete-overlay org-read-date-overlay)
16425 (setq org-read-date-overlay nil)))))
16426 (bury-buffer "*Calendar*")))))
16428 (t ; Naked prompt only
16429 (unwind-protect
16430 (setq ans (read-string prompt default-input
16431 'org-read-date-history timestr))
16432 (when org-read-date-overlay
16433 (delete-overlay org-read-date-overlay)
16434 (setq org-read-date-overlay nil)))))
16436 (setq final (org-read-date-analyze ans org-def org-defdecode))
16438 (when org-read-date-analyze-forced-year
16439 (message "Year was forced into %s"
16440 (if org-read-date-force-compatible-dates
16441 "compatible range (1970-2037)"
16442 "range representable on this machine"))
16443 (ding))
16445 ;; One round trip to get rid of 34th of August and stuff like that....
16446 (setq final (decode-time (apply 'encode-time final)))
16448 (setq org-read-date-final-answer ans)
16450 (if to-time
16451 (apply 'encode-time final)
16452 (if (and (boundp 'org-time-was-given) org-time-was-given)
16453 (format "%04d-%02d-%02d %02d:%02d"
16454 (nth 5 final) (nth 4 final) (nth 3 final)
16455 (nth 2 final) (nth 1 final))
16456 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16458 (defun org-read-date-display ()
16459 "Display the current date prompt interpretation in the minibuffer."
16460 (when org-read-date-display-live
16461 (when org-read-date-overlay
16462 (delete-overlay org-read-date-overlay))
16463 (when (minibufferp (current-buffer))
16464 (save-excursion
16465 (end-of-line 1)
16466 (while (not (equal (buffer-substring
16467 (max (point-min) (- (point) 4)) (point))
16468 " "))
16469 (insert " ")))
16470 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16471 " " (or org-ans1 org-ans2)))
16472 (org-end-time-was-given nil)
16473 (f (org-read-date-analyze ans org-def org-defdecode))
16474 (fmts (if org-dcst
16475 org-time-stamp-custom-formats
16476 org-time-stamp-formats))
16477 (fmt (if (or org-with-time
16478 (and (boundp 'org-time-was-given) org-time-was-given))
16479 (cdr fmts)
16480 (car fmts)))
16481 (txt (format-time-string fmt (apply 'encode-time f)))
16482 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16483 (txt (concat "=> " txt)))
16484 (when (and org-end-time-was-given
16485 (string-match org-plain-time-of-day-regexp txt))
16486 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16487 org-end-time-was-given
16488 (substring txt (match-end 0)))))
16489 (when org-read-date-analyze-futurep
16490 (setq txt (concat txt " (=>F)")))
16491 (setq org-read-date-overlay
16492 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16493 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16495 (defun org-read-date-analyze (ans org-def org-defdecode)
16496 "Analyze the combined answer of the date prompt."
16497 ;; FIXME: cleanup and comment
16498 (let ((nowdecode (decode-time (current-time)))
16499 delta deltan deltaw deltadef year month day
16500 hour minute second wday pm h2 m2 tl wday1
16501 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16502 (setq org-read-date-analyze-futurep nil
16503 org-read-date-analyze-forced-year nil)
16504 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16505 (setq ans "+0"))
16507 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16508 (setq ans (replace-match "" t t ans)
16509 deltan (car delta)
16510 deltaw (nth 1 delta)
16511 deltadef (nth 2 delta)))
16513 ;; Check if there is an iso week date in there. If yes, store the
16514 ;; info and postpone interpreting it until the rest of the parsing
16515 ;; is done.
16516 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16517 (setq iso-year (if (match-end 1)
16518 (org-small-year-to-year
16519 (string-to-number (match-string 1 ans))))
16520 iso-weekday (if (match-end 3)
16521 (string-to-number (match-string 3 ans)))
16522 iso-week (string-to-number (match-string 2 ans)))
16523 (setq ans (replace-match "" t t ans)))
16525 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16526 (when (string-match
16527 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16528 (setq year (if (match-end 2)
16529 (string-to-number (match-string 2 ans))
16530 (progn (setq kill-year t)
16531 (string-to-number (format-time-string "%Y"))))
16532 month (string-to-number (match-string 3 ans))
16533 day (string-to-number (match-string 4 ans)))
16534 (if (< year 100) (setq year (+ 2000 year)))
16535 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16536 t nil ans)))
16538 ;; Help matching dotted european dates
16539 (when (string-match
16540 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16541 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16542 (setq kill-year t)
16543 (string-to-number (format-time-string "%Y")))
16544 day (string-to-number (match-string 1 ans))
16545 month (string-to-number (match-string 2 ans))
16546 ans (replace-match (format "%04d-%02d-%02d" year month day)
16547 t nil ans)))
16549 ;; Help matching american dates, like 5/30 or 5/30/7
16550 (when (string-match
16551 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16552 (setq year (if (match-end 4)
16553 (string-to-number (match-string 4 ans))
16554 (progn (setq kill-year t)
16555 (string-to-number (format-time-string "%Y"))))
16556 month (string-to-number (match-string 1 ans))
16557 day (string-to-number (match-string 2 ans)))
16558 (if (< year 100) (setq year (+ 2000 year)))
16559 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16560 t nil ans)))
16561 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16562 ;; If there is a time with am/pm, and *no* time without it, we convert
16563 ;; so that matching will be successful.
16564 (loop for i from 1 to 2 do ; twice, for end time as well
16565 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16566 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16567 (setq hour (string-to-number (match-string 1 ans))
16568 minute (if (match-end 3)
16569 (string-to-number (match-string 3 ans))
16571 pm (equal ?p
16572 (string-to-char (downcase (match-string 4 ans)))))
16573 (if (and (= hour 12) (not pm))
16574 (setq hour 0)
16575 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16576 (setq ans (replace-match (format "%02d:%02d" hour minute)
16577 t t ans))))
16579 ;; Check if a time range is given as a duration
16580 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16581 (setq hour (string-to-number (match-string 1 ans))
16582 h2 (+ hour (string-to-number (match-string 3 ans)))
16583 minute (string-to-number (match-string 2 ans))
16584 m2 (+ minute (if (match-end 5) (string-to-number
16585 (match-string 5 ans))0)))
16586 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16587 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16588 t t ans)))
16590 ;; Check if there is a time range
16591 (when (boundp 'org-end-time-was-given)
16592 (setq org-time-was-given nil)
16593 (when (and (string-match org-plain-time-of-day-regexp ans)
16594 (match-end 8))
16595 (setq org-end-time-was-given (match-string 8 ans))
16596 (setq ans (concat (substring ans 0 (match-beginning 7))
16597 (substring ans (match-end 7))))))
16599 (setq tl (parse-time-string ans)
16600 day (or (nth 3 tl) (nth 3 org-defdecode))
16601 month (or (nth 4 tl)
16602 (if (and org-read-date-prefer-future
16603 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16604 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16605 (nth 4 org-defdecode)))
16606 year (or (and (not kill-year) (nth 5 tl))
16607 (if (and org-read-date-prefer-future
16608 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16609 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16610 (nth 5 org-defdecode)))
16611 hour (or (nth 2 tl) (nth 2 org-defdecode))
16612 minute (or (nth 1 tl) (nth 1 org-defdecode))
16613 second (or (nth 0 tl) 0)
16614 wday (nth 6 tl))
16616 (when (and (eq org-read-date-prefer-future 'time)
16617 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16618 (equal day (nth 3 nowdecode))
16619 (equal month (nth 4 nowdecode))
16620 (equal year (nth 5 nowdecode))
16621 (nth 2 tl)
16622 (or (< (nth 2 tl) (nth 2 nowdecode))
16623 (and (= (nth 2 tl) (nth 2 nowdecode))
16624 (nth 1 tl)
16625 (< (nth 1 tl) (nth 1 nowdecode)))))
16626 (setq day (1+ day)
16627 futurep t))
16629 ;; Special date definitions below
16630 (cond
16631 (iso-week
16632 ;; There was an iso week
16633 (require 'cal-iso)
16634 (setq futurep nil)
16635 (setq year (or iso-year year)
16636 day (or iso-weekday wday 1)
16637 wday nil ; to make sure that the trigger below does not match
16638 iso-date (calendar-gregorian-from-absolute
16639 (calendar-absolute-from-iso
16640 (list iso-week day year))))
16641 ; FIXME: Should we also push ISO weeks into the future?
16642 ; (when (and org-read-date-prefer-future
16643 ; (not iso-year)
16644 ; (< (calendar-absolute-from-gregorian iso-date)
16645 ; (time-to-days (current-time))))
16646 ; (setq year (1+ year)
16647 ; iso-date (calendar-gregorian-from-absolute
16648 ; (calendar-absolute-from-iso
16649 ; (list iso-week day year)))))
16650 (setq month (car iso-date)
16651 year (nth 2 iso-date)
16652 day (nth 1 iso-date)))
16653 (deltan
16654 (setq futurep nil)
16655 (unless deltadef
16656 (let ((now (decode-time (current-time))))
16657 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16658 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16659 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16660 ((equal deltaw "m") (setq month (+ month deltan)))
16661 ((equal deltaw "y") (setq year (+ year deltan)))))
16662 ((and wday (not (nth 3 tl)))
16663 ;; Weekday was given, but no day, so pick that day in the week
16664 ;; on or after the derived date.
16665 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16666 (unless (equal wday wday1)
16667 (setq day (+ day (% (- wday wday1 -7) 7))))))
16668 (if (and (boundp 'org-time-was-given)
16669 (nth 2 tl))
16670 (setq org-time-was-given t))
16671 (if (< year 100) (setq year (+ 2000 year)))
16672 ;; Check of the date is representable
16673 (if org-read-date-force-compatible-dates
16674 (progn
16675 (if (< year 1970)
16676 (setq year 1970 org-read-date-analyze-forced-year t))
16677 (if (> year 2037)
16678 (setq year 2037 org-read-date-analyze-forced-year t)))
16679 (condition-case nil
16680 (ignore (encode-time second minute hour day month year))
16681 (error
16682 (setq year (nth 5 org-defdecode))
16683 (setq org-read-date-analyze-forced-year t))))
16684 (setq org-read-date-analyze-futurep futurep)
16685 (list second minute hour day month year)))
16687 (defvar parse-time-weekdays)
16688 (defun org-read-date-get-relative (s today default)
16689 "Check string S for special relative date string.
16690 TODAY and DEFAULT are internal times, for today and for a default.
16691 Return shift list (N what def-flag)
16692 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16693 N is the number of WHATs to shift.
16694 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16695 the DEFAULT date rather than TODAY."
16696 (require 'parse-time)
16697 (when (and
16698 (string-match
16699 (concat
16700 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16701 "\\([0-9]+\\)?"
16702 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16703 "\\([ \t]\\|$\\)") s)
16704 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16705 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16706 (string-to-char (substring (match-string 1 s) -1))
16707 ?+))
16708 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16709 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16710 (what (if (match-end 3) (match-string 3 s) "d"))
16711 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16712 (date (if rel default today))
16713 (wday (nth 6 (decode-time date)))
16714 delta)
16715 (if wday1
16716 (progn
16717 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16718 (if (= delta 0) (setq delta 7))
16719 (if (= dir ?-)
16720 (progn
16721 (setq delta (- delta 7))
16722 (if (= delta 0) (setq delta -7))))
16723 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16724 (list delta "d" rel))
16725 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16727 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16728 "Turn a user-specified date into the internal representation.
16729 The internal representation needed by the calendar is (month day year).
16730 This is a wrapper to handle the brain-dead convention in calendar that
16731 user function argument order change dependent on argument order."
16732 (if (boundp 'calendar-date-style)
16733 (cond
16734 ((eq calendar-date-style 'american)
16735 (list arg1 arg2 arg3))
16736 ((eq calendar-date-style 'european)
16737 (list arg2 arg1 arg3))
16738 ((eq calendar-date-style 'iso)
16739 (list arg2 arg3 arg1)))
16740 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16741 (if (org-bound-and-true-p european-calendar-style)
16742 (list arg2 arg1 arg3)
16743 (list arg1 arg2 arg3)))))
16745 (defun org-eval-in-calendar (form &optional keepdate)
16746 "Eval FORM in the calendar window and return to current window.
16747 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16748 otherwise stick to the current value of `org-ans2'."
16749 (let ((sf (selected-frame))
16750 (sw (selected-window)))
16751 (select-window (get-buffer-window "*Calendar*" t))
16752 (eval form)
16753 (when (and (not keepdate) (calendar-cursor-to-date))
16754 (let* ((date (calendar-cursor-to-date))
16755 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16756 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16757 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16758 (select-window sw)
16759 (org-select-frame-set-input-focus sf)))
16761 (defun org-calendar-select ()
16762 "Return to `org-read-date' with the date currently selected.
16763 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16764 (interactive)
16765 (when (calendar-cursor-to-date)
16766 (let* ((date (calendar-cursor-to-date))
16767 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16768 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16769 (if (active-minibuffer-window) (exit-minibuffer))))
16771 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16772 "Insert a date stamp for the date given by the internal TIME.
16773 WITH-HM means use the stamp format that includes the time of the day.
16774 INACTIVE means use square brackets instead of angular ones, so that the
16775 stamp will not contribute to the agenda.
16776 PRE and POST are optional strings to be inserted before and after the
16777 stamp.
16778 The command returns the inserted time stamp."
16779 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16780 stamp)
16781 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16782 (insert-before-markers (or pre ""))
16783 (when (listp extra)
16784 (setq extra (car extra))
16785 (if (and (stringp extra)
16786 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16787 (setq extra (format "-%02d:%02d"
16788 (string-to-number (match-string 1 extra))
16789 (string-to-number (match-string 2 extra))))
16790 (setq extra nil)))
16791 (when extra
16792 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16793 (insert-before-markers (setq stamp (format-time-string fmt time)))
16794 (insert-before-markers (or post ""))
16795 (setq org-last-inserted-timestamp stamp)))
16797 (defun org-toggle-time-stamp-overlays ()
16798 "Toggle the use of custom time stamp formats."
16799 (interactive)
16800 (setq org-display-custom-times (not org-display-custom-times))
16801 (unless org-display-custom-times
16802 (let ((p (point-min)) (bmp (buffer-modified-p)))
16803 (while (setq p (next-single-property-change p 'display))
16804 (if (and (get-text-property p 'display)
16805 (eq (get-text-property p 'face) 'org-date))
16806 (remove-text-properties
16807 p (setq p (next-single-property-change p 'display))
16808 '(display t))))
16809 (set-buffer-modified-p bmp)))
16810 (if (featurep 'xemacs)
16811 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16812 (org-restart-font-lock)
16813 (setq org-table-may-need-update t)
16814 (if org-display-custom-times
16815 (message "Time stamps are overlaid with custom format")
16816 (message "Time stamp overlays removed")))
16818 (defun org-display-custom-time (beg end)
16819 "Overlay modified time stamp format over timestamp between BEG and END."
16820 (let* ((ts (buffer-substring beg end))
16821 t1 w1 with-hm tf time str w2 (off 0))
16822 (save-match-data
16823 (setq t1 (org-parse-time-string ts t))
16824 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16825 (setq off (- (match-end 0) (match-beginning 0)))))
16826 (setq end (- end off))
16827 (setq w1 (- end beg)
16828 with-hm (and (nth 1 t1) (nth 2 t1))
16829 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16830 time (org-fix-decoded-time t1)
16831 str (org-add-props
16832 (format-time-string
16833 (substring tf 1 -1) (apply 'encode-time time))
16834 nil 'mouse-face 'highlight)
16835 w2 (length str))
16836 (if (not (= w2 w1))
16837 (add-text-properties (1+ beg) (+ 2 beg)
16838 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16839 (if (featurep 'xemacs)
16840 (progn
16841 (put-text-property beg end 'invisible t)
16842 (put-text-property beg end 'end-glyph (make-glyph str)))
16843 (put-text-property beg end 'display str))))
16845 (defun org-translate-time (string)
16846 "Translate all timestamps in STRING to custom format.
16847 But do this only if the variable `org-display-custom-times' is set."
16848 (when org-display-custom-times
16849 (save-match-data
16850 (let* ((start 0)
16851 (re org-ts-regexp-both)
16852 t1 with-hm inactive tf time str beg end)
16853 (while (setq start (string-match re string start))
16854 (setq beg (match-beginning 0)
16855 end (match-end 0)
16856 t1 (save-match-data
16857 (org-parse-time-string (substring string beg end) t))
16858 with-hm (and (nth 1 t1) (nth 2 t1))
16859 inactive (equal (substring string beg (1+ beg)) "[")
16860 tf (funcall (if with-hm 'cdr 'car)
16861 org-time-stamp-custom-formats)
16862 time (org-fix-decoded-time t1)
16863 str (format-time-string
16864 (concat
16865 (if inactive "[" "<") (substring tf 1 -1)
16866 (if inactive "]" ">"))
16867 (apply 'encode-time time))
16868 string (replace-match str t t string)
16869 start (+ start (length str)))))))
16870 string)
16872 (defun org-fix-decoded-time (time)
16873 "Set 0 instead of nil for the first 6 elements of time.
16874 Don't touch the rest."
16875 (let ((n 0))
16876 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16878 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16880 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16881 "Difference between TIMESTAMP-STRING and now in days.
16882 If SECONDS is non-nil, return the difference in seconds."
16883 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16884 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16885 (funcall fdiff (current-time)))))
16887 (defun org-deadline-close (timestamp-string &optional ndays)
16888 "Is the time in TIMESTAMP-STRING close to the current date?"
16889 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16890 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16891 (not (org-entry-is-done-p))))
16893 (defun org-get-wdays (ts &optional delay zero-delay)
16894 "Get the deadline lead time appropriate for timestring TS.
16895 When DELAY is non-nil, get the delay time for scheduled items
16896 instead of the deadline lead time. When ZERO-DELAY is non-nil
16897 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16898 don't try to find the delay cookie in the scheduled timestamp."
16899 (let ((tv (if delay org-scheduled-delay-days
16900 org-deadline-warning-days)))
16901 (cond
16902 ((or (and delay (< tv 0))
16903 (and delay zero-delay (<= tv 0))
16904 (and (not delay) (<= tv 0)))
16905 ;; Enforce this value no matter what
16906 (- tv))
16907 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16908 ;; lead time is specified.
16909 (floor (* (string-to-number (match-string 1 ts))
16910 (cdr (assoc (match-string 2 ts)
16911 '(("d" . 1) ("w" . 7)
16912 ("m" . 30.4) ("y" . 365.25)
16913 ("h" . 0.041667)))))))
16914 ;; go for the default.
16915 (t tv))))
16917 (defun org-calendar-select-mouse (ev)
16918 "Return to `org-read-date' with the date currently selected.
16919 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16920 (interactive "e")
16921 (mouse-set-point ev)
16922 (when (calendar-cursor-to-date)
16923 (let* ((date (calendar-cursor-to-date))
16924 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16925 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16926 (if (active-minibuffer-window) (exit-minibuffer))))
16928 (defun org-check-deadlines (ndays)
16929 "Check if there are any deadlines due or past due.
16930 A deadline is considered due if it happens within `org-deadline-warning-days'
16931 days from today's date. If the deadline appears in an entry marked DONE,
16932 it is not shown. The prefix arg NDAYS can be used to test that many
16933 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16934 (interactive "P")
16935 (let* ((org-warn-days
16936 (cond
16937 ((equal ndays '(4)) 100000)
16938 (ndays (prefix-numeric-value ndays))
16939 (t (abs org-deadline-warning-days))))
16940 (case-fold-search nil)
16941 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16942 (callback
16943 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16945 (message "%d deadlines past-due or due within %d days"
16946 (org-occur regexp nil callback)
16947 org-warn-days)))
16949 (defsubst org-re-timestamp (type)
16950 "Return a regexp for timestamp TYPE.
16951 Allowed values for TYPE are:
16953 all: all timestamps
16954 active: only active timestamps (<...>)
16955 inactive: only inactive timestamps ([...])
16956 scheduled: only scheduled timestamps
16957 deadline: only deadline timestamps
16958 closed: only closed time-stamps
16960 When TYPE is nil, fall back on returning a regexp that matches
16961 both scheduled and deadline timestamps."
16962 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16963 ((eq type 'active) org-ts-regexp)
16964 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16965 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16966 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16967 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16968 ((eq type 'scheduled-or-deadline)
16969 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16971 (defun org-check-before-date (date)
16972 "Check if there are deadlines or scheduled entries before DATE."
16973 (interactive (list (org-read-date)))
16974 (let ((case-fold-search nil)
16975 (regexp (org-re-timestamp org-ts-type))
16976 (callback
16977 (lambda () (time-less-p
16978 (org-time-string-to-time (match-string 1))
16979 (org-time-string-to-time date)))))
16980 (message "%d entries before %s"
16981 (org-occur regexp nil callback) date)))
16983 (defun org-check-after-date (date)
16984 "Check if there are deadlines or scheduled entries after DATE."
16985 (interactive (list (org-read-date)))
16986 (let ((case-fold-search nil)
16987 (regexp (org-re-timestamp org-ts-type))
16988 (callback
16989 (lambda () (not
16990 (time-less-p
16991 (org-time-string-to-time (match-string 1))
16992 (org-time-string-to-time date))))))
16993 (message "%d entries after %s"
16994 (org-occur regexp nil callback) date)))
16996 (defun org-check-dates-range (start-date end-date)
16997 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16998 (interactive (list (org-read-date nil nil nil "Range starts")
16999 (org-read-date nil nil nil "Range end")))
17000 (let ((case-fold-search nil)
17001 (regexp (org-re-timestamp org-ts-type))
17002 (callback
17003 (lambda ()
17004 (let ((match (match-string 1)))
17005 (and
17006 (not (time-less-p
17007 (org-time-string-to-time match)
17008 (org-time-string-to-time start-date)))
17009 (time-less-p
17010 (org-time-string-to-time match)
17011 (org-time-string-to-time end-date)))))))
17012 (message "%d entries between %s and %s"
17013 (org-occur regexp nil callback) start-date end-date)))
17015 (defun org-evaluate-time-range (&optional to-buffer)
17016 "Evaluate a time range by computing the difference between start and end.
17017 Normally the result is just printed in the echo area, but with prefix arg
17018 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17019 If the time range is actually in a table, the result is inserted into the
17020 next column.
17021 For time difference computation, a year is assumed to be exactly 365
17022 days in order to avoid rounding problems."
17023 (interactive "P")
17025 (org-clock-update-time-maybe)
17026 (save-excursion
17027 (unless (org-at-date-range-p t)
17028 (goto-char (point-at-bol))
17029 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17030 (if (not (org-at-date-range-p t))
17031 (user-error "Not at a time-stamp range, and none found in current line")))
17032 (let* ((ts1 (match-string 1))
17033 (ts2 (match-string 2))
17034 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17035 (match-end (match-end 0))
17036 (time1 (org-time-string-to-time ts1))
17037 (time2 (org-time-string-to-time ts2))
17038 (t1 (org-float-time time1))
17039 (t2 (org-float-time time2))
17040 (diff (abs (- t2 t1)))
17041 (negative (< (- t2 t1) 0))
17042 ;; (ys (floor (* 365 24 60 60)))
17043 (ds (* 24 60 60))
17044 (hs (* 60 60))
17045 (fy "%dy %dd %02d:%02d")
17046 (fy1 "%dy %dd")
17047 (fd "%dd %02d:%02d")
17048 (fd1 "%dd")
17049 (fh "%02d:%02d")
17050 y d h m align)
17051 (if havetime
17052 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17054 d (floor (/ diff ds)) diff (mod diff ds)
17055 h (floor (/ diff hs)) diff (mod diff hs)
17056 m (floor (/ diff 60)))
17057 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17059 d (floor (+ (/ diff ds) 0.5))
17060 h 0 m 0))
17061 (if (not to-buffer)
17062 (message "%s" (org-make-tdiff-string y d h m))
17063 (if (org-at-table-p)
17064 (progn
17065 (goto-char match-end)
17066 (setq align t)
17067 (and (looking-at " *|") (goto-char (match-end 0))))
17068 (goto-char match-end))
17069 (if (looking-at
17070 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17071 (replace-match ""))
17072 (if negative (insert " -"))
17073 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17074 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17075 (insert " " (format fh h m))))
17076 (if align (org-table-align))
17077 (message "Time difference inserted")))))
17079 (defun org-make-tdiff-string (y d h m)
17080 (let ((fmt "")
17081 (l nil))
17082 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17083 l (push y l)))
17084 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17085 l (push d l)))
17086 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17087 l (push h l)))
17088 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17089 l (push m l)))
17090 (apply 'format fmt (nreverse l))))
17092 (defun org-time-string-to-time (s &optional buffer pos)
17093 "Convert a timestamp string into internal time."
17094 (condition-case errdata
17095 (apply 'encode-time (org-parse-time-string s))
17096 (error (error "Bad timestamp `%s'%s\nError was: %s"
17097 s (if (not (and buffer pos))
17099 (format " at %d in buffer `%s'" pos buffer))
17100 (cdr errdata)))))
17102 (defun org-time-string-to-seconds (s)
17103 "Convert a timestamp string to a number of seconds."
17104 (org-float-time (org-time-string-to-time s)))
17106 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17107 "Convert a time stamp to an absolute day number.
17108 If there is a specifier for a cyclic time stamp, get the closest
17109 date to DAYNR.
17110 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17111 The variable `date' is bound by the calendar when this is called."
17112 (cond
17113 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17114 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17115 daynr
17116 (+ daynr 1000)))
17117 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17118 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17119 (time-to-days (current-time))) (match-string 0 s)
17120 prefer show-all))
17121 (t (time-to-days
17122 (condition-case errdata
17123 (apply 'encode-time (org-parse-time-string s))
17124 (error (error "Bad timestamp `%s'%s\nError was: %s"
17125 s (if (not (and buffer pos))
17127 (format " at %d in buffer `%s'" pos buffer))
17128 (cdr errdata))))))))
17130 (defun org-days-to-iso-week (days)
17131 "Return the iso week number."
17132 (require 'cal-iso)
17133 (car (calendar-iso-from-absolute days)))
17135 (defun org-small-year-to-year (year)
17136 "Convert 2-digit years into 4-digit years.
17137 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17138 The year 2000 cannot be abbreviated. Any year larger than 99
17139 is returned unchanged."
17140 (if (< year 38)
17141 (setq year (+ 2000 year))
17142 (if (< year 100)
17143 (setq year (+ 1900 year))))
17144 year)
17146 (defun org-time-from-absolute (d)
17147 "Return the time corresponding to date D.
17148 D may be an absolute day number, or a calendar-type list (month day year)."
17149 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17150 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17152 (defun org-calendar-holiday ()
17153 "List of holidays, for Diary display in Org-mode."
17154 (require 'holidays)
17155 (let ((hl (funcall
17156 (if (fboundp 'calendar-check-holidays)
17157 'calendar-check-holidays 'check-calendar-holidays) date)))
17158 (if hl (mapconcat 'identity hl "; "))))
17160 (defun org-diary-sexp-entry (sexp entry date)
17161 "Process a SEXP diary ENTRY for DATE."
17162 (require 'diary-lib)
17163 (let ((result (if calendar-debug-sexp
17164 (let ((stack-trace-on-error t))
17165 (eval (car (read-from-string sexp))))
17166 (condition-case nil
17167 (eval (car (read-from-string sexp)))
17168 (error
17169 (beep)
17170 (message "Bad sexp at line %d in %s: %s"
17171 (org-current-line)
17172 (buffer-file-name) sexp)
17173 (sleep-for 2))))))
17174 (cond ((stringp result) (split-string result "; "))
17175 ((and (consp result)
17176 (not (consp (cdr result)))
17177 (stringp (cdr result))) (cdr result))
17178 ((and (consp result)
17179 (stringp (car result))) result)
17180 (result entry))))
17182 (defun org-diary-to-ical-string (frombuf)
17183 "Get iCalendar entries from diary entries in buffer FROMBUF.
17184 This uses the icalendar.el library."
17185 (let* ((tmpdir (if (featurep 'xemacs)
17186 (temp-directory)
17187 temporary-file-directory))
17188 (tmpfile (make-temp-name
17189 (expand-file-name "orgics" tmpdir)))
17190 buf rtn b e)
17191 (with-current-buffer frombuf
17192 (icalendar-export-region (point-min) (point-max) tmpfile)
17193 (setq buf (find-buffer-visiting tmpfile))
17194 (set-buffer buf)
17195 (goto-char (point-min))
17196 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17197 (setq b (match-beginning 0)))
17198 (goto-char (point-max))
17199 (if (re-search-backward "^END:VEVENT" nil t)
17200 (setq e (match-end 0)))
17201 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17202 (kill-buffer buf)
17203 (delete-file tmpfile)
17204 rtn))
17206 (defun org-closest-date (start current change prefer show-all)
17207 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17208 When PREFER is `past', return a date that is either CURRENT or past.
17209 When PREFER is `future', return a date that is either CURRENT or future.
17210 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17211 ;; Make the proper lists from the dates
17212 (catch 'exit
17213 (let ((a1 '(("h" . hour)
17214 ("d" . day)
17215 ("w" . week)
17216 ("m" . month)
17217 ("y" . year)))
17218 (shour (nth 2 (org-parse-time-string start)))
17219 dn dw sday cday n1 n2 n0
17220 d m y y1 y2 date1 date2 nmonths nm ny m2)
17222 (setq start (org-date-to-gregorian start)
17223 current (org-date-to-gregorian
17224 (if show-all
17225 current
17226 (time-to-days (current-time))))
17227 sday (calendar-absolute-from-gregorian start)
17228 cday (calendar-absolute-from-gregorian current))
17230 (if (<= cday sday) (throw 'exit sday))
17232 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17233 (setq dn (string-to-number (match-string 1 change))
17234 dw (cdr (assoc (match-string 2 change) a1)))
17235 (user-error "Invalid change specifier: %s" change))
17236 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17237 (cond
17238 ((eq dw 'hour)
17239 (let ((missing-hours
17240 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17241 dn)))
17242 (setq n1 (if (zerop missing-hours) cday
17243 (- cday (1+ (floor (/ missing-hours 24)))))
17244 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17245 ((eq dw 'day)
17246 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17247 n2 (+ n1 dn)))
17248 ((eq dw 'year)
17249 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17250 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17251 (setq date1 (list m d y1)
17252 n1 (calendar-absolute-from-gregorian date1)
17253 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17254 n2 (calendar-absolute-from-gregorian date2)))
17255 ((eq dw 'month)
17256 ;; approx number of month between the two dates
17257 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17258 ;; How often does dn fit in there?
17259 (setq d (nth 1 start) m (car start) y (nth 2 start)
17260 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17261 m (+ m nm)
17262 ny (floor (/ m 12))
17263 y (+ y ny)
17264 m (- m (* ny 12)))
17265 (while (> m 12) (setq m (- m 12) y (1+ y)))
17266 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17267 (setq m2 (+ m dn) y2 y)
17268 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17269 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17270 (while (<= n2 cday)
17271 (setq n1 n2 m m2 y y2)
17272 (setq m2 (+ m dn) y2 y)
17273 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17274 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17275 ;; Make sure n1 is the earlier date
17276 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17277 (if show-all
17278 (cond
17279 ((eq prefer 'past) (if (= cday n2) n2 n1))
17280 ((eq prefer 'future) (if (= cday n1) n1 n2))
17281 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17282 (cond
17283 ((eq prefer 'past) (if (= cday n2) n2 n1))
17284 ((eq prefer 'future) (if (= cday n1) n1 n2))
17285 (t (if (= cday n1) n1 n2)))))))
17287 (defun org-date-to-gregorian (date)
17288 "Turn any specification of DATE into a Gregorian date for the calendar."
17289 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17290 ((and (listp date) (= (length date) 3)) date)
17291 ((stringp date)
17292 (setq date (org-parse-time-string date))
17293 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17294 ((listp date)
17295 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17297 (defun org-parse-time-string (s &optional nodefault)
17298 "Parse the standard Org-mode time string.
17299 This should be a lot faster than the normal `parse-time-string'.
17300 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17301 hour and minute fields will be nil if not given."
17302 (cond ((string-match org-ts-regexp0 s)
17303 (list 0
17304 (if (or (match-beginning 8) (not nodefault))
17305 (string-to-number (or (match-string 8 s) "0")))
17306 (if (or (match-beginning 7) (not nodefault))
17307 (string-to-number (or (match-string 7 s) "0")))
17308 (string-to-number (match-string 4 s))
17309 (string-to-number (match-string 3 s))
17310 (string-to-number (match-string 2 s))
17311 nil nil nil))
17312 ((string-match "^<[^>]+>$" s)
17313 (decode-time (seconds-to-time (org-matcher-time s))))
17314 (t (error "Not a standard Org-mode time string: %s" s))))
17316 (defun org-timestamp-up (&optional arg)
17317 "Increase the date item at the cursor by one.
17318 If the cursor is on the year, change the year. If it is on the month,
17319 the day or the time, change that.
17320 With prefix ARG, change by that many units."
17321 (interactive "p")
17322 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17324 (defun org-timestamp-down (&optional arg)
17325 "Decrease the date item at the cursor by one.
17326 If the cursor is on the year, change the year. If it is on the month,
17327 the day or the time, change that.
17328 With prefix ARG, change by that many units."
17329 (interactive "p")
17330 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17332 (defun org-timestamp-up-day (&optional arg)
17333 "Increase the date in the time stamp by one day.
17334 With prefix ARG, change that many days."
17335 (interactive "p")
17336 (if (and (not (org-at-timestamp-p t))
17337 (org-at-heading-p))
17338 (org-todo 'up)
17339 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17341 (defun org-timestamp-down-day (&optional arg)
17342 "Decrease the date in the time stamp by one day.
17343 With prefix ARG, change that many days."
17344 (interactive "p")
17345 (if (and (not (org-at-timestamp-p t))
17346 (org-at-heading-p))
17347 (org-todo 'down)
17348 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17350 (defun org-at-timestamp-p (&optional inactive-ok)
17351 "Determine if the cursor is in or at a timestamp."
17352 (interactive)
17353 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17354 (pos (point))
17355 (ans (or (looking-at tsr)
17356 (save-excursion
17357 (skip-chars-backward "^[<\n\r\t")
17358 (if (> (point) (point-min)) (backward-char 1))
17359 (and (looking-at tsr)
17360 (> (- (match-end 0) pos) -1))))))
17361 (and ans
17362 (boundp 'org-ts-what)
17363 (setq org-ts-what
17364 (cond
17365 ((= pos (match-beginning 0)) 'bracket)
17366 ;; Point is considered to be "on the bracket" whether
17367 ;; it's really on it or right after it.
17368 ((= pos (1- (match-end 0))) 'bracket)
17369 ((= pos (match-end 0)) 'after)
17370 ((org-pos-in-match-range pos 2) 'year)
17371 ((org-pos-in-match-range pos 3) 'month)
17372 ((org-pos-in-match-range pos 7) 'hour)
17373 ((org-pos-in-match-range pos 8) 'minute)
17374 ((or (org-pos-in-match-range pos 4)
17375 (org-pos-in-match-range pos 5)) 'day)
17376 ((and (> pos (or (match-end 8) (match-end 5)))
17377 (< pos (match-end 0)))
17378 (- pos (or (match-end 8) (match-end 5))))
17379 (t 'day))))
17380 ans))
17382 (defun org-toggle-timestamp-type ()
17383 "Toggle the type (<active> or [inactive]) of a time stamp."
17384 (interactive)
17385 (when (org-at-timestamp-p t)
17386 (let ((beg (match-beginning 0)) (end (match-end 0))
17387 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17388 (save-excursion
17389 (goto-char beg)
17390 (while (re-search-forward "[][<>]" end t)
17391 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17392 t t)))
17393 (message "Timestamp is now %sactive"
17394 (if (equal (char-after beg) ?<) "" "in")))))
17396 (defun org-at-clock-log-p nil
17397 "Is the cursor on the clock log line?"
17398 (save-excursion
17399 (move-beginning-of-line 1)
17400 (looking-at "^[ \t]*CLOCK:")))
17402 (defvar org-clock-history) ; defined in org-clock.el
17403 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17404 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17405 "Change the date in the time stamp at point.
17406 The date will be changed by N times WHAT. WHAT can be `day', `month',
17407 `year', `minute', `second'. If WHAT is not given, the cursor position
17408 in the timestamp determines what will be changed.
17409 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17410 (let ((origin (point)) origin-cat
17411 with-hm inactive
17412 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17413 org-ts-what
17414 extra rem
17415 ts time time0 fixnext clrgx)
17416 (if (not (org-at-timestamp-p t))
17417 (user-error "Not at a timestamp"))
17418 (if (and (not what) (eq org-ts-what 'bracket))
17419 (org-toggle-timestamp-type)
17420 ;; Point isn't on brackets. Remember the part of the time-stamp
17421 ;; the point was in. Indeed, size of time-stamps may change,
17422 ;; but point must be kept in the same category nonetheless.
17423 (setq origin-cat org-ts-what)
17424 (if (and (not what) (not (eq org-ts-what 'day))
17425 org-display-custom-times
17426 (get-text-property (point) 'display)
17427 (not (get-text-property (1- (point)) 'display)))
17428 (setq org-ts-what 'day))
17429 (setq org-ts-what (or what org-ts-what)
17430 inactive (= (char-after (match-beginning 0)) ?\[)
17431 ts (match-string 0))
17432 (replace-match "")
17433 (when (string-match
17434 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17436 (setq extra (match-string 1 ts))
17437 (if suppress-tmp-delay
17438 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17439 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17440 (setq with-hm t))
17441 (setq time0 (org-parse-time-string ts))
17442 (when (and updown
17443 (eq org-ts-what 'minute)
17444 (not current-prefix-arg))
17445 ;; This looks like s-up and s-down. Change by one rounding step.
17446 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17447 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17448 (setcar (cdr time0) (+ (nth 1 time0)
17449 (if (> n 0) (- rem) (- dm rem))))))
17450 (setq time
17451 (encode-time (or (car time0) 0)
17452 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17453 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17454 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17455 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17456 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17457 (nthcdr 6 time0)))
17458 (when (and (member org-ts-what '(hour minute))
17459 extra
17460 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17461 (setq extra (org-modify-ts-extra
17462 extra
17463 (if (eq org-ts-what 'hour) 2 5)
17464 n dm)))
17465 (when (integerp org-ts-what)
17466 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17467 (if (eq what 'calendar)
17468 (let ((cal-date (org-get-date-from-calendar)))
17469 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17470 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17471 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17472 (setcar time0 (or (car time0) 0))
17473 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17474 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17475 (setq time (apply 'encode-time time0))))
17476 ;; Insert the new time-stamp, and ensure point stays in the same
17477 ;; category as before (i.e. not after the last position in that
17478 ;; category).
17479 (let ((pos (point)))
17480 ;; Stay before inserted string. `save-excursion' is of no use.
17481 (setq org-last-changed-timestamp
17482 (org-insert-time-stamp time with-hm inactive nil nil extra))
17483 (goto-char pos))
17484 (save-match-data
17485 (looking-at org-ts-regexp3)
17486 (goto-char (cond
17487 ;; `day' category ends before `hour' if any, or at
17488 ;; the end of the day name.
17489 ((eq origin-cat 'day)
17490 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17491 ((eq origin-cat 'hour) (min (match-end 7) origin))
17492 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17493 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17494 ;; `year' and `month' have both fixed size: point
17495 ;; couldn't have moved into another part.
17496 (t origin))))
17497 ;; Update clock if on a CLOCK line.
17498 (org-clock-update-time-maybe)
17499 ;; Maybe adjust the closest clock in `org-clock-history'
17500 (when org-clock-adjust-closest
17501 (if (not (and (org-at-clock-log-p)
17502 (< 1 (length (delq nil (mapcar 'marker-position
17503 org-clock-history))))))
17504 (message "No clock to adjust")
17505 (cond ((save-excursion ; fix previous clock?
17506 (re-search-backward org-ts-regexp0 nil t)
17507 (org-looking-back (concat org-clock-string " \\[")))
17508 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17509 ((save-excursion ; fix next clock?
17510 (re-search-backward org-ts-regexp0 nil t)
17511 (looking-at (concat org-ts-regexp0 "\\] =>")))
17512 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17513 (save-window-excursion
17514 ;; Find closest clock to point, adjust the previous/next one in history
17515 (let* ((p (save-excursion (org-back-to-heading t)))
17516 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17517 (clfixnth
17518 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17519 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17520 (if (not clfixpos)
17521 (message "No clock to adjust")
17522 (save-excursion
17523 (org-goto-marker-or-bmk clfixpos)
17524 (org-show-subtree)
17525 (when (re-search-forward clrgx nil t)
17526 (goto-char (match-beginning 1))
17527 (let (org-clock-adjust-closest)
17528 (org-timestamp-change n org-ts-what updown))
17529 (message "Clock adjusted in %s for heading: %s"
17530 (file-name-nondirectory (buffer-file-name))
17531 (org-get-heading t t)))))))))
17532 ;; Try to recenter the calendar window, if any.
17533 (if (and org-calendar-follow-timestamp-change
17534 (get-buffer-window "*Calendar*" t)
17535 (memq org-ts-what '(day month year)))
17536 (org-recenter-calendar (time-to-days time))))))
17538 (defun org-modify-ts-extra (s pos n dm)
17539 "Change the different parts of the lead-time and repeat fields in timestamp."
17540 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17541 ng h m new rem)
17542 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17543 (cond
17544 ((or (org-pos-in-match-range pos 2)
17545 (org-pos-in-match-range pos 3))
17546 (setq m (string-to-number (match-string 3 s))
17547 h (string-to-number (match-string 2 s)))
17548 (if (org-pos-in-match-range pos 2)
17549 (setq h (+ h n))
17550 (setq n (* dm (org-no-warnings (signum n))))
17551 (when (not (= 0 (setq rem (% m dm))))
17552 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17553 (setq m (+ m n)))
17554 (if (< m 0) (setq m (+ m 60) h (1- h)))
17555 (if (> m 59) (setq m (- m 60) h (1+ h)))
17556 (setq h (min 24 (max 0 h)))
17557 (setq ng 1 new (format "-%02d:%02d" h m)))
17558 ((org-pos-in-match-range pos 6)
17559 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17560 ((org-pos-in-match-range pos 5)
17561 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17563 ((org-pos-in-match-range pos 9)
17564 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17565 ((org-pos-in-match-range pos 8)
17566 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17568 (when ng
17569 (setq s (concat
17570 (substring s 0 (match-beginning ng))
17572 (substring s (match-end ng))))))
17575 (defun org-recenter-calendar (date)
17576 "If the calendar is visible, recenter it to DATE."
17577 (let ((cwin (get-buffer-window "*Calendar*" t)))
17578 (when cwin
17579 (let ((calendar-move-hook nil))
17580 (with-selected-window cwin
17581 (calendar-goto-date (if (listp date) date
17582 (calendar-gregorian-from-absolute date))))))))
17584 (defun org-goto-calendar (&optional arg)
17585 "Go to the Emacs calendar at the current date.
17586 If there is a time stamp in the current line, go to that date.
17587 A prefix ARG can be used to force the current date."
17588 (interactive "P")
17589 (let ((tsr org-ts-regexp) diff
17590 (calendar-move-hook nil)
17591 (calendar-view-holidays-initially-flag nil)
17592 (calendar-view-diary-initially-flag nil))
17593 (if (or (org-at-timestamp-p)
17594 (save-excursion
17595 (beginning-of-line 1)
17596 (looking-at (concat ".*" tsr))))
17597 (let ((d1 (time-to-days (current-time)))
17598 (d2 (time-to-days
17599 (org-time-string-to-time (match-string 1)))))
17600 (setq diff (- d2 d1))))
17601 (calendar)
17602 (calendar-goto-today)
17603 (if (and diff (not arg)) (calendar-forward-day diff))))
17605 (defun org-get-date-from-calendar ()
17606 "Return a list (month day year) of date at point in calendar."
17607 (with-current-buffer "*Calendar*"
17608 (save-match-data
17609 (calendar-cursor-to-date))))
17611 (defun org-date-from-calendar ()
17612 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17613 If there is already a time stamp at the cursor position, update it."
17614 (interactive)
17615 (if (org-at-timestamp-p t)
17616 (org-timestamp-change 0 'calendar)
17617 (let ((cal-date (org-get-date-from-calendar)))
17618 (org-insert-time-stamp
17619 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17621 (defcustom org-effort-durations
17622 `(("h" . 60)
17623 ("d" . ,(* 60 8))
17624 ("w" . ,(* 60 8 5))
17625 ("m" . ,(* 60 8 5 4))
17626 ("y" . ,(* 60 8 5 40)))
17627 "Conversion factor to minutes for an effort modifier.
17629 Each entry has the form (MODIFIER . MINUTES).
17631 In an effort string, a number followed by MODIFIER is multiplied
17632 by the specified number of MINUTES to obtain an effort in
17633 minutes.
17635 For example, if the value of this variable is ((\"hours\" . 60)), then an
17636 effort string \"2hours\" is equivalent to 120 minutes."
17637 :group 'org-agenda
17638 :version "24.1"
17639 :type '(alist :key-type (string :tag "Modifier")
17640 :value-type (number :tag "Minutes")))
17642 (defun org-minutes-to-clocksum-string (m)
17643 "Format number of minutes as a clocksum string.
17644 The format is determined by `org-time-clocksum-format',
17645 `org-time-clocksum-use-fractional' and
17646 `org-time-clocksum-fractional-format' and
17647 `org-time-clocksum-use-effort-durations'."
17648 (let ((clocksum "")
17649 (m (round m)) ; Don't allow fractions of minutes
17650 h d w mo y fmt n)
17651 (setq h (if org-time-clocksum-use-effort-durations
17652 (cdr (assoc "h" org-effort-durations)) 60)
17653 d (if org-time-clocksum-use-effort-durations
17654 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17655 w (if org-time-clocksum-use-effort-durations
17656 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17657 mo (if org-time-clocksum-use-effort-durations
17658 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17659 y (if org-time-clocksum-use-effort-durations
17660 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17661 ;; fractional format
17662 (if org-time-clocksum-use-fractional
17663 (cond
17664 ;; single format string
17665 ((stringp org-time-clocksum-fractional-format)
17666 (format org-time-clocksum-fractional-format (/ m (float h))))
17667 ;; choice of fractional formats for different time units
17668 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17669 (> (/ (truncate m) (* y d h)) 0))
17670 (format fmt (/ m (* y d (float h)))))
17671 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17672 (> (/ (truncate m) (* mo d h)) 0))
17673 (format fmt (/ m (* mo d (float h)))))
17674 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17675 (> (/ (truncate m) (* w d h)) 0))
17676 (format fmt (/ m (* w d (float h)))))
17677 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17678 (> (/ (truncate m) (* d h)) 0))
17679 (format fmt (/ m (* d (float h)))))
17680 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17681 (> (/ (truncate m) h) 0))
17682 (format fmt (/ m (float h))))
17683 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17684 (format fmt m))
17685 ;; fall back to smallest time unit with a format
17686 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17687 (format fmt (/ m (float h))))
17688 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17689 (format fmt (/ m (* d (float h)))))
17690 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17691 (format fmt (/ m (* w d (float h)))))
17692 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17693 (format fmt (/ m (* mo d (float h)))))
17694 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17695 (format fmt (/ m (* y d (float h))))))
17696 ;; standard (non-fractional) format, with single format string
17697 (if (stringp org-time-clocksum-format)
17698 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17699 ;; separate formats components
17700 (and (setq fmt (plist-get org-time-clocksum-format :years))
17701 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17702 (plist-get org-time-clocksum-format :require-years))
17703 (setq clocksum (concat clocksum (format fmt n))
17704 m (- m (* n y d h))))
17705 (and (setq fmt (plist-get org-time-clocksum-format :months))
17706 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17707 (plist-get org-time-clocksum-format :require-months))
17708 (setq clocksum (concat clocksum (format fmt n))
17709 m (- m (* n mo d h))))
17710 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17711 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17712 (plist-get org-time-clocksum-format :require-weeks))
17713 (setq clocksum (concat clocksum (format fmt n))
17714 m (- m (* n w d h))))
17715 (and (setq fmt (plist-get org-time-clocksum-format :days))
17716 (or (> (setq n (/ (truncate m) (* d h))) 0)
17717 (plist-get org-time-clocksum-format :require-days))
17718 (setq clocksum (concat clocksum (format fmt n))
17719 m (- m (* n d h))))
17720 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17721 (or (> (setq n (/ (truncate m) h)) 0)
17722 (plist-get org-time-clocksum-format :require-hours))
17723 (setq clocksum (concat clocksum (format fmt n))
17724 m (- m (* n h))))
17725 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17726 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17727 (setq clocksum (concat clocksum (format fmt m))))
17728 ;; return formatted time duration
17729 clocksum))))
17731 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17732 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17733 "Org mode version 8.0")
17735 (defun org-hours-to-clocksum-string (n)
17736 (org-minutes-to-clocksum-string (* n 60)))
17738 (defun org-hh:mm-string-to-minutes (s)
17739 "Convert a string H:MM to a number of minutes.
17740 If the string is just a number, interpret it as minutes.
17741 In fact, the first hh:mm or number in the string will be taken,
17742 there can be extra stuff in the string.
17743 If no number is found, the return value is 0."
17744 (cond
17745 ((integerp s) s)
17746 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17747 (+ (* (string-to-number (match-string 1 s)) 60)
17748 (string-to-number (match-string 2 s))))
17749 ((string-match "\\([0-9]+\\)" s)
17750 (string-to-number (match-string 1 s)))
17751 (t 0)))
17753 (defcustom org-image-actual-width t
17754 "Should we use the actual width of images when inlining them?
17756 When set to `t', always use the image width.
17758 When set to a number, use imagemagick (when available) to set
17759 the image's width to this value.
17761 When set to a number in a list, try to get the width from any
17762 #+ATTR.* keyword if it matches a width specification like
17764 #+ATTR_HTML: :width 300px
17766 and fall back on that number if none is found.
17768 When set to nil, try to get the width from an #+ATTR.* keyword
17769 and fall back on the original width if none is found.
17771 This requires Emacs >= 24.1, build with imagemagick support."
17772 :group 'org-appearance
17773 :version "24.4"
17774 :package-version '(Org . "8.0")
17775 :type '(choice
17776 (const :tag "Use the image width" t)
17777 (integer :tag "Use a number of pixels")
17778 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17779 (const :tag "Use #+ATTR* or don't resize" nil)))
17781 (defcustom org-agenda-inhibit-startup nil
17782 "Inhibit startup when preparing agenda buffers.
17783 When this variable is `t' (the default), the initialization of
17784 the Org agenda buffers is inhibited: e.g. the visibility state
17785 is not set, the tables are not re-aligned, etc."
17786 :type 'boolean
17787 :version "24.3"
17788 :group 'org-agenda)
17790 (defcustom org-agenda-ignore-drawer-properties nil
17791 "Avoid updating text properties when building the agenda.
17792 Properties are used to prepare buffers for effort estimates, appointments,
17793 and subtree-local categories.
17794 If you don't use these in the agenda, you can add them to this list and
17795 agenda building will be a bit faster.
17796 The value is a list, with zero or more of the symbols `effort', `appt',
17797 or `category'."
17798 :type '(set :greedy t
17799 (const effort)
17800 (const appt)
17801 (const category))
17802 :version "24.3"
17803 :group 'org-agenda)
17805 (defun org-duration-string-to-minutes (s &optional output-to-string)
17806 "Convert a duration string S to minutes.
17808 A bare number is interpreted as minutes, modifiers can be set by
17809 customizing `org-effort-durations' (which see).
17811 Entries containing a colon are interpreted as H:MM by
17812 `org-hh:mm-string-to-minutes'."
17813 (let ((result 0)
17814 (re (concat "\\([0-9.]+\\) *\\("
17815 (regexp-opt (mapcar 'car org-effort-durations))
17816 "\\)")))
17817 (while (string-match re s)
17818 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17819 (string-to-number (match-string 1 s))))
17820 (setq s (replace-match "" nil t s)))
17821 (setq result (floor result))
17822 (incf result (org-hh:mm-string-to-minutes s))
17823 (if output-to-string (number-to-string result) result)))
17825 ;;;; Files
17827 (defun org-save-all-org-buffers ()
17828 "Save all Org-mode buffers without user confirmation."
17829 (interactive)
17830 (message "Saving all Org-mode buffers...")
17831 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17832 (when (featurep 'org-id) (org-id-locations-save))
17833 (message "Saving all Org-mode buffers... done"))
17835 (defun org-revert-all-org-buffers ()
17836 "Revert all Org-mode buffers.
17837 Prompt for confirmation when there are unsaved changes.
17838 Be sure you know what you are doing before letting this function
17839 overwrite your changes.
17841 This function is useful in a setup where one tracks org files
17842 with a version control system, to revert on one machine after pulling
17843 changes from another. I believe the procedure must be like this:
17845 1. M-x org-save-all-org-buffers
17846 2. Pull changes from the other machine, resolve conflicts
17847 3. M-x org-revert-all-org-buffers"
17848 (interactive)
17849 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17850 (user-error "Abort"))
17851 (save-excursion
17852 (save-window-excursion
17853 (mapc
17854 (lambda (b)
17855 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17856 (with-current-buffer b buffer-file-name))
17857 (org-pop-to-buffer-same-window b)
17858 (revert-buffer t 'no-confirm)))
17859 (buffer-list))
17860 (when (and (featurep 'org-id) org-id-track-globally)
17861 (org-id-locations-load)))))
17863 ;;;; Agenda files
17865 ;;;###autoload
17866 (defun org-switchb (&optional arg)
17867 "Switch between Org buffers.
17868 With one prefix argument, restrict available buffers to files.
17869 With two prefix arguments, restrict available buffers to agenda files.
17871 Defaults to `iswitchb' for buffer name completion.
17872 Set `org-completion-use-ido' to make it use ido instead."
17873 (interactive "P")
17874 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17875 ((equal arg '(16)) (org-buffer-list 'agenda))
17876 (t (org-buffer-list))))
17877 (org-completion-use-iswitchb org-completion-use-iswitchb)
17878 (org-completion-use-ido org-completion-use-ido))
17879 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17880 (setq org-completion-use-iswitchb t))
17881 (org-pop-to-buffer-same-window
17882 (org-icompleting-read "Org buffer: "
17883 (mapcar 'list (mapcar 'buffer-name blist))
17884 nil t))))
17886 ;;; Define some older names previously used for this functionality
17887 ;;;###autoload
17888 (defalias 'org-ido-switchb 'org-switchb)
17889 ;;;###autoload
17890 (defalias 'org-iswitchb 'org-switchb)
17892 (defun org-buffer-list (&optional predicate exclude-tmp)
17893 "Return a list of Org buffers.
17894 PREDICATE can be `export', `files' or `agenda'.
17896 export restrict the list to Export buffers.
17897 files restrict the list to buffers visiting Org files.
17898 agenda restrict the list to buffers visiting agenda files.
17900 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17901 (let* ((bfn nil)
17902 (agenda-files (and (eq predicate 'agenda)
17903 (mapcar 'file-truename (org-agenda-files t))))
17904 (filter
17905 (cond
17906 ((eq predicate 'files)
17907 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17908 ((eq predicate 'export)
17909 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17910 ((eq predicate 'agenda)
17911 (lambda (b)
17912 (with-current-buffer b
17913 (and (derived-mode-p 'org-mode)
17914 (setq bfn (buffer-file-name b))
17915 (member (file-truename bfn) agenda-files)))))
17916 (t (lambda (b) (with-current-buffer b
17917 (or (derived-mode-p 'org-mode)
17918 (string-match "\*Org .*Export"
17919 (buffer-name b)))))))))
17920 (delq nil
17921 (mapcar
17922 (lambda(b)
17923 (if (and (funcall filter b)
17924 (or (not exclude-tmp)
17925 (not (string-match "tmp" (buffer-name b)))))
17927 nil))
17928 (buffer-list)))))
17930 (defun org-agenda-files (&optional unrestricted archives)
17931 "Get the list of agenda files.
17932 Optional UNRESTRICTED means return the full list even if a restriction
17933 is currently in place.
17934 When ARCHIVES is t, include all archive files that are really being
17935 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17936 `org-agenda-archives-mode' is t."
17937 (let ((files
17938 (cond
17939 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17940 ((stringp org-agenda-files) (org-read-agenda-file-list))
17941 ((listp org-agenda-files) org-agenda-files)
17942 (t (error "Invalid value of `org-agenda-files'")))))
17943 (setq files (apply 'append
17944 (mapcar (lambda (f)
17945 (if (file-directory-p f)
17946 (directory-files
17947 f t org-agenda-file-regexp)
17948 (list f)))
17949 files)))
17950 (when org-agenda-skip-unavailable-files
17951 (setq files (delq nil
17952 (mapcar (function
17953 (lambda (file)
17954 (and (file-readable-p file) file)))
17955 files))))
17956 (when (or (eq archives t)
17957 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17958 (setq files (org-add-archive-files files)))
17959 files))
17961 (defun org-agenda-file-p (&optional file)
17962 "Return non-nil, if FILE is an agenda file.
17963 If FILE is omitted, use the file associated with the current
17964 buffer."
17965 (member (or file (buffer-file-name))
17966 (org-agenda-files t)))
17968 (defun org-edit-agenda-file-list ()
17969 "Edit the list of agenda files.
17970 Depending on setup, this either uses customize to edit the variable
17971 `org-agenda-files', or it visits the file that is holding the list. In the
17972 latter case, the buffer is set up in a way that saving it automatically kills
17973 the buffer and restores the previous window configuration."
17974 (interactive)
17975 (if (stringp org-agenda-files)
17976 (let ((cw (current-window-configuration)))
17977 (find-file org-agenda-files)
17978 (org-set-local 'org-window-configuration cw)
17979 (org-add-hook 'after-save-hook
17980 (lambda ()
17981 (set-window-configuration
17982 (prog1 org-window-configuration
17983 (kill-buffer (current-buffer))))
17984 (org-install-agenda-files-menu)
17985 (message "New agenda file list installed"))
17986 nil 'local)
17987 (message "%s" (substitute-command-keys
17988 "Edit list and finish with \\[save-buffer]")))
17989 (customize-variable 'org-agenda-files)))
17991 (defun org-store-new-agenda-file-list (list)
17992 "Set new value for the agenda file list and save it correctly."
17993 (if (stringp org-agenda-files)
17994 (let ((fe (org-read-agenda-file-list t)) b u)
17995 (while (setq b (find-buffer-visiting org-agenda-files))
17996 (kill-buffer b))
17997 (with-temp-file org-agenda-files
17998 (insert
17999 (mapconcat
18000 (lambda (f) ;; Keep un-expanded entries.
18001 (if (setq u (assoc f fe))
18002 (cdr u)
18004 list "\n")
18005 "\n")))
18006 (let ((org-mode-hook nil) (org-inhibit-startup t)
18007 (org-insert-mode-line-in-empty-file nil))
18008 (setq org-agenda-files list)
18009 (customize-save-variable 'org-agenda-files org-agenda-files))))
18011 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18012 "Read the list of agenda files from a file.
18013 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18014 filenames, used by `org-store-new-agenda-file-list' to write back
18015 un-expanded file names."
18016 (when (file-directory-p org-agenda-files)
18017 (error "`org-agenda-files' cannot be a single directory"))
18018 (when (stringp org-agenda-files)
18019 (with-temp-buffer
18020 (insert-file-contents org-agenda-files)
18021 (mapcar
18022 (lambda (f)
18023 (let ((e (expand-file-name (substitute-in-file-name f)
18024 org-directory)))
18025 (if pair-with-expansion
18026 (cons e f)
18027 e)))
18028 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18030 ;;;###autoload
18031 (defun org-cycle-agenda-files ()
18032 "Cycle through the files in `org-agenda-files'.
18033 If the current buffer visits an agenda file, find the next one in the list.
18034 If the current buffer does not, find the first agenda file."
18035 (interactive)
18036 (let* ((fs (org-agenda-files t))
18037 (files (append fs (list (car fs))))
18038 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18039 file)
18040 (unless files (user-error "No agenda files"))
18041 (catch 'exit
18042 (while (setq file (pop files))
18043 (if (equal (file-truename file) tcf)
18044 (when (car files)
18045 (find-file (car files))
18046 (throw 'exit t))))
18047 (find-file (car fs)))
18048 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18050 (defun org-agenda-file-to-front (&optional to-end)
18051 "Move/add the current file to the top of the agenda file list.
18052 If the file is not present in the list, it is added to the front. If it is
18053 present, it is moved there. With optional argument TO-END, add/move to the
18054 end of the list."
18055 (interactive "P")
18056 (let ((org-agenda-skip-unavailable-files nil)
18057 (file-alist (mapcar (lambda (x)
18058 (cons (file-truename x) x))
18059 (org-agenda-files t)))
18060 (ctf (file-truename
18061 (or buffer-file-name
18062 (user-error "Please save the current buffer to a file"))))
18063 x had)
18064 (setq x (assoc ctf file-alist) had x)
18066 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18067 (if to-end
18068 (setq file-alist (append (delq x file-alist) (list x)))
18069 (setq file-alist (cons x (delq x file-alist))))
18070 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18071 (org-install-agenda-files-menu)
18072 (message "File %s to %s of agenda file list"
18073 (if had "moved" "added") (if to-end "end" "front"))))
18075 (defun org-remove-file (&optional file)
18076 "Remove current file from the list of files in variable `org-agenda-files'.
18077 These are the files which are being checked for agenda entries.
18078 Optional argument FILE means use this file instead of the current."
18079 (interactive)
18080 (let* ((org-agenda-skip-unavailable-files nil)
18081 (file (or file buffer-file-name
18082 (user-error "Current buffer does not visit a file")))
18083 (true-file (file-truename file))
18084 (afile (abbreviate-file-name file))
18085 (files (delq nil (mapcar
18086 (lambda (x)
18087 (if (equal true-file
18088 (file-truename x))
18089 nil x))
18090 (org-agenda-files t)))))
18091 (if (not (= (length files) (length (org-agenda-files t))))
18092 (progn
18093 (org-store-new-agenda-file-list files)
18094 (org-install-agenda-files-menu)
18095 (message "Removed file: %s" afile))
18096 (message "File was not in list: %s (not removed)" afile))))
18098 (defun org-file-menu-entry (file)
18099 (vector file (list 'find-file file) t))
18101 (defun org-check-agenda-file (file)
18102 "Make sure FILE exists. If not, ask user what to do."
18103 (when (not (file-exists-p file))
18104 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18105 (abbreviate-file-name file))
18106 (let ((r (downcase (read-char-exclusive))))
18107 (cond
18108 ((equal r ?r)
18109 (org-remove-file file)
18110 (throw 'nextfile t))
18111 (t (error "Abort"))))))
18113 (defun org-get-agenda-file-buffer (file)
18114 "Get a buffer visiting FILE. If the buffer needs to be created, add
18115 it to the list of buffers which might be released later."
18116 (let ((buf (org-find-base-buffer-visiting file)))
18117 (if buf
18118 buf ; just return it
18119 ;; Make a new buffer and remember it
18120 (setq buf (find-file-noselect file))
18121 (if buf (push buf org-agenda-new-buffers))
18122 buf)))
18124 (defun org-release-buffers (blist)
18125 "Release all buffers in list, asking the user for confirmation when needed.
18126 When a buffer is unmodified, it is just killed. When modified, it is saved
18127 \(if the user agrees) and then killed."
18128 (let (buf file)
18129 (while (setq buf (pop blist))
18130 (setq file (buffer-file-name buf))
18131 (when (and (buffer-modified-p buf)
18132 file
18133 (y-or-n-p (format "Save file %s? " file)))
18134 (with-current-buffer buf (save-buffer)))
18135 (kill-buffer buf))))
18137 (defun org-agenda-prepare-buffers (files)
18138 "Create buffers for all agenda files, protect archived trees and comments."
18139 (interactive)
18140 (let ((pa '(:org-archived t))
18141 (pc '(:org-comment t))
18142 (pall '(:org-archived t :org-comment t))
18143 (inhibit-read-only t)
18144 (org-inhibit-startup org-agenda-inhibit-startup)
18145 (rea (concat ":" org-archive-tag ":"))
18146 file re pos)
18147 (setq org-tag-alist-for-agenda nil
18148 org-tag-groups-alist-for-agenda nil)
18149 (save-excursion
18150 (save-restriction
18151 (while (setq file (pop files))
18152 (catch 'nextfile
18153 (if (bufferp file)
18154 (set-buffer file)
18155 (org-check-agenda-file file)
18156 (set-buffer (org-get-agenda-file-buffer file)))
18157 (widen)
18158 (org-set-regexps-and-options-for-tags)
18159 (setq pos (point))
18160 (goto-char (point-min))
18161 (let ((case-fold-search t))
18162 (when (search-forward "#+setupfile" nil t)
18163 ;; Don't set all regexps and options systematically as
18164 ;; this is only run for setting agenda tags from setup
18165 ;; file
18166 (org-set-regexps-and-options)))
18167 (or (memq 'category org-agenda-ignore-drawer-properties)
18168 (org-refresh-category-properties))
18169 (or (memq 'effort org-agenda-ignore-drawer-properties)
18170 (org-refresh-properties org-effort-property 'org-effort))
18171 (or (memq 'appt org-agenda-ignore-drawer-properties)
18172 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18173 (setq org-todo-keywords-for-agenda
18174 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18175 (setq org-done-keywords-for-agenda
18176 (append org-done-keywords-for-agenda org-done-keywords))
18177 (setq org-todo-keyword-alist-for-agenda
18178 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18179 (setq org-tag-alist-for-agenda
18180 (org-uniquify
18181 (append org-tag-alist-for-agenda
18182 org-tag-alist
18183 org-tag-persistent-alist)))
18184 (if org-group-tags
18185 (setq org-tag-groups-alist-for-agenda
18186 (org-uniquify-alist
18187 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18188 (org-with-silent-modifications
18189 (save-excursion
18190 (remove-text-properties (point-min) (point-max) pall)
18191 (when org-agenda-skip-archived-trees
18192 (goto-char (point-min))
18193 (while (re-search-forward rea nil t)
18194 (if (org-at-heading-p t)
18195 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18196 (goto-char (point-min))
18197 (setq re (format org-heading-keyword-regexp-format
18198 org-comment-string))
18199 (while (re-search-forward re nil t)
18200 (add-text-properties
18201 (match-beginning 0) (org-end-of-subtree t) pc))))
18202 (goto-char pos)))))
18203 (setq org-todo-keywords-for-agenda
18204 (org-uniquify org-todo-keywords-for-agenda))
18205 (setq org-todo-keyword-alist-for-agenda
18206 (org-uniquify org-todo-keyword-alist-for-agenda))))
18209 ;;;; CDLaTeX minor mode
18211 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18212 "Keymap for the minor `org-cdlatex-mode'.")
18214 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18215 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18216 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18217 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18218 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18220 (defvar org-cdlatex-texmathp-advice-is-done nil
18221 "Flag remembering if we have applied the advice to texmathp already.")
18223 (define-minor-mode org-cdlatex-mode
18224 "Toggle the minor `org-cdlatex-mode'.
18225 This mode supports entering LaTeX environment and math in LaTeX fragments
18226 in Org-mode.
18227 \\{org-cdlatex-mode-map}"
18228 nil " OCDL" nil
18229 (when org-cdlatex-mode
18230 (require 'cdlatex)
18231 (run-hooks 'cdlatex-mode-hook)
18232 (cdlatex-compute-tables))
18233 (unless org-cdlatex-texmathp-advice-is-done
18234 (setq org-cdlatex-texmathp-advice-is-done t)
18235 (defadvice texmathp (around org-math-always-on activate)
18236 "Always return t in org-mode buffers.
18237 This is because we want to insert math symbols without dollars even outside
18238 the LaTeX math segments. If Orgmode thinks that point is actually inside
18239 an embedded LaTeX fragment, let texmathp do its job.
18240 \\[org-cdlatex-mode-map]"
18241 (interactive)
18242 (let (p)
18243 (cond
18244 ((not (derived-mode-p 'org-mode)) ad-do-it)
18245 ((eq this-command 'cdlatex-math-symbol)
18246 (setq ad-return-value t
18247 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18249 (let ((p (org-inside-LaTeX-fragment-p)))
18250 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18251 (setq ad-return-value t
18252 texmathp-why '("Org-mode embedded math" . 0))
18253 (if p ad-do-it)))))))))
18255 (defun turn-on-org-cdlatex ()
18256 "Unconditionally turn on `org-cdlatex-mode'."
18257 (org-cdlatex-mode 1))
18259 (defun org-try-cdlatex-tab ()
18260 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18261 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18262 - inside a LaTeX fragment, or
18263 - after the first word in a line, where an abbreviation expansion could
18264 insert a LaTeX environment."
18265 (when org-cdlatex-mode
18266 (cond
18267 ;; Before any word on the line: No expansion possible.
18268 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18269 ;; Just after first word on the line: Expand it. Make sure it
18270 ;; cannot happen on headlines, though.
18271 ((save-excursion
18272 (skip-chars-backward "a-zA-Z0-9*")
18273 (skip-chars-backward " \t")
18274 (and (bolp) (not (org-at-heading-p))))
18275 (cdlatex-tab) t)
18276 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18278 (defun org-cdlatex-underscore-caret (&optional arg)
18279 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18280 Revert to the normal definition outside of these fragments."
18281 (interactive "P")
18282 (if (org-inside-LaTeX-fragment-p)
18283 (call-interactively 'cdlatex-sub-superscript)
18284 (let (org-cdlatex-mode)
18285 (call-interactively (key-binding (vector last-input-event))))))
18287 (defun org-cdlatex-math-modify (&optional arg)
18288 "Execute `cdlatex-math-modify' in LaTeX fragments.
18289 Revert to the normal definition outside of these fragments."
18290 (interactive "P")
18291 (if (org-inside-LaTeX-fragment-p)
18292 (call-interactively 'cdlatex-math-modify)
18293 (let (org-cdlatex-mode)
18294 (call-interactively (key-binding (vector last-input-event))))))
18298 ;;;; LaTeX fragments
18300 (defun org-inside-LaTeX-fragment-p ()
18301 "Test if point is inside a LaTeX fragment.
18302 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18303 sequence appearing also before point.
18304 Even though the matchers for math are configurable, this function assumes
18305 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18306 delimiters are skipped when they have been removed by customization.
18307 The return value is nil, or a cons cell with the delimiter and the
18308 position of this delimiter.
18310 This function does a reasonably good job, but can locally be fooled by
18311 for example currency specifications. For example it will assume being in
18312 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18313 fragments that are properly closed, but during editing, we have to live
18314 with the uncertainty caused by missing closing delimiters. This function
18315 looks only before point, not after."
18316 (catch 'exit
18317 (let ((pos (point))
18318 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18319 (lim (progn
18320 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18321 (point)))
18322 dd-on str (start 0) m re)
18323 (goto-char pos)
18324 (when dodollar
18325 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18326 re (nth 1 (assoc "$" org-latex-regexps)))
18327 (while (string-match re str start)
18328 (cond
18329 ((= (match-end 0) (length str))
18330 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18331 ((= (match-end 0) (- (length str) 5))
18332 (throw 'exit nil))
18333 (t (setq start (match-end 0))))))
18334 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18335 (goto-char pos)
18336 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18337 (and (match-beginning 2) (throw 'exit nil))
18338 ;; count $$
18339 (while (re-search-backward "\\$\\$" lim t)
18340 (setq dd-on (not dd-on)))
18341 (goto-char pos)
18342 (if dd-on (cons "$$" m))))))
18344 (defun org-inside-latex-macro-p ()
18345 "Is point inside a LaTeX macro or its arguments?"
18346 (save-match-data
18347 (org-in-regexp
18348 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18350 (defvar org-latex-fragment-image-overlays nil
18351 "List of overlays carrying the images of latex fragments.")
18352 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18354 (defun org-remove-latex-fragment-image-overlays ()
18355 "Remove all overlays with LaTeX fragment images in current buffer."
18356 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18357 (setq org-latex-fragment-image-overlays nil))
18359 (defun org-preview-latex-fragment (&optional subtree)
18360 "Preview the LaTeX fragment at point, or all locally or globally.
18361 If the cursor is in a LaTeX fragment, create the image and overlay
18362 it over the source code. If there is no fragment at point, display
18363 all fragments in the current text, from one headline to the next. With
18364 prefix SUBTREE, display all fragments in the current subtree. With a
18365 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18366 the cursor is before the first headline,
18367 display all fragments in the buffer.
18368 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18369 (interactive "P")
18370 (unless buffer-file-name
18371 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18372 (when (display-graphic-p)
18373 (org-remove-latex-fragment-image-overlays)
18374 (save-excursion
18375 (save-restriction
18376 (let (beg end at msg)
18377 (cond
18378 ((or (equal subtree '(16))
18379 (not (save-excursion
18380 (re-search-backward org-outline-regexp-bol nil t))))
18381 (setq beg (point-min) end (point-max)
18382 msg "Creating images for buffer...%s"))
18383 ((equal subtree '(4))
18384 (org-back-to-heading)
18385 (setq beg (point) end (org-end-of-subtree t)
18386 msg "Creating images for subtree...%s"))
18388 (if (setq at (org-inside-LaTeX-fragment-p))
18389 (goto-char (max (point-min) (- (cdr at) 2)))
18390 (org-back-to-heading))
18391 (setq beg (point) end (progn (outline-next-heading) (point))
18392 msg (if at "Creating image...%s"
18393 "Creating images for entry...%s"))))
18394 (message msg "")
18395 (narrow-to-region beg end)
18396 (goto-char beg)
18397 (org-format-latex
18398 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18399 (file-name-nondirectory
18400 buffer-file-name)))
18401 default-directory 'overlays msg at 'forbuffer
18402 org-latex-create-formula-image-program)
18403 (message msg "done. Use `C-c C-c' to remove images."))))))
18405 (defun org-format-latex (prefix &optional dir overlays msg at
18406 forbuffer processing-type)
18407 "Replace LaTeX fragments with links to an image, and produce images.
18408 Some of the options can be changed using the variable
18409 `org-format-latex-options'."
18410 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18411 (let* ((prefixnodir (file-name-nondirectory prefix))
18412 (absprefix (expand-file-name prefix dir))
18413 (todir (file-name-directory absprefix))
18414 (opt org-format-latex-options)
18415 (optnew org-format-latex-options)
18416 (matchers (plist-get opt :matchers))
18417 (re-list org-latex-regexps)
18418 (cnt 0) txt hash link beg end re e checkdir
18419 string
18420 m n block-type block linkfile movefile ov)
18421 ;; Check the different regular expressions
18422 (while (setq e (pop re-list))
18423 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18424 block (if block-type "\n\n" ""))
18425 (when (member m matchers)
18426 (goto-char (point-min))
18427 (while (re-search-forward re nil t)
18428 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18429 (or (not overlays)
18430 (not (eq (get-char-property (match-beginning n)
18431 'org-overlay-type)
18432 'org-latex-overlay))))
18433 (cond
18434 ((eq processing-type 'verbatim))
18435 ((eq processing-type 'mathjax)
18436 ;; Prepare for MathJax processing.
18437 (setq string (match-string n))
18438 (when (member m '("$" "$1"))
18439 (save-excursion
18440 (delete-region (match-beginning n) (match-end n))
18441 (goto-char (match-beginning n))
18442 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18443 ((or (eq processing-type 'dvipng)
18444 (eq processing-type 'imagemagick))
18445 ;; Process to an image.
18446 (setq txt (match-string n)
18447 beg (match-beginning n) end (match-end n)
18448 cnt (1+ cnt))
18449 (let ((face (face-at-point))
18450 (fg (plist-get opt :foreground))
18451 (bg (plist-get opt :background))
18452 ;; Ensure full list is printed.
18453 print-length print-level)
18454 (when forbuffer
18455 ;; Get the colors from the face at point.
18456 (goto-char beg)
18457 (when (eq fg 'auto)
18458 (setq fg (face-attribute face :foreground nil 'default)))
18459 (when (eq bg 'auto)
18460 (setq bg (face-attribute face :background nil 'default)))
18461 (setq optnew (copy-sequence opt))
18462 (plist-put optnew :foreground fg)
18463 (plist-put optnew :background bg))
18464 (setq hash (sha1 (prin1-to-string
18465 (list org-format-latex-header
18466 org-latex-default-packages-alist
18467 org-latex-packages-alist
18468 org-format-latex-options
18469 forbuffer txt fg bg)))
18470 linkfile (format "%s_%s.png" prefix hash)
18471 movefile (format "%s_%s.png" absprefix hash)))
18472 (setq link (concat block "[[file:" linkfile "]]" block))
18473 (if msg (message msg cnt))
18474 (goto-char beg)
18475 (unless checkdir ; Ensure the directory exists.
18476 (setq checkdir t)
18477 (or (file-directory-p todir) (make-directory todir t)))
18478 (unless (file-exists-p movefile)
18479 (org-create-formula-image
18480 txt movefile optnew forbuffer processing-type))
18481 (if overlays
18482 (progn
18483 (mapc (lambda (o)
18484 (if (eq (overlay-get o 'org-overlay-type)
18485 'org-latex-overlay)
18486 (delete-overlay o)))
18487 (overlays-in beg end))
18488 (setq ov (make-overlay beg end))
18489 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18490 (if (featurep 'xemacs)
18491 (progn
18492 (overlay-put ov 'invisible t)
18493 (overlay-put
18494 ov 'end-glyph
18495 (make-glyph (vector 'png :file movefile))))
18496 (overlay-put
18497 ov 'display
18498 (list 'image :type 'png :file movefile :ascent 'center)))
18499 (push ov org-latex-fragment-image-overlays)
18500 (goto-char end))
18501 (delete-region beg end)
18502 (insert (org-add-props link
18503 (list 'org-latex-src
18504 (replace-regexp-in-string
18505 "\"" "" txt)
18506 'org-latex-src-embed-type
18507 (if block-type 'paragraph 'character))))))
18508 ((eq processing-type 'mathml)
18509 ;; Process to MathML
18510 (unless (save-match-data (org-format-latex-mathml-available-p))
18511 (user-error "LaTeX to MathML converter not configured"))
18512 (setq txt (match-string n)
18513 beg (match-beginning n) end (match-end n)
18514 cnt (1+ cnt))
18515 (if msg (message msg cnt))
18516 (goto-char beg)
18517 (delete-region beg end)
18518 (insert (org-format-latex-as-mathml
18519 txt block-type prefix dir)))
18521 (error "Unknown conversion type %s for LaTeX fragments"
18522 processing-type)))))))))
18524 (defun org-create-math-formula (latex-frag &optional mathml-file)
18525 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18526 Use `org-latex-to-mathml-convert-command'. If the conversion is
18527 sucessful, return the portion between \"<math...> </math>\"
18528 elements otherwise return nil. When MATHML-FILE is specified,
18529 write the results in to that file. When invoked as an
18530 interactive command, prompt for LATEX-FRAG, with initial value
18531 set to the current active region and echo the results for user
18532 inspection."
18533 (interactive (list (let ((frag (when (org-region-active-p)
18534 (buffer-substring-no-properties
18535 (region-beginning) (region-end)))))
18536 (read-string "LaTeX Fragment: " frag nil frag))))
18537 (unless latex-frag (error "Invalid LaTeX fragment"))
18538 (let* ((tmp-in-file (file-relative-name
18539 (make-temp-name (expand-file-name "ltxmathml-in"))))
18540 (ignore (write-region latex-frag nil tmp-in-file))
18541 (tmp-out-file (file-relative-name
18542 (make-temp-name (expand-file-name "ltxmathml-out"))))
18543 (cmd (format-spec
18544 org-latex-to-mathml-convert-command
18545 `((?j . ,(shell-quote-argument
18546 (expand-file-name org-latex-to-mathml-jar-file)))
18547 (?I . ,(shell-quote-argument tmp-in-file))
18548 (?o . ,(shell-quote-argument tmp-out-file)))))
18549 mathml shell-command-output)
18550 (when (org-called-interactively-p 'any)
18551 (unless (org-format-latex-mathml-available-p)
18552 (user-error "LaTeX to MathML converter not configured")))
18553 (message "Running %s" cmd)
18554 (setq shell-command-output (shell-command-to-string cmd))
18555 (setq mathml
18556 (when (file-readable-p tmp-out-file)
18557 (with-current-buffer (find-file-noselect tmp-out-file t)
18558 (goto-char (point-min))
18559 (when (re-search-forward
18560 (concat
18561 (regexp-quote
18562 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18563 "\\(.\\|\n\\)*"
18564 (regexp-quote "</math>")) nil t)
18565 (prog1 (match-string 0) (kill-buffer))))))
18566 (cond
18567 (mathml
18568 (setq mathml
18569 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18570 (when mathml-file
18571 (write-region mathml nil mathml-file))
18572 (when (org-called-interactively-p 'any)
18573 (message mathml)))
18574 ((message "LaTeX to MathML conversion failed")
18575 (message shell-command-output)))
18576 (delete-file tmp-in-file)
18577 (when (file-exists-p tmp-out-file)
18578 (delete-file tmp-out-file))
18579 mathml))
18581 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18582 prefix &optional dir)
18583 "Use `org-create-math-formula' but check local cache first."
18584 (let* ((absprefix (expand-file-name prefix dir))
18585 (print-length nil) (print-level nil)
18586 (formula-id (concat
18587 "formula-"
18588 (sha1
18589 (prin1-to-string
18590 (list latex-frag
18591 org-latex-to-mathml-convert-command)))))
18592 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18593 (formula-cache-dir (file-name-directory formula-cache)))
18595 (unless (file-directory-p formula-cache-dir)
18596 (make-directory formula-cache-dir t))
18598 (unless (file-exists-p formula-cache)
18599 (org-create-math-formula latex-frag formula-cache))
18601 (if (file-exists-p formula-cache)
18602 ;; Successful conversion. Return the link to MathML file.
18603 (org-add-props
18604 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18605 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18606 'org-latex-src-embed-type (if latex-frag-type
18607 'paragraph 'character)))
18608 ;; Failed conversion. Return the LaTeX fragment verbatim
18609 latex-frag)))
18611 (defun org-create-formula-image (string tofile options buffer &optional type)
18612 "Create an image from LaTeX source using dvipng or convert.
18613 This function calls either `org-create-formula-image-with-dvipng'
18614 or `org-create-formula-image-with-imagemagick' depending on the
18615 value of `org-latex-create-formula-image-program' or on the value
18616 of the optional TYPE variable.
18618 Note: ultimately these two function should be combined as they
18619 share a good deal of logic."
18620 (org-check-external-command
18621 "latex" "needed to convert LaTeX fragments to images")
18622 (funcall
18623 (case (or type org-latex-create-formula-image-program)
18624 ('dvipng
18625 (org-check-external-command
18626 "dvipng" "needed to convert LaTeX fragments to images")
18627 #'org-create-formula-image-with-dvipng)
18628 ('imagemagick
18629 (org-check-external-command
18630 "convert" "you need to install imagemagick")
18631 #'org-create-formula-image-with-imagemagick)
18632 (t (error
18633 "Invalid value of `org-latex-create-formula-image-program'")))
18634 string tofile options buffer))
18636 (declare-function org-export-get-backend "ox" (name))
18637 (declare-function org-export--get-global-options "ox" (&optional backend))
18638 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18639 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18640 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18641 (defun org-create-formula--latex-header ()
18642 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18643 (let ((info (org-combine-plists (org-export--get-global-options
18644 (org-export-get-backend 'latex))
18645 (org-export--get-inbuffer-options
18646 (org-export-get-backend 'latex)))))
18647 (org-latex-guess-babel-language
18648 (org-latex-guess-inputenc
18649 (org-splice-latex-header
18650 org-format-latex-header
18651 org-latex-default-packages-alist
18652 org-latex-packages-alist t
18653 (plist-get info :latex-header)))
18654 info)))
18656 ;; This function borrows from Ganesh Swami's latex2png.el
18657 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18658 "This calls dvipng."
18659 (require 'ox-latex)
18660 (let* ((tmpdir (if (featurep 'xemacs)
18661 (temp-directory)
18662 temporary-file-directory))
18663 (texfilebase (make-temp-name
18664 (expand-file-name "orgtex" tmpdir)))
18665 (texfile (concat texfilebase ".tex"))
18666 (dvifile (concat texfilebase ".dvi"))
18667 (pngfile (concat texfilebase ".png"))
18668 (fnh (if (featurep 'xemacs)
18669 (font-height (face-font 'default))
18670 (face-attribute 'default :height nil)))
18671 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18672 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18673 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18674 "Black"))
18675 (bg (or (plist-get options (if buffer :background :html-background))
18676 "Transparent")))
18677 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18678 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18679 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18680 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18681 (let ((latex-header (org-create-formula--latex-header)))
18682 (with-temp-file texfile
18683 (insert latex-header)
18684 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18685 (let ((dir default-directory))
18686 (condition-case nil
18687 (progn
18688 (cd tmpdir)
18689 (call-process "latex" nil nil nil texfile))
18690 (error nil))
18691 (cd dir))
18692 (if (not (file-exists-p dvifile))
18693 (progn (message "Failed to create dvi file from %s" texfile) nil)
18694 (condition-case nil
18695 (if (featurep 'xemacs)
18696 (call-process "dvipng" nil nil nil
18697 "-fg" fg "-bg" bg
18698 "-T" "tight"
18699 "-o" pngfile
18700 dvifile)
18701 (call-process "dvipng" nil nil nil
18702 "-fg" fg "-bg" bg
18703 "-D" dpi
18704 ;;"-x" scale "-y" scale
18705 "-T" "tight"
18706 "-o" pngfile
18707 dvifile))
18708 (error nil))
18709 (if (not (file-exists-p pngfile))
18710 (if org-format-latex-signal-error
18711 (error "Failed to create png file from %s" texfile)
18712 (message "Failed to create png file from %s" texfile)
18713 nil)
18714 ;; Use the requested file name and clean up
18715 (copy-file pngfile tofile 'replace)
18716 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18717 (if (file-exists-p (concat texfilebase e))
18718 (delete-file (concat texfilebase e))))
18719 pngfile))))
18721 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18722 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18723 "This calls convert, which is included into imagemagick."
18724 (require 'ox-latex)
18725 (let* ((tmpdir (if (featurep 'xemacs)
18726 (temp-directory)
18727 temporary-file-directory))
18728 (texfilebase (make-temp-name
18729 (expand-file-name "orgtex" tmpdir)))
18730 (texfile (concat texfilebase ".tex"))
18731 (pdffile (concat texfilebase ".pdf"))
18732 (pngfile (concat texfilebase ".png"))
18733 (fnh (if (featurep 'xemacs)
18734 (font-height (face-font 'default))
18735 (face-attribute 'default :height nil)))
18736 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18737 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18738 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18739 "black"))
18740 (bg (or (plist-get options (if buffer :background :html-background))
18741 "white")))
18742 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18743 (setq fg (org-latex-color-format fg)))
18744 (if (eq bg 'default) (setq bg (org-latex-color :background))
18745 (setq bg (org-latex-color-format
18746 (if (string= bg "Transparent") "white" bg))))
18747 (let ((latex-header (org-create-formula--latex-header)))
18748 (with-temp-file texfile
18749 (insert latex-header)
18750 (insert "\n\\begin{document}\n"
18751 "\\definecolor{fg}{rgb}{" fg "}\n"
18752 "\\definecolor{bg}{rgb}{" bg "}\n"
18753 "\n\\pagecolor{bg}\n"
18754 "\n{\\color{fg}\n"
18755 string
18756 "\n}\n"
18757 "\n\\end{document}\n")))
18758 (org-latex-compile texfile t)
18759 (if (not (file-exists-p pdffile))
18760 (progn (message "Failed to create pdf file from %s" texfile) nil)
18761 (condition-case nil
18762 (if (featurep 'xemacs)
18763 (call-process "convert" nil nil nil
18764 "-density" "96"
18765 "-trim"
18766 "-antialias"
18767 pdffile
18768 "-quality" "100"
18769 ;; "-sharpen" "0x1.0"
18770 pngfile)
18771 (call-process "convert" nil nil nil
18772 "-density" dpi
18773 "-trim"
18774 "-antialias"
18775 pdffile
18776 "-quality" "100"
18777 ;; "-sharpen" "0x1.0"
18778 pngfile))
18779 (error nil))
18780 (if (not (file-exists-p pngfile))
18781 (if org-format-latex-signal-error
18782 (error "Failed to create png file from %s" texfile)
18783 (message "Failed to create png file from %s" texfile)
18784 nil)
18785 ;; Use the requested file name and clean up
18786 (copy-file pngfile tofile 'replace)
18787 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18788 (if (file-exists-p (concat texfilebase e))
18789 (delete-file (concat texfilebase e))))
18790 pngfile))))
18792 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18793 "Fill a LaTeX header template TPL.
18794 In the template, the following place holders will be recognized:
18796 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18797 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18798 [PACKAGES] \\usepackage statements for PKG
18799 [NO-PACKAGES] do not include PKG
18800 [EXTRA] the string EXTRA
18801 [NO-EXTRA] do not include EXTRA
18803 For backward compatibility, if both the positive and the negative place
18804 holder is missing, the positive one (without the \"NO-\") will be
18805 assumed to be present at the end of the template.
18806 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18807 EXTRA is a string.
18808 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18809 (let (rpl (end ""))
18810 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18811 (setq rpl (if (or (match-end 1) (not def-pkg))
18812 "" (org-latex-packages-to-string def-pkg snippets-p t))
18813 tpl (replace-match rpl t t tpl))
18814 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18816 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18817 (setq rpl (if (or (match-end 1) (not pkg))
18818 "" (org-latex-packages-to-string pkg snippets-p t))
18819 tpl (replace-match rpl t t tpl))
18820 (if pkg (setq end
18821 (concat end "\n"
18822 (org-latex-packages-to-string pkg snippets-p)))))
18824 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18825 (setq rpl (if (or (match-end 1) (not extra))
18826 "" (concat extra "\n"))
18827 tpl (replace-match rpl t t tpl))
18828 (if (and extra (string-match "\\S-" extra))
18829 (setq end (concat end "\n" extra))))
18831 (if (string-match "\\S-" end)
18832 (concat tpl "\n" end)
18833 tpl)))
18835 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18836 "Turn an alist of packages into a string with the \\usepackage macros."
18837 (setq pkg (mapconcat (lambda(p)
18838 (cond
18839 ((stringp p) p)
18840 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18841 (format "%% Package %s omitted" (cadr p)))
18842 ((equal "" (car p))
18843 (format "\\usepackage{%s}" (cadr p)))
18845 (format "\\usepackage[%s]{%s}"
18846 (car p) (cadr p)))))
18848 "\n"))
18849 (if newline (concat pkg "\n") pkg))
18851 (defun org-dvipng-color (attr)
18852 "Return a RGB color specification for dvipng."
18853 (apply 'format "rgb %s %s %s"
18854 (mapcar 'org-normalize-color
18855 (if (featurep 'xemacs)
18856 (color-rgb-components
18857 (face-property 'default
18858 (cond ((eq attr :foreground) 'foreground)
18859 ((eq attr :background) 'background))))
18860 (color-values (face-attribute 'default attr nil))))))
18862 (defun org-dvipng-color-format (color-name)
18863 "Convert COLOR-NAME to a RGB color value for dvipng."
18864 (apply 'format "rgb %s %s %s"
18865 (mapcar 'org-normalize-color
18866 (color-values color-name))))
18868 (defun org-latex-color (attr)
18869 "Return a RGB color for the LaTeX color package."
18870 (apply 'format "%s,%s,%s"
18871 (mapcar 'org-normalize-color
18872 (if (featurep 'xemacs)
18873 (color-rgb-components
18874 (face-property 'default
18875 (cond ((eq attr :foreground) 'foreground)
18876 ((eq attr :background) 'background))))
18877 (color-values (face-attribute 'default attr nil))))))
18879 (defun org-latex-color-format (color-name)
18880 "Convert COLOR-NAME to a RGB color value."
18881 (apply 'format "%s,%s,%s"
18882 (mapcar 'org-normalize-color
18883 (color-values color-name))))
18885 (defun org-normalize-color (value)
18886 "Return string to be used as color value for an RGB component."
18887 (format "%g" (/ value 65535.0)))
18891 ;; Image display
18893 (defvar org-inline-image-overlays nil)
18894 (make-variable-buffer-local 'org-inline-image-overlays)
18896 (defun org-toggle-inline-images (&optional include-linked)
18897 "Toggle the display of inline images.
18898 INCLUDE-LINKED is passed to `org-display-inline-images'."
18899 (interactive "P")
18900 (if org-inline-image-overlays
18901 (progn
18902 (org-remove-inline-images)
18903 (message "Inline image display turned off"))
18904 (org-display-inline-images include-linked)
18905 (if (and (org-called-interactively-p)
18906 org-inline-image-overlays)
18907 (message "%d images displayed inline"
18908 (length org-inline-image-overlays))
18909 (message "No images to display inline"))))
18911 (defun org-redisplay-inline-images ()
18912 "Refresh the display of inline images."
18913 (interactive)
18914 (if (not org-inline-image-overlays)
18915 (org-toggle-inline-images)
18916 (org-toggle-inline-images)
18917 (org-toggle-inline-images)))
18919 (defun org-display-inline-images (&optional include-linked refresh beg end)
18920 "Display inline images.
18922 An inline image is a link which follows either of these
18923 conventions:
18925 1. Its path is a file with an extension matching return value
18926 from `image-file-name-regexp' and it has no contents.
18928 2. Its description consists in a single link of the previous
18929 type.
18931 When optional argument INCLUDE-LINKED is non-nil, also links with
18932 a text description part will be inlined. This can be nice for
18933 a quick look at those images, but it does not reflect what
18934 exported files will look like.
18936 When optional argument REFRESH is non-nil, refresh existing
18937 images between BEG and END. This will create new image displays
18938 only if necessary. BEG and END default to the buffer
18939 boundaries."
18940 (interactive "P")
18941 (when (display-graphic-p)
18942 (unless refresh
18943 (org-remove-inline-images)
18944 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18945 (org-with-wide-buffer
18946 (goto-char (or beg (point-min)))
18947 (let ((case-fold-search t)
18948 (file-extension-re (org-image-file-name-regexp)))
18949 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
18950 (let ((link (save-match-data (org-element-context))))
18951 ;; Check if we're at an inline image.
18952 (when (and (equal (org-element-property :type link) "file")
18953 (or include-linked
18954 (not (org-element-property :contents-begin link)))
18955 (let ((parent (org-element-property :parent link)))
18956 (or (not (eq (org-element-type parent) 'link))
18957 (not (cdr (org-element-contents parent)))))
18958 (org-string-match-p file-extension-re
18959 (org-element-property :path link)))
18960 (let ((file (expand-file-name (org-element-property :path link))))
18961 (when (file-exists-p file)
18962 (let ((width
18963 ;; Apply `org-image-actual-width' specifications.
18964 (cond
18965 ((not (image-type-available-p 'imagemagick)) nil)
18966 ((eq org-image-actual-width t) nil)
18967 ((listp org-image-actual-width)
18969 ;; First try to find a width among
18970 ;; attributes associated to the paragraph
18971 ;; containing link.
18972 (let ((paragraph
18973 (let ((e link))
18974 (while (and (setq e (org-element-property
18975 :parent e))
18976 (not (eq (org-element-type e)
18977 'paragraph))))
18978 e)))
18979 (when paragraph
18980 (save-excursion
18981 (goto-char (org-element-property :begin paragraph))
18982 (when (save-match-data
18983 (re-search-forward
18984 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18985 (org-element-property
18986 :post-affiliated paragraph)
18988 (string-to-number (match-string 1))))))
18989 ;; Otherwise, fall-back to provided number.
18990 (car org-image-actual-width)))
18991 ((numberp org-image-actual-width)
18992 org-image-actual-width)))
18993 (old (get-char-property-and-overlay
18994 (org-element-property :begin link)
18995 'org-image-overlay)))
18996 (if (and (car-safe old) refresh)
18997 (image-refresh (overlay-get (cdr old) 'display))
18998 (let ((image (save-match-data
18999 (create-image file
19000 (and width 'imagemagick)
19002 :width width))))
19003 (when image
19004 (let* ((link
19005 ;; If inline image is the description
19006 ;; of another link, be sure to
19007 ;; consider the latter as the one to
19008 ;; apply the overlay on.
19009 (let ((parent
19010 (org-element-property :parent link)))
19011 (if (eq (org-element-type parent) 'link)
19012 parent
19013 link)))
19014 (ov (make-overlay
19015 (org-element-property :begin link)
19016 (progn
19017 (goto-char
19018 (org-element-property :end link))
19019 (skip-chars-backward " \t")
19020 (point)))))
19021 (overlay-put ov 'display image)
19022 (overlay-put ov 'face 'default)
19023 (overlay-put ov 'org-image-overlay t)
19024 (overlay-put
19025 ov 'modification-hooks
19026 (list 'org-display-inline-remove-overlay))
19027 (push ov org-inline-image-overlays)))))))))))))))
19029 (define-obsolete-function-alias
19030 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19032 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19033 "Remove inline-display overlay if a corresponding region is modified."
19034 (let ((inhibit-modification-hooks t))
19035 (when (and ov after)
19036 (delete ov org-inline-image-overlays)
19037 (delete-overlay ov))))
19039 (defun org-remove-inline-images ()
19040 "Remove inline display of images."
19041 (interactive)
19042 (mapc 'delete-overlay org-inline-image-overlays)
19043 (setq org-inline-image-overlays nil))
19045 ;;;; Key bindings
19047 ;; Outline functions from `outline-mode-prefix-map'
19048 ;; that can be remapped in Org:
19049 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19050 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19051 (define-key org-mode-map [remap outline-forward-same-level]
19052 'org-forward-heading-same-level)
19053 (define-key org-mode-map [remap outline-backward-same-level]
19054 'org-backward-heading-same-level)
19055 (define-key org-mode-map [remap show-branches]
19056 'org-kill-note-or-show-branches)
19057 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19058 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19059 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19061 ;; Outline functions from `outline-mode-prefix-map' that can not
19062 ;; be remapped in Org:
19064 ;; - the column "key binding" shows whether the Outline function is still
19065 ;; available in Org mode on the same key that it has been bound to in
19066 ;; Outline mode:
19067 ;; - "overridden": key used for a different functionality in Org mode
19068 ;; - else: key still bound to the same Outline function in Org mode
19070 ;; | Outline function | key binding | Org replacement |
19071 ;; |------------------------------------+-------------+-----------------------|
19072 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19073 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19074 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19075 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19076 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19077 ;; | `show-entry' | overridden | no replacement |
19078 ;; | `show-children' | `C-c C-i' | visibility cycling |
19079 ;; | `show-branches' | `C-c C-k' | still same function |
19080 ;; | `show-subtree' | overridden | visibility cycling |
19081 ;; | `show-all' | overridden | no replacement |
19082 ;; | `hide-subtree' | overridden | visibility cycling |
19083 ;; | `hide-body' | overridden | no replacement |
19084 ;; | `hide-entry' | overridden | visibility cycling |
19085 ;; | `hide-leaves' | overridden | no replacement |
19086 ;; | `hide-sublevels' | overridden | no replacement |
19087 ;; | `hide-other' | overridden | no replacement |
19089 ;; Make `C-c C-x' a prefix key
19090 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19092 ;; TAB key with modifiers
19093 (org-defkey org-mode-map "\C-i" 'org-cycle)
19094 (org-defkey org-mode-map [(tab)] 'org-cycle)
19095 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19096 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19097 ;; The following line is necessary under Suse GNU/Linux
19098 (unless (featurep 'xemacs)
19099 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19100 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19101 (define-key org-mode-map [backtab] 'org-shifttab)
19103 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19104 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19105 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19107 ;; Cursor keys with modifiers
19108 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19109 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19110 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19111 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19113 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19114 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19115 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19116 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19118 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19119 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19120 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19121 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19123 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19124 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19125 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19126 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19128 ;; Babel keys
19129 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19130 (mapc (lambda (pair)
19131 (define-key org-babel-map (car pair) (cdr pair)))
19132 org-babel-key-bindings)
19134 ;;; Extra keys for tty access.
19135 ;; We only set them when really needed because otherwise the
19136 ;; menus don't show the simple keys
19138 (when (or org-use-extra-keys
19139 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19140 (not window-system))
19141 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19142 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19143 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19144 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19145 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19146 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19147 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19148 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19149 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19150 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19151 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19152 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19153 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19154 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19155 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19156 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19157 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19158 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19159 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19160 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19161 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19162 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19163 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19164 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19165 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19166 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19167 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19168 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19170 ;; All the other keys
19172 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19173 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19174 (if (boundp 'narrow-map)
19175 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19176 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19177 (if (boundp 'narrow-map)
19178 (org-defkey narrow-map "b" 'org-narrow-to-block)
19179 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19180 (if (boundp 'narrow-map)
19181 (org-defkey narrow-map "e" 'org-narrow-to-element)
19182 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19183 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19184 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19185 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19186 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19187 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19188 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19189 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19190 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19191 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19192 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19193 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19194 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19195 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19196 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19197 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19198 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19199 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19200 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19201 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19202 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19203 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19204 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19205 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19206 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19207 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19208 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19209 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19210 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19211 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19212 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19213 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19214 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19215 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19216 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19217 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19218 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19219 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19220 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19221 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19222 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19223 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19224 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19225 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19226 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19227 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19228 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19229 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19230 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19231 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19232 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19233 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19234 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19235 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19236 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19237 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19238 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19239 (org-defkey org-mode-map "\C-c^" 'org-sort)
19240 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19241 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19242 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19243 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19244 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19245 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19246 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19247 (org-defkey org-mode-map "\C-m" 'org-return)
19248 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19249 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19250 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19251 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19252 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19253 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19254 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19255 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19256 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19257 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19258 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19259 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19260 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19261 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19262 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19263 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19264 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19265 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19266 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19267 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19268 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19269 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19270 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19272 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19273 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19274 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19276 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19277 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19278 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19279 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19280 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19281 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19282 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19283 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19284 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19285 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19286 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19287 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19288 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19289 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19290 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19291 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19292 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19293 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19294 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19295 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19296 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19297 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19298 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19300 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19301 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19302 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19303 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19304 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19306 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19308 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19310 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19311 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19313 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19316 (when (featurep 'xemacs)
19317 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19320 (defconst org-speed-commands-default
19322 ("Outline Navigation")
19323 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19324 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19325 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19326 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19327 ("F" . org-next-block)
19328 ("B" . org-previous-block)
19329 ("u" . (org-speed-move-safe 'outline-up-heading))
19330 ("j" . org-goto)
19331 ("g" . (org-refile t))
19332 ("Outline Visibility")
19333 ("c" . org-cycle)
19334 ("C" . org-shifttab)
19335 (" " . org-display-outline-path)
19336 ("s" . org-narrow-to-subtree)
19337 ("=" . org-columns)
19338 ("Outline Structure Editing")
19339 ("U" . org-shiftmetaup)
19340 ("D" . org-shiftmetadown)
19341 ("r" . org-metaright)
19342 ("l" . org-metaleft)
19343 ("R" . org-shiftmetaright)
19344 ("L" . org-shiftmetaleft)
19345 ("i" . (progn (forward-char 1) (call-interactively
19346 'org-insert-heading-respect-content)))
19347 ("^" . org-sort)
19348 ("w" . org-refile)
19349 ("a" . org-archive-subtree-default-with-confirmation)
19350 ("@" . org-mark-subtree)
19351 ("#" . org-toggle-comment)
19352 ("Clock Commands")
19353 ("I" . org-clock-in)
19354 ("O" . org-clock-out)
19355 ("Meta Data Editing")
19356 ("t" . org-todo)
19357 ("," . (org-priority))
19358 ("0" . (org-priority ?\ ))
19359 ("1" . (org-priority ?A))
19360 ("2" . (org-priority ?B))
19361 ("3" . (org-priority ?C))
19362 (":" . org-set-tags-command)
19363 ("e" . org-set-effort)
19364 ("E" . org-inc-effort)
19365 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19366 (org-entry-put (point) "APPT_WARNTIME" m)))
19367 ("Agenda Views etc")
19368 ("v" . org-agenda)
19369 ("/" . org-sparse-tree)
19370 ("Misc")
19371 ("o" . org-open-at-point)
19372 ("?" . org-speed-command-help)
19373 ("<" . (org-agenda-set-restriction-lock 'subtree))
19374 (">" . (org-agenda-remove-restriction-lock))
19376 "The default speed commands.")
19378 (defun org-print-speed-command (e)
19379 (if (> (length (car e)) 1)
19380 (progn
19381 (princ "\n")
19382 (princ (car e))
19383 (princ "\n")
19384 (princ (make-string (length (car e)) ?-))
19385 (princ "\n"))
19386 (princ (car e))
19387 (princ " ")
19388 (if (symbolp (cdr e))
19389 (princ (symbol-name (cdr e)))
19390 (prin1 (cdr e)))
19391 (princ "\n")))
19393 (defun org-speed-command-help ()
19394 "Show the available speed commands."
19395 (interactive)
19396 (if (not org-use-speed-commands)
19397 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19398 (with-output-to-temp-buffer "*Help*"
19399 (princ "User-defined Speed commands\n===========================\n")
19400 (mapc 'org-print-speed-command org-speed-commands-user)
19401 (princ "\n")
19402 (princ "Built-in Speed commands\n=======================\n")
19403 (mapc 'org-print-speed-command org-speed-commands-default))
19404 (with-current-buffer "*Help*"
19405 (setq truncate-lines t))))
19407 (defun org-speed-move-safe (cmd)
19408 "Execute CMD, but make sure that the cursor always ends up in a headline.
19409 If not, return to the original position and throw an error."
19410 (interactive)
19411 (let ((pos (point)))
19412 (call-interactively cmd)
19413 (unless (and (bolp) (org-at-heading-p))
19414 (goto-char pos)
19415 (error "Boundary reached while executing %s" cmd))))
19417 (defvar org-self-insert-command-undo-counter 0)
19419 (defvar org-table-auto-blank-field) ; defined in org-table.el
19420 (defvar org-speed-command nil)
19422 (define-obsolete-function-alias
19423 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19425 (defun org-speed-command-activate (keys)
19426 "Hook for activating single-letter speed commands.
19427 `org-speed-commands-default' specifies a minimal command set.
19428 Use `org-speed-commands-user' for further customization."
19429 (when (or (and (bolp) (looking-at org-outline-regexp))
19430 (and (functionp org-use-speed-commands)
19431 (funcall org-use-speed-commands)))
19432 (cdr (assoc keys (append org-speed-commands-user
19433 org-speed-commands-default)))))
19435 (define-obsolete-function-alias
19436 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19438 (defun org-babel-speed-command-activate (keys)
19439 "Hook for activating single-letter code block commands."
19440 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19441 (cdr (assoc keys org-babel-key-bindings))))
19443 (defcustom org-speed-command-hook
19444 '(org-speed-command-default-hook org-babel-speed-command-hook)
19445 "Hook for activating speed commands at strategic locations.
19446 Hook functions are called in sequence until a valid handler is
19447 found.
19449 Each hook takes a single argument, a user-pressed command key
19450 which is also a `self-insert-command' from the global map.
19452 Within the hook, examine the cursor position and the command key
19453 and return nil or a valid handler as appropriate. Handler could
19454 be one of an interactive command, a function, or a form.
19456 Set `org-use-speed-commands' to non-nil value to enable this
19457 hook. The default setting is `org-speed-command-activate'."
19458 :group 'org-structure
19459 :version "24.1"
19460 :type 'hook)
19462 (defun org-self-insert-command (N)
19463 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19464 If the cursor is in a table looking at whitespace, the whitespace is
19465 overwritten, and the table is not marked as requiring realignment."
19466 (interactive "p")
19467 (org-check-before-invisible-edit 'insert)
19468 (cond
19469 ((and org-use-speed-commands
19470 (setq org-speed-command
19471 (run-hook-with-args-until-success
19472 'org-speed-command-hook (this-command-keys))))
19473 (cond
19474 ((commandp org-speed-command)
19475 (setq this-command org-speed-command)
19476 (call-interactively org-speed-command))
19477 ((functionp org-speed-command)
19478 (funcall org-speed-command))
19479 ((and org-speed-command (listp org-speed-command))
19480 (eval org-speed-command))
19481 (t (let (org-use-speed-commands)
19482 (call-interactively 'org-self-insert-command)))))
19483 ((and
19484 (org-table-p)
19485 (progn
19486 ;; check if we blank the field, and if that triggers align
19487 (and (featurep 'org-table) org-table-auto-blank-field
19488 (member last-command
19489 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19490 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19491 ;; got extra space, this field does not determine column width
19492 (let (org-table-may-need-update) (org-table-blank-field))
19493 ;; no extra space, this field may determine column width
19494 (org-table-blank-field)))
19496 (eq N 1)
19497 (looking-at "[^|\n]* |"))
19498 (let (org-table-may-need-update)
19499 (goto-char (1- (match-end 0)))
19500 (backward-delete-char 1)
19501 (goto-char (match-beginning 0))
19502 (self-insert-command N)))
19504 (setq org-table-may-need-update t)
19505 (self-insert-command N)
19506 (org-fix-tags-on-the-fly)
19507 (if org-self-insert-cluster-for-undo
19508 (if (not (eq last-command 'org-self-insert-command))
19509 (setq org-self-insert-command-undo-counter 1)
19510 (if (>= org-self-insert-command-undo-counter 20)
19511 (setq org-self-insert-command-undo-counter 1)
19512 (and (> org-self-insert-command-undo-counter 0)
19513 buffer-undo-list (listp buffer-undo-list)
19514 (not (cadr buffer-undo-list)) ; remove nil entry
19515 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19516 (setq org-self-insert-command-undo-counter
19517 (1+ org-self-insert-command-undo-counter))))))))
19519 (defun org-check-before-invisible-edit (kind)
19520 "Check is editing if kind KIND would be dangerous with invisible text around.
19521 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19522 ;; First, try to get out of here as quickly as possible, to reduce overhead
19523 (if (and org-catch-invisible-edits
19524 (or (not (boundp 'visible-mode)) (not visible-mode))
19525 (or (get-char-property (point) 'invisible)
19526 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19527 ;; OK, we need to take a closer look
19528 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19529 (invisible-before-point (if (bobp) nil (get-char-property
19530 (1- (point)) 'invisible)))
19531 (border-and-ok-direction
19533 ;; Check if we are acting predictably before invisible text
19534 (and invisible-at-point (not invisible-before-point)
19535 (memq kind '(insert delete-backward)))
19536 ;; Check if we are acting predictably after invisible text
19537 ;; This works not well, and I have turned it off. It seems
19538 ;; better to always show and stop after invisible text.
19539 ;; (and (not invisible-at-point) invisible-before-point
19540 ;; (memq kind '(insert delete)))
19542 (when (or (memq invisible-at-point '(outline org-hide-block t))
19543 (memq invisible-before-point '(outline org-hide-block t)))
19544 (if (eq org-catch-invisible-edits 'error)
19545 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19546 (if (and org-custom-properties-overlays
19547 (y-or-n-p "Display invisible properties in this buffer? "))
19548 (org-toggle-custom-properties-visibility)
19549 ;; Make the area visible
19550 (save-excursion
19551 (if invisible-before-point
19552 (goto-char (previous-single-char-property-change
19553 (point) 'invisible)))
19554 (org-cycle))
19555 (cond
19556 ((eq org-catch-invisible-edits 'show)
19557 ;; That's it, we do the edit after showing
19558 (message
19559 "Unfolding invisible region around point before editing")
19560 (sit-for 1))
19561 ((and (eq org-catch-invisible-edits 'smart)
19562 border-and-ok-direction)
19563 (message "Unfolding invisible region around point before editing"))
19565 ;; Don't do the edit, make the user repeat it in full visibility
19566 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19568 (defun org-fix-tags-on-the-fly ()
19569 (when (and (equal (char-after (point-at-bol)) ?*)
19570 (org-at-heading-p))
19571 (org-align-tags-here org-tags-column)))
19573 (defun org-delete-backward-char (N)
19574 "Like `delete-backward-char', insert whitespace at field end in tables.
19575 When deleting backwards, in tables this function will insert whitespace in
19576 front of the next \"|\" separator, to keep the table aligned. The table will
19577 still be marked for re-alignment if the field did fill the entire column,
19578 because, in this case the deletion might narrow the column."
19579 (interactive "p")
19580 (save-match-data
19581 (org-check-before-invisible-edit 'delete-backward)
19582 (if (and (org-table-p)
19583 (eq N 1)
19584 (string-match "|" (buffer-substring (point-at-bol) (point)))
19585 (looking-at ".*?|"))
19586 (let ((pos (point))
19587 (noalign (looking-at "[^|\n\r]* |"))
19588 (c org-table-may-need-update))
19589 (backward-delete-char N)
19590 (if (not overwrite-mode)
19591 (progn
19592 (skip-chars-forward "^|")
19593 (insert " ")
19594 (goto-char (1- pos))))
19595 ;; noalign: if there were two spaces at the end, this field
19596 ;; does not determine the width of the column.
19597 (if noalign (setq org-table-may-need-update c)))
19598 (backward-delete-char N)
19599 (org-fix-tags-on-the-fly))))
19601 (defun org-delete-char (N)
19602 "Like `delete-char', but insert whitespace at field end in tables.
19603 When deleting characters, in tables this function will insert whitespace in
19604 front of the next \"|\" separator, to keep the table aligned. The table will
19605 still be marked for re-alignment if the field did fill the entire column,
19606 because, in this case the deletion might narrow the column."
19607 (interactive "p")
19608 (save-match-data
19609 (org-check-before-invisible-edit 'delete)
19610 (if (and (org-table-p)
19611 (not (bolp))
19612 (not (= (char-after) ?|))
19613 (eq N 1))
19614 (if (looking-at ".*?|")
19615 (let ((pos (point))
19616 (noalign (looking-at "[^|\n\r]* |"))
19617 (c org-table-may-need-update))
19618 (replace-match
19619 (concat (substring (match-string 0) 1 -1) " |") nil t)
19620 (goto-char pos)
19621 ;; noalign: if there were two spaces at the end, this field
19622 ;; does not determine the width of the column.
19623 (if noalign (setq org-table-may-need-update c)))
19624 (delete-char N))
19625 (delete-char N)
19626 (org-fix-tags-on-the-fly))))
19628 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19629 (put 'org-self-insert-command 'delete-selection
19630 (lambda ()
19631 (not (run-hook-with-args-until-success
19632 'self-insert-uses-region-functions))))
19633 (put 'orgtbl-self-insert-command 'delete-selection
19634 (lambda ()
19635 (not (run-hook-with-args-until-success
19636 'self-insert-uses-region-functions))))
19637 (put 'org-delete-char 'delete-selection 'supersede)
19638 (put 'org-delete-backward-char 'delete-selection 'supersede)
19639 (put 'org-yank 'delete-selection 'yank)
19641 ;; Make `flyspell-mode' delay after some commands
19642 (put 'org-self-insert-command 'flyspell-delayed t)
19643 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19644 (put 'org-delete-char 'flyspell-delayed t)
19645 (put 'org-delete-backward-char 'flyspell-delayed t)
19647 ;; Make pabbrev-mode expand after org-mode commands
19648 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19649 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19651 (defun org-remap (map &rest commands)
19652 "In MAP, remap the functions given in COMMANDS.
19653 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19654 (let (new old)
19655 (while commands
19656 (setq old (pop commands) new (pop commands))
19657 (if (fboundp 'command-remapping)
19658 (org-defkey map (vector 'remap old) new)
19659 (substitute-key-definition old new map global-map)))))
19661 (defun org-transpose-words ()
19662 "Transpose words for Org.
19663 This uses the `org-mode-transpose-word-syntax-table' syntax
19664 table, which interprets characters in `org-emphasis-alist' as
19665 word constituents."
19666 (interactive)
19667 (with-syntax-table org-mode-transpose-word-syntax-table
19668 (call-interactively 'transpose-words)))
19669 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19671 (when (eq org-enable-table-editor 'optimized)
19672 ;; If the user wants maximum table support, we need to hijack
19673 ;; some standard editing functions
19674 (org-remap org-mode-map
19675 'self-insert-command 'org-self-insert-command
19676 'delete-char 'org-delete-char
19677 'delete-backward-char 'org-delete-backward-char)
19678 (org-defkey org-mode-map "|" 'org-force-self-insert))
19680 (defvar org-ctrl-c-ctrl-c-hook nil
19681 "Hook for functions attaching themselves to `C-c C-c'.
19683 This can be used to add additional functionality to the C-c C-c
19684 key which executes context-dependent commands. This hook is run
19685 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19686 run after the last test.
19688 Each function will be called with no arguments. The function
19689 must check if the context is appropriate for it to act. If yes,
19690 it should do its thing and then return a non-nil value. If the
19691 context is wrong, just do nothing and return nil.")
19693 (defvar org-ctrl-c-ctrl-c-final-hook nil
19694 "Hook for functions attaching themselves to `C-c C-c'.
19696 This can be used to add additional functionality to the C-c C-c
19697 key which executes context-dependent commands. This hook is run
19698 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19699 before the first test.
19701 Each function will be called with no arguments. The function
19702 must check if the context is appropriate for it to act. If yes,
19703 it should do its thing and then return a non-nil value. If the
19704 context is wrong, just do nothing and return nil.")
19706 (defvar org-tab-first-hook nil
19707 "Hook for functions to attach themselves to TAB.
19708 See `org-ctrl-c-ctrl-c-hook' for more information.
19709 This hook runs as the first action when TAB is pressed, even before
19710 `org-cycle' messes around with the `outline-regexp' to cater for
19711 inline tasks and plain list item folding.
19712 If any function in this hook returns t, any other actions that
19713 would have been caused by TAB (such as table field motion or visibility
19714 cycling) will not occur.")
19716 (defvar org-tab-after-check-for-table-hook nil
19717 "Hook for functions to attach themselves to TAB.
19718 See `org-ctrl-c-ctrl-c-hook' for more information.
19719 This hook runs after it has been established that the cursor is not in a
19720 table, but before checking if the cursor is in a headline or if global cycling
19721 should be done.
19722 If any function in this hook returns t, not other actions like visibility
19723 cycling will be done.")
19725 (defvar org-tab-after-check-for-cycling-hook nil
19726 "Hook for functions to attach themselves to TAB.
19727 See `org-ctrl-c-ctrl-c-hook' for more information.
19728 This hook runs after it has been established that not table field motion and
19729 not visibility should be done because of current context. This is probably
19730 the place where a package like yasnippets can hook in.")
19732 (defvar org-tab-before-tab-emulation-hook nil
19733 "Hook for functions to attach themselves to TAB.
19734 See `org-ctrl-c-ctrl-c-hook' for more information.
19735 This hook runs after every other options for TAB have been exhausted, but
19736 before indentation and \t insertion takes place.")
19738 (defvar org-metaleft-hook nil
19739 "Hook for functions attaching themselves to `M-left'.
19740 See `org-ctrl-c-ctrl-c-hook' for more information.")
19741 (defvar org-metaright-hook nil
19742 "Hook for functions attaching themselves to `M-right'.
19743 See `org-ctrl-c-ctrl-c-hook' for more information.")
19744 (defvar org-metaup-hook nil
19745 "Hook for functions attaching themselves to `M-up'.
19746 See `org-ctrl-c-ctrl-c-hook' for more information.")
19747 (defvar org-metadown-hook nil
19748 "Hook for functions attaching themselves to `M-down'.
19749 See `org-ctrl-c-ctrl-c-hook' for more information.")
19750 (defvar org-shiftmetaleft-hook nil
19751 "Hook for functions attaching themselves to `M-S-left'.
19752 See `org-ctrl-c-ctrl-c-hook' for more information.")
19753 (defvar org-shiftmetaright-hook nil
19754 "Hook for functions attaching themselves to `M-S-right'.
19755 See `org-ctrl-c-ctrl-c-hook' for more information.")
19756 (defvar org-shiftmetaup-hook nil
19757 "Hook for functions attaching themselves to `M-S-up'.
19758 See `org-ctrl-c-ctrl-c-hook' for more information.")
19759 (defvar org-shiftmetadown-hook nil
19760 "Hook for functions attaching themselves to `M-S-down'.
19761 See `org-ctrl-c-ctrl-c-hook' for more information.")
19762 (defvar org-metareturn-hook nil
19763 "Hook for functions attaching themselves to `M-RET'.
19764 See `org-ctrl-c-ctrl-c-hook' for more information.")
19765 (defvar org-shiftup-hook nil
19766 "Hook for functions attaching themselves to `S-up'.
19767 See `org-ctrl-c-ctrl-c-hook' for more information.")
19768 (defvar org-shiftup-final-hook nil
19769 "Hook for functions attaching themselves to `S-up'.
19770 This one runs after all other options except shift-select have been excluded.
19771 See `org-ctrl-c-ctrl-c-hook' for more information.")
19772 (defvar org-shiftdown-hook nil
19773 "Hook for functions attaching themselves to `S-down'.
19774 See `org-ctrl-c-ctrl-c-hook' for more information.")
19775 (defvar org-shiftdown-final-hook nil
19776 "Hook for functions attaching themselves to `S-down'.
19777 This one runs after all other options except shift-select have been excluded.
19778 See `org-ctrl-c-ctrl-c-hook' for more information.")
19779 (defvar org-shiftleft-hook nil
19780 "Hook for functions attaching themselves to `S-left'.
19781 See `org-ctrl-c-ctrl-c-hook' for more information.")
19782 (defvar org-shiftleft-final-hook nil
19783 "Hook for functions attaching themselves to `S-left'.
19784 This one runs after all other options except shift-select have been excluded.
19785 See `org-ctrl-c-ctrl-c-hook' for more information.")
19786 (defvar org-shiftright-hook nil
19787 "Hook for functions attaching themselves to `S-right'.
19788 See `org-ctrl-c-ctrl-c-hook' for more information.")
19789 (defvar org-shiftright-final-hook nil
19790 "Hook for functions attaching themselves to `S-right'.
19791 This one runs after all other options except shift-select have been excluded.
19792 See `org-ctrl-c-ctrl-c-hook' for more information.")
19794 (defun org-modifier-cursor-error ()
19795 "Throw an error, a modified cursor command was applied in wrong context."
19796 (user-error "This command is active in special context like tables, headlines or items"))
19798 (defun org-shiftselect-error ()
19799 "Throw an error because Shift-Cursor command was applied in wrong context."
19800 (if (and (boundp 'shift-select-mode) shift-select-mode)
19801 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19802 (user-error "This command works only in special context like headlines or timestamps")))
19804 (defun org-call-for-shift-select (cmd)
19805 (let ((this-command-keys-shift-translated t))
19806 (call-interactively cmd)))
19808 (defun org-shifttab (&optional arg)
19809 "Global visibility cycling or move to previous table field.
19810 Call `org-table-previous-field' within a table.
19811 When ARG is nil, cycle globally through visibility states.
19812 When ARG is a numeric prefix, show contents of this level."
19813 (interactive "P")
19814 (cond
19815 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19816 ((integerp arg)
19817 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19818 (message "Content view to level: %d" arg)
19819 (org-content (prefix-numeric-value arg2))
19820 (org-cycle-show-empty-lines t)
19821 (setq org-cycle-global-status 'overview)))
19822 (t (call-interactively 'org-global-cycle))))
19824 (defun org-shiftmetaleft ()
19825 "Promote subtree or delete table column.
19826 Calls `org-promote-subtree', `org-outdent-item-tree', or
19827 `org-table-delete-column', depending on context. See the
19828 individual commands for more information."
19829 (interactive)
19830 (cond
19831 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19832 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19833 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19834 ((if (not (org-region-active-p)) (org-at-item-p)
19835 (save-excursion (goto-char (region-beginning))
19836 (org-at-item-p)))
19837 (call-interactively 'org-outdent-item-tree))
19838 (t (org-modifier-cursor-error))))
19840 (defun org-shiftmetaright ()
19841 "Demote subtree or insert table column.
19842 Calls `org-demote-subtree', `org-indent-item-tree', or
19843 `org-table-insert-column', depending on context. See the
19844 individual commands for more information."
19845 (interactive)
19846 (cond
19847 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19848 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19849 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19850 ((if (not (org-region-active-p)) (org-at-item-p)
19851 (save-excursion (goto-char (region-beginning))
19852 (org-at-item-p)))
19853 (call-interactively 'org-indent-item-tree))
19854 (t (org-modifier-cursor-error))))
19856 (defun org-shiftmetaup (&optional arg)
19857 "Move subtree up or kill table row.
19858 Calls `org-move-subtree-up' or `org-table-kill-row' or
19859 `org-move-item-up' or `org-timestamp-up', depending on context.
19860 See the individual commands for more information."
19861 (interactive "P")
19862 (cond
19863 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19864 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19865 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19866 ((org-at-item-p) (call-interactively 'org-move-item-up))
19867 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19868 (call-interactively 'org-timestamp-up)))
19869 (t (call-interactively 'org-drag-line-backward))))
19871 (defun org-shiftmetadown (&optional arg)
19872 "Move subtree down or insert table row.
19873 Calls `org-move-subtree-down' or `org-table-insert-row' or
19874 `org-move-item-down' or `org-timestamp-up', depending on context.
19875 See the individual commands for more information."
19876 (interactive "P")
19877 (cond
19878 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19879 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19880 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19881 ((org-at-item-p) (call-interactively 'org-move-item-down))
19882 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19883 (call-interactively 'org-timestamp-down)))
19884 (t (call-interactively 'org-drag-line-forward))))
19886 (defsubst org-hidden-tree-error ()
19887 (user-error
19888 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19890 (defun org-metaleft (&optional arg)
19891 "Promote heading or move table column to left.
19892 Calls `org-do-promote' or `org-table-move-column', depending on context.
19893 With no specific context, calls the Emacs default `backward-word'.
19894 See the individual commands for more information."
19895 (interactive "P")
19896 (cond
19897 ((run-hook-with-args-until-success 'org-metaleft-hook))
19898 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19899 ((org-with-limited-levels
19900 (or (org-at-heading-p)
19901 (and (org-region-active-p)
19902 (save-excursion
19903 (goto-char (region-beginning))
19904 (org-at-heading-p)))))
19905 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19906 (call-interactively 'org-do-promote))
19907 ;; At an inline task.
19908 ((org-at-heading-p)
19909 (call-interactively 'org-inlinetask-promote))
19910 ((or (org-at-item-p)
19911 (and (org-region-active-p)
19912 (save-excursion
19913 (goto-char (region-beginning))
19914 (org-at-item-p))))
19915 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19916 (call-interactively 'org-outdent-item))
19917 (t (call-interactively 'backward-word))))
19919 (defun org-metaright (&optional arg)
19920 "Demote a subtree, a list item or move table column to right.
19921 In front of a drawer or a block keyword, indent it correctly.
19922 With no specific context, calls the Emacs default `forward-word'.
19923 See the individual commands for more information."
19924 (interactive "P")
19925 (cond
19926 ((run-hook-with-args-until-success 'org-metaright-hook))
19927 ((org-at-table-p) (call-interactively 'org-table-move-column))
19928 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19929 ((org-at-block-p) (call-interactively 'org-indent-block))
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-demote))
19938 ;; At an inline task.
19939 ((org-at-heading-p)
19940 (call-interactively 'org-inlinetask-demote))
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-indent-item))
19948 (t (call-interactively 'forward-word))))
19950 (defun org-check-for-hidden (what)
19951 "Check if there are hidden headlines/items in the current visual line.
19952 WHAT can be either `headlines' or `items'. If the current line is
19953 an outline or item heading and it has a folded subtree below it,
19954 this function returns t, nil otherwise."
19955 (let ((re (cond
19956 ((eq what 'headlines) org-outline-regexp-bol)
19957 ((eq what 'items) (org-item-beginning-re))
19958 (t (error "This should not happen"))))
19959 beg end)
19960 (save-excursion
19961 (catch 'exit
19962 (unless (org-region-active-p)
19963 (setq beg (point-at-bol))
19964 (beginning-of-line 2)
19965 (while (and (not (eobp)) ;; this is like `next-line'
19966 (get-char-property (1- (point)) 'invisible))
19967 (beginning-of-line 2))
19968 (setq end (point))
19969 (goto-char beg)
19970 (goto-char (point-at-eol))
19971 (setq end (max end (point)))
19972 (while (re-search-forward re end t)
19973 (if (get-char-property (match-beginning 0) 'invisible)
19974 (throw 'exit t))))
19975 nil))))
19977 (defun org-metaup (&optional arg)
19978 "Move subtree up or move table row up.
19979 Calls `org-move-subtree-up' or `org-table-move-row' or
19980 `org-move-item-up', depending on context. See the individual commands
19981 for more information."
19982 (interactive "P")
19983 (cond
19984 ((run-hook-with-args-until-success 'org-metaup-hook))
19985 ((org-region-active-p)
19986 (let* ((a (min (region-beginning) (region-end)))
19987 (b (1- (max (region-beginning) (region-end))))
19988 (c (save-excursion (goto-char a)
19989 (move-beginning-of-line 0)))
19990 (d (save-excursion (goto-char a)
19991 (move-end-of-line 0) (point))))
19992 (transpose-regions a b c d)
19993 (goto-char c)))
19994 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19995 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19996 ((org-at-item-p) (call-interactively 'org-move-item-up))
19997 (t (org-drag-element-backward))))
19999 (defun org-metadown (&optional arg)
20000 "Move subtree down or move table row down.
20001 Calls `org-move-subtree-down' or `org-table-move-row' or
20002 `org-move-item-down', depending on context. See the individual
20003 commands for more information."
20004 (interactive "P")
20005 (cond
20006 ((run-hook-with-args-until-success 'org-metadown-hook))
20007 ((org-region-active-p)
20008 (let* ((a (min (region-beginning) (region-end)))
20009 (b (max (region-beginning) (region-end)))
20010 (c (save-excursion (goto-char b)
20011 (move-beginning-of-line 1)))
20012 (d (save-excursion (goto-char b)
20013 (move-end-of-line 1) (1+ (point)))))
20014 (transpose-regions a b c d)
20015 (goto-char d)))
20016 ((org-at-table-p) (call-interactively 'org-table-move-row))
20017 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20018 ((org-at-item-p) (call-interactively 'org-move-item-down))
20019 (t (org-drag-element-forward))))
20021 (defun org-shiftup (&optional arg)
20022 "Increase item in timestamp or increase priority of current headline.
20023 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20024 depending on context. See the individual commands for more information."
20025 (interactive "P")
20026 (cond
20027 ((run-hook-with-args-until-success 'org-shiftup-hook))
20028 ((and org-support-shift-select (org-region-active-p))
20029 (org-call-for-shift-select 'previous-line))
20030 ((org-at-timestamp-p t)
20031 (call-interactively (if org-edit-timestamp-down-means-later
20032 'org-timestamp-down 'org-timestamp-up)))
20033 ((and (not (eq org-support-shift-select 'always))
20034 org-enable-priority-commands
20035 (org-at-heading-p))
20036 (call-interactively 'org-priority-up))
20037 ((and (not org-support-shift-select) (org-at-item-p))
20038 (call-interactively 'org-previous-item))
20039 ((org-clocktable-try-shift 'up arg))
20040 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20041 (org-support-shift-select
20042 (org-call-for-shift-select 'previous-line))
20043 (t (org-shiftselect-error))))
20045 (defun org-shiftdown (&optional arg)
20046 "Decrease item in timestamp or decrease priority of current headline.
20047 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20048 depending on context. See the individual commands for more information."
20049 (interactive "P")
20050 (cond
20051 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20052 ((and org-support-shift-select (org-region-active-p))
20053 (org-call-for-shift-select 'next-line))
20054 ((org-at-timestamp-p t)
20055 (call-interactively (if org-edit-timestamp-down-means-later
20056 'org-timestamp-up 'org-timestamp-down)))
20057 ((and (not (eq org-support-shift-select 'always))
20058 org-enable-priority-commands
20059 (org-at-heading-p))
20060 (call-interactively 'org-priority-down))
20061 ((and (not org-support-shift-select) (org-at-item-p))
20062 (call-interactively 'org-next-item))
20063 ((org-clocktable-try-shift 'down arg))
20064 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20065 (org-support-shift-select
20066 (org-call-for-shift-select 'next-line))
20067 (t (org-shiftselect-error))))
20069 (defun org-shiftright (&optional arg)
20070 "Cycle the thing at point or in the current line, depending on context.
20071 Depending on context, this does one of the following:
20073 - switch a timestamp at point one day into the future
20074 - on a headline, switch to the next TODO keyword.
20075 - on an item, switch entire list to the next bullet type
20076 - on a property line, switch to the next allowed value
20077 - on a clocktable definition line, move time block into the future"
20078 (interactive "P")
20079 (cond
20080 ((run-hook-with-args-until-success 'org-shiftright-hook))
20081 ((and org-support-shift-select (org-region-active-p))
20082 (org-call-for-shift-select 'forward-char))
20083 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20084 ((and (not (eq org-support-shift-select 'always))
20085 (org-at-heading-p))
20086 (let ((org-inhibit-logging
20087 (not org-treat-S-cursor-todo-selection-as-state-change))
20088 (org-inhibit-blocking
20089 (not org-treat-S-cursor-todo-selection-as-state-change)))
20090 (org-call-with-arg 'org-todo 'right)))
20091 ((or (and org-support-shift-select
20092 (not (eq org-support-shift-select 'always))
20093 (org-at-item-bullet-p))
20094 (and (not org-support-shift-select) (org-at-item-p)))
20095 (org-call-with-arg 'org-cycle-list-bullet nil))
20096 ((and (not (eq org-support-shift-select 'always))
20097 (org-at-property-p))
20098 (call-interactively 'org-property-next-allowed-value))
20099 ((org-clocktable-try-shift 'right arg))
20100 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20101 (org-support-shift-select
20102 (org-call-for-shift-select 'forward-char))
20103 (t (org-shiftselect-error))))
20105 (defun org-shiftleft (&optional arg)
20106 "Cycle the thing at point or in the current line, depending on context.
20107 Depending on context, this does one of the following:
20109 - switch a timestamp at point one day into the past
20110 - on a headline, switch to the previous TODO keyword.
20111 - on an item, switch entire list to the previous bullet type
20112 - on a property line, switch to the previous allowed value
20113 - on a clocktable definition line, move time block into the past"
20114 (interactive "P")
20115 (cond
20116 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20117 ((and org-support-shift-select (org-region-active-p))
20118 (org-call-for-shift-select 'backward-char))
20119 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20120 ((and (not (eq org-support-shift-select 'always))
20121 (org-at-heading-p))
20122 (let ((org-inhibit-logging
20123 (not org-treat-S-cursor-todo-selection-as-state-change))
20124 (org-inhibit-blocking
20125 (not org-treat-S-cursor-todo-selection-as-state-change)))
20126 (org-call-with-arg 'org-todo 'left)))
20127 ((or (and org-support-shift-select
20128 (not (eq org-support-shift-select 'always))
20129 (org-at-item-bullet-p))
20130 (and (not org-support-shift-select) (org-at-item-p)))
20131 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20132 ((and (not (eq org-support-shift-select 'always))
20133 (org-at-property-p))
20134 (call-interactively 'org-property-previous-allowed-value))
20135 ((org-clocktable-try-shift 'left arg))
20136 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20137 (org-support-shift-select
20138 (org-call-for-shift-select 'backward-char))
20139 (t (org-shiftselect-error))))
20141 (defun org-shiftcontrolright ()
20142 "Switch to next TODO set."
20143 (interactive)
20144 (cond
20145 ((and org-support-shift-select (org-region-active-p))
20146 (org-call-for-shift-select 'forward-word))
20147 ((and (not (eq org-support-shift-select 'always))
20148 (org-at-heading-p))
20149 (org-call-with-arg 'org-todo 'nextset))
20150 (org-support-shift-select
20151 (org-call-for-shift-select 'forward-word))
20152 (t (org-shiftselect-error))))
20154 (defun org-shiftcontrolleft ()
20155 "Switch to previous TODO set."
20156 (interactive)
20157 (cond
20158 ((and org-support-shift-select (org-region-active-p))
20159 (org-call-for-shift-select 'backward-word))
20160 ((and (not (eq org-support-shift-select 'always))
20161 (org-at-heading-p))
20162 (org-call-with-arg 'org-todo 'previousset))
20163 (org-support-shift-select
20164 (org-call-for-shift-select 'backward-word))
20165 (t (org-shiftselect-error))))
20167 (defun org-shiftcontrolup (&optional n)
20168 "Change timestamps synchronously up in CLOCK log lines.
20169 Optional argument N tells to change by that many units."
20170 (interactive "P")
20171 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20172 (let (org-support-shift-select)
20173 (org-clock-timestamps-up n))
20174 (user-error "Not at a clock log")))
20176 (defun org-shiftcontroldown (&optional n)
20177 "Change timestamps synchronously down in CLOCK log lines.
20178 Optional argument N tells to change by that many units."
20179 (interactive "P")
20180 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20181 (let (org-support-shift-select)
20182 (org-clock-timestamps-down n))
20183 (user-error "Not at a clock log")))
20185 (defun org-ctrl-c-ret ()
20186 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20187 (interactive)
20188 (cond
20189 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20190 (t (call-interactively 'org-insert-heading))))
20192 (defun org-find-visible ()
20193 (let ((s (point)))
20194 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20195 (get-char-property s 'invisible)))
20197 (defun org-find-invisible ()
20198 (let ((s (point)))
20199 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20200 (not (get-char-property s 'invisible))))
20203 (defun org-copy-visible (beg end)
20204 "Copy the visible parts of the region."
20205 (interactive "r")
20206 (let (snippets s)
20207 (save-excursion
20208 (save-restriction
20209 (narrow-to-region beg end)
20210 (setq s (goto-char (point-min)))
20211 (while (not (= (point) (point-max)))
20212 (goto-char (org-find-invisible))
20213 (push (buffer-substring s (point)) snippets)
20214 (setq s (goto-char (org-find-visible))))))
20215 (kill-new (apply 'concat (nreverse snippets)))))
20217 (defun org-copy-special ()
20218 "Copy region in table or copy current subtree.
20219 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20220 See the individual commands for more information."
20221 (interactive)
20222 (call-interactively
20223 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20225 (defun org-cut-special ()
20226 "Cut region in table or cut current subtree.
20227 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20228 See the individual commands for more information."
20229 (interactive)
20230 (call-interactively
20231 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20233 (defun org-paste-special (arg)
20234 "Paste rectangular region into table, or past subtree relative to level.
20235 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20236 See the individual commands for more information."
20237 (interactive "P")
20238 (if (org-at-table-p)
20239 (org-table-paste-rectangle)
20240 (org-paste-subtree arg)))
20242 (defsubst org-in-fixed-width-region-p ()
20243 "Is point in a fixed-width region?"
20244 (save-match-data
20245 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20247 (defun org-edit-special (&optional arg)
20248 "Call a special editor for the element at point.
20249 When at a table, call the formula editor with `org-table-edit-formulas'.
20250 When in a source code block, call `org-edit-src-code'.
20251 When in a fixed-width region, call `org-edit-fixed-width-region'.
20252 When at an #+INCLUDE keyword, visit the included file.
20253 On a link, call `ffap' to visit the link at point.
20254 Otherwise, return a user error."
20255 (interactive "P")
20256 (let ((element (org-element-at-point)))
20257 (assert (not buffer-read-only) nil
20258 "Buffer is read-only: %s" (buffer-name))
20259 (case (org-element-type element)
20260 (src-block
20261 (if (not arg) (org-edit-src-code)
20262 (let* ((info (org-babel-get-src-block-info))
20263 (lang (nth 0 info))
20264 (params (nth 2 info))
20265 (session (cdr (assq :session params))))
20266 (if (not session) (org-edit-src-code)
20267 ;; At a src-block with a session and function called with
20268 ;; an ARG: switch to the buffer related to the inferior
20269 ;; process.
20270 (switch-to-buffer
20271 (funcall (intern (concat "org-babel-prep-session:" lang))
20272 session params))))))
20273 (keyword
20274 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20275 (find-file-other-window
20276 (org-remove-double-quotes
20277 (car (org-split-string (org-element-property :value element)))))
20278 (user-error "No special environment to edit here")))
20279 (table
20280 (if (eq (org-element-property :type element) 'table.el)
20281 (org-edit-src-code)
20282 (call-interactively 'org-table-edit-formulas)))
20283 ;; Only Org tables contain `table-row' type elements.
20284 (table-row (call-interactively 'org-table-edit-formulas))
20285 ((example-block export-block) (org-edit-src-code))
20286 (fixed-width (org-edit-fixed-width-region))
20287 (otherwise
20288 ;; No notable element at point. Though, we may be at a link,
20289 ;; which is an object. Thus, scan deeper.
20290 (if (eq (org-element-type (org-element-context element)) 'link)
20291 (call-interactively 'ffap)
20292 (user-error "No special environment to edit here"))))))
20294 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20295 (defun org-ctrl-c-ctrl-c (&optional arg)
20296 "Set tags in headline, or update according to changed information at point.
20298 This command does many different things, depending on context:
20300 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20301 this is what we do.
20303 - If the cursor is on a statistics cookie, update it.
20305 - If the cursor is in a headline, prompt for tags and insert them
20306 into the current line, aligned to `org-tags-column'. When called
20307 with prefix arg, realign all tags in the current buffer.
20309 - If the cursor is in one of the special #+KEYWORD lines, this
20310 triggers scanning the buffer for these lines and updating the
20311 information.
20313 - If the cursor is inside a table, realign the table. This command
20314 works even if the automatic table editor has been turned off.
20316 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20317 the entire table.
20319 - If the cursor is at a footnote reference or definition, jump to
20320 the corresponding definition or references, respectively.
20322 - If the cursor is a the beginning of a dynamic block, update it.
20324 - If the current buffer is a capture buffer, close note and file it.
20326 - If the cursor is on a <<<target>>>, update radio targets and
20327 corresponding links in this buffer.
20329 - If the cursor is on a numbered item in a plain list, renumber the
20330 ordered list.
20332 - If the cursor is on a checkbox, toggle it.
20334 - If the cursor is on a code block, evaluate it. The variable
20335 `org-confirm-babel-evaluate' can be used to control prompting
20336 before code block evaluation, by default every code block
20337 evaluation requires confirmation. Code block evaluation can be
20338 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20339 (interactive "P")
20340 (cond
20341 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20342 org-occur-highlights
20343 org-latex-fragment-image-overlays)
20344 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20345 (org-remove-occur-highlights)
20346 (org-remove-latex-fragment-image-overlays)
20347 (message "Temporary highlights/overlays removed from current buffer"))
20348 ((and (local-variable-p 'org-finish-function (current-buffer))
20349 (fboundp org-finish-function))
20350 (funcall org-finish-function))
20351 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20353 (let* ((context (org-element-context)) (type (org-element-type context)))
20354 ;; Test if point is within a blank line.
20355 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20356 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20357 (user-error "C-c C-c can do nothing useful at this location"))
20358 (case type
20359 ;; When at a link, act according to the parent instead.
20360 (link (setq context (org-element-property :parent context))
20361 (setq type (org-element-type context)))
20362 ;; Unsupported object types: check parent element instead.
20363 ((bold code entity export-snippet inline-babel-call inline-src-block
20364 italic latex-fragment line-break macro strike-through subscript
20365 superscript underline verbatim)
20366 (while (and (setq context (org-element-property :parent context))
20367 (not (memq (setq type (org-element-type context))
20368 '(paragraph verse-block table-cell)))))))
20369 ;; For convenience: at the first line of a paragraph on the
20370 ;; same line as an item, apply function on that item instead.
20371 (when (eq type 'paragraph)
20372 (let ((parent (org-element-property :parent context)))
20373 (when (and (eq (org-element-type parent) 'item)
20374 (= (point-at-bol) (org-element-property :begin parent)))
20375 (setq context parent type 'item))))
20376 ;; Act according to type of element or object at point.
20377 (case type
20378 (clock (org-clock-update-time-maybe))
20379 (dynamic-block
20380 (save-excursion
20381 (goto-char (org-element-property :post-affiliated context))
20382 (org-update-dblock)))
20383 (footnote-definition
20384 (goto-char (org-element-property :post-affiliated context))
20385 (call-interactively 'org-footnote-action))
20386 (footnote-reference (call-interactively 'org-footnote-action))
20387 ((headline inlinetask)
20388 (save-excursion (goto-char (org-element-property :begin context))
20389 (call-interactively 'org-set-tags)))
20390 (item
20391 ;; At an item: a double C-u set checkbox to "[-]"
20392 ;; unconditionally, whereas a single one will toggle its
20393 ;; presence. Without an universal argument, if the item
20394 ;; has a checkbox, toggle it. Otherwise repair the list.
20395 (let* ((box (org-element-property :checkbox context))
20396 (struct (org-element-property :structure context))
20397 (old-struct (copy-tree struct))
20398 (parents (org-list-parents-alist struct))
20399 (prevs (org-list-prevs-alist struct))
20400 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20401 (org-list-set-checkbox
20402 (org-element-property :begin context) struct
20403 (cond ((equal arg '(16)) "[-]")
20404 ((and (not box) (equal arg '(4))) "[ ]")
20405 ((or (not box) (equal arg '(4))) nil)
20406 ((eq box 'on) "[ ]")
20407 (t "[X]")))
20408 ;; Mimic `org-list-write-struct' but with grabbing
20409 ;; a return value from `org-list-struct-fix-box'.
20410 (org-list-struct-fix-ind struct parents 2)
20411 (org-list-struct-fix-item-end struct)
20412 (org-list-struct-fix-bul struct prevs)
20413 (org-list-struct-fix-ind struct parents)
20414 (let ((block-item
20415 (org-list-struct-fix-box struct parents prevs orderedp)))
20416 (if (and box (equal struct old-struct))
20417 (if (equal arg '(16))
20418 (message "Checkboxes already reset")
20419 (user-error "Cannot toggle this checkbox: %s"
20420 (if (eq box 'on)
20421 "all subitems checked"
20422 "unchecked subitems")))
20423 (org-list-struct-apply-struct struct old-struct)
20424 (org-update-checkbox-count-maybe))
20425 (when block-item
20426 (message "Checkboxes were removed due to empty box at line %d"
20427 (org-current-line block-item))))))
20428 (keyword
20429 (let ((org-inhibit-startup-visibility-stuff t)
20430 (org-startup-align-all-tables nil))
20431 (when (boundp 'org-table-coordinate-overlays)
20432 (mapc 'delete-overlay org-table-coordinate-overlays)
20433 (setq org-table-coordinate-overlays nil))
20434 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20435 (message "Local setup has been refreshed"))
20436 (plain-list
20437 ;; At a plain list, with a double C-u argument, set
20438 ;; checkboxes of each item to "[-]", whereas a single one
20439 ;; will toggle their presence according to the state of the
20440 ;; first item in the list. Without an argument, repair the
20441 ;; list.
20442 (let* ((begin (org-element-property :contents-begin context))
20443 (beginm (move-marker (make-marker) begin))
20444 (struct (org-element-property :structure context))
20445 (old-struct (copy-tree struct))
20446 (first-box (save-excursion
20447 (goto-char begin)
20448 (looking-at org-list-full-item-re)
20449 (match-string-no-properties 3)))
20450 (new-box (cond ((equal arg '(16)) "[-]")
20451 ((equal arg '(4)) (unless first-box "[ ]"))
20452 ((equal first-box "[X]") "[ ]")
20453 (t "[X]"))))
20454 (cond
20455 (arg
20456 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20457 (org-list-get-all-items
20458 begin struct (org-list-prevs-alist struct))))
20459 ((and first-box (eq (point) begin))
20460 ;; For convenience, when point is at bol on the first
20461 ;; item of the list and no argument is provided, simply
20462 ;; toggle checkbox of that item, if any.
20463 (org-list-set-checkbox begin struct new-box)))
20464 (org-list-write-struct
20465 struct (org-list-parents-alist struct) old-struct)
20466 (org-update-checkbox-count-maybe)
20467 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20468 ((property-drawer node-property)
20469 (call-interactively 'org-property-action))
20470 ((radio-target target)
20471 (call-interactively 'org-update-radio-target-regexp))
20472 (statistics-cookie
20473 (call-interactively 'org-update-statistics-cookies))
20474 ((table table-cell table-row)
20475 ;; At a table, recalculate every field and align it. Also
20476 ;; send the table if necessary. If the table has
20477 ;; a `table.el' type, just give up. At a table row or
20478 ;; cell, maybe recalculate line but always align table.
20479 (if (eq (org-element-property :type context) 'table.el)
20480 (message "Use C-c ' to edit table.el tables")
20481 (let ((org-enable-table-editor t))
20482 (if (or (eq type 'table)
20483 ;; Check if point is at a TBLFM line.
20484 (and (eq type 'table-row)
20485 (= (point) (org-element-property :end context))))
20486 (save-excursion
20487 (if (org-at-TBLFM-p)
20488 (progn (require 'org-table)
20489 (org-table-calc-current-TBLFM))
20490 (goto-char (org-element-property :contents-begin context))
20491 (org-call-with-arg 'org-table-recalculate (or arg t))
20492 (orgtbl-send-table 'maybe)))
20493 (org-table-maybe-eval-formula)
20494 (cond (arg (call-interactively 'org-table-recalculate))
20495 ((org-table-maybe-recalculate-line))
20496 (t (org-table-align)))))))
20497 (timestamp (org-timestamp-change 0 'day))
20498 (otherwise
20499 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20500 (user-error
20501 "C-c C-c can do nothing useful at this location")))))))))
20503 (defun org-mode-restart ()
20504 (interactive)
20505 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20506 (funcall major-mode)
20507 (hack-local-variables)
20508 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20509 (org-indent-mode -1)))
20510 (message "%s restarted" major-mode))
20512 (defun org-kill-note-or-show-branches ()
20513 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20514 (interactive)
20515 (if (not org-finish-function)
20516 (progn
20517 (hide-subtree)
20518 (call-interactively 'show-branches))
20519 (let ((org-note-abort t))
20520 (funcall org-finish-function))))
20522 (defun org-open-line (n)
20523 "Insert a new row in tables, call `open-line' elsewhere.
20524 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20525 (interactive "*p")
20526 (cond
20527 ((not org-special-ctrl-o)
20528 (open-line n))
20529 ((org-at-table-p)
20530 (org-table-insert-row))
20532 (open-line n))))
20534 (defun org-return (&optional indent)
20535 "Goto next table row or insert a newline.
20536 Calls `org-table-next-row' or `newline', depending on context.
20537 See the individual commands for more information."
20538 (interactive)
20539 (let (org-ts-what)
20540 (cond
20541 ((or (bobp) (org-in-src-block-p))
20542 (if indent (newline-and-indent) (newline)))
20543 ((org-at-table-p)
20544 (org-table-justify-field-maybe)
20545 (call-interactively 'org-table-next-row))
20546 ;; when `newline-and-indent' is called within a list, make sure
20547 ;; text moved stays inside the item.
20548 ((and (org-in-item-p) indent)
20549 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20550 (progn
20551 (save-match-data (newline))
20552 (org-indent-line-to (length (match-string 0))))
20553 (let ((ind (org-get-indentation)))
20554 (newline)
20555 (if (org-looking-back org-list-end-re)
20556 (org-indent-line)
20557 (org-indent-line-to ind)))))
20558 ((and org-return-follows-link
20559 (org-at-timestamp-p t)
20560 (not (eq org-ts-what 'after)))
20561 (org-follow-timestamp-link))
20562 ((and org-return-follows-link
20563 (let ((tprop (get-text-property (point) 'face)))
20564 (or (eq tprop 'org-link)
20565 (and (listp tprop) (memq 'org-link tprop)))))
20566 (call-interactively 'org-open-at-point))
20567 ((and (org-at-heading-p)
20568 (looking-at
20569 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20570 (org-show-entry)
20571 (end-of-line 1)
20572 (newline))
20573 (t (if indent (newline-and-indent) (newline))))))
20575 (defun org-return-indent ()
20576 "Goto next table row or insert a newline and indent.
20577 Calls `org-table-next-row' or `newline-and-indent', depending on
20578 context. See the individual commands for more information."
20579 (interactive)
20580 (org-return t))
20582 (defun org-ctrl-c-star ()
20583 "Compute table, or change heading status of lines.
20584 Calls `org-table-recalculate' or `org-toggle-heading',
20585 depending on context."
20586 (interactive)
20587 (cond
20588 ((org-at-table-p)
20589 (call-interactively 'org-table-recalculate))
20591 ;; Convert all lines in region to list items
20592 (call-interactively 'org-toggle-heading))))
20594 (defun org-ctrl-c-minus ()
20595 "Insert separator line in table or modify bullet status of line.
20596 Also turns a plain line or a region of lines into list items.
20597 Calls `org-table-insert-hline', `org-toggle-item', or
20598 `org-cycle-list-bullet', depending on context."
20599 (interactive)
20600 (cond
20601 ((org-at-table-p)
20602 (call-interactively 'org-table-insert-hline))
20603 ((org-region-active-p)
20604 (call-interactively 'org-toggle-item))
20605 ((org-in-item-p)
20606 (call-interactively 'org-cycle-list-bullet))
20608 (call-interactively 'org-toggle-item))))
20610 (defun org-toggle-item (arg)
20611 "Convert headings or normal lines to items, items to normal lines.
20612 If there is no active region, only the current line is considered.
20614 If the first non blank line in the region is a headline, convert
20615 all headlines to items, shifting text accordingly.
20617 If it is an item, convert all items to normal lines.
20619 If it is normal text, change region into a list of items.
20620 With a prefix argument ARG, change the region in a single item."
20621 (interactive "P")
20622 (let ((shift-text
20623 (function
20624 ;; Shift text in current section to IND, from point to END.
20625 ;; The function leaves point to END line.
20626 (lambda (ind end)
20627 (let ((min-i 1000) (end (copy-marker end)))
20628 ;; First determine the minimum indentation (MIN-I) of
20629 ;; the text.
20630 (save-excursion
20631 (catch 'exit
20632 (while (< (point) end)
20633 (let ((i (org-get-indentation)))
20634 (cond
20635 ;; Skip blank lines and inline tasks.
20636 ((looking-at "^[ \t]*$"))
20637 ((looking-at org-outline-regexp-bol))
20638 ;; We can't find less than 0 indentation.
20639 ((zerop i) (throw 'exit (setq min-i 0)))
20640 ((< i min-i) (setq min-i i))))
20641 (forward-line))))
20642 ;; Then indent each line so that a line indented to
20643 ;; MIN-I becomes indented to IND. Ignore blank lines
20644 ;; and inline tasks in the process.
20645 (let ((delta (- ind min-i)))
20646 (while (< (point) end)
20647 (unless (or (looking-at "^[ \t]*$")
20648 (looking-at org-outline-regexp-bol))
20649 (org-indent-line-to (+ (org-get-indentation) delta)))
20650 (forward-line)))))))
20651 (skip-blanks
20652 (function
20653 ;; Return beginning of first non-blank line, starting from
20654 ;; line at POS.
20655 (lambda (pos)
20656 (save-excursion
20657 (goto-char pos)
20658 (skip-chars-forward " \r\t\n")
20659 (point-at-bol)))))
20660 beg end)
20661 ;; Determine boundaries of changes.
20662 (if (org-region-active-p)
20663 (setq beg (funcall skip-blanks (region-beginning))
20664 end (copy-marker (region-end)))
20665 (setq beg (funcall skip-blanks (point-at-bol))
20666 end (copy-marker (point-at-eol))))
20667 ;; Depending on the starting line, choose an action on the text
20668 ;; between BEG and END.
20669 (org-with-limited-levels
20670 (save-excursion
20671 (goto-char beg)
20672 (cond
20673 ;; Case 1. Start at an item: de-itemize. Note that it only
20674 ;; happens when a region is active: `org-ctrl-c-minus'
20675 ;; would call `org-cycle-list-bullet' otherwise.
20676 ((org-at-item-p)
20677 (while (< (point) end)
20678 (when (org-at-item-p)
20679 (skip-chars-forward " \t")
20680 (delete-region (point) (match-end 0)))
20681 (forward-line)))
20682 ;; Case 2. Start at an heading: convert to items.
20683 ((org-at-heading-p)
20684 (let* ((bul (org-list-bullet-string "-"))
20685 (bul-len (length bul))
20686 (done (org-entry-is-done-p))
20687 (todo (org-entry-is-todo-p))
20688 ;; Indentation of the first heading. It should be
20689 ;; relative to the indentation of its parent, if any.
20690 (start-ind (save-excursion
20691 (cond
20692 ((not org-adapt-indentation) 0)
20693 ((not (outline-previous-heading)) 0)
20694 (t (length (match-string 0))))))
20695 ;; Level of first heading. Further headings will be
20696 ;; compared to it to determine hierarchy in the list.
20697 (ref-level (org-reduced-level (org-outline-level))))
20698 (when (or done todo) (org-todo ""))
20699 (while (< (point) end)
20700 (let* ((level (org-reduced-level (org-outline-level)))
20701 (delta (max 0 (- level ref-level))))
20702 ;; If current headline is less indented than the first
20703 ;; one, set it as reference, in order to preserve
20704 ;; subtrees.
20705 (when (< level ref-level) (setq ref-level level))
20706 (replace-match bul t t)
20707 (org-indent-line-to (+ start-ind (* delta bul-len)))
20708 (when (or done todo)
20709 (let* ((struct (org-list-struct))
20710 (old (copy-tree struct)))
20711 (org-list-set-checkbox (line-beginning-position)
20712 struct
20713 (if done "[X]" "[ ]"))
20714 (org-list-write-struct struct
20715 (org-list-parents-alist struct)
20716 old)))
20717 ;; Ensure all text down to END (or SECTION-END) belongs
20718 ;; to the newly created item.
20719 (let ((section-end (save-excursion
20720 (or (outline-next-heading) (point)))))
20721 (forward-line)
20722 (funcall shift-text
20723 (+ start-ind (* (1+ delta) bul-len))
20724 (min end section-end)))))))
20725 ;; Case 3. Normal line with ARG: make the first line of region
20726 ;; an item, and shift indentation of others lines to
20727 ;; set them as item's body.
20728 (arg (let* ((bul (org-list-bullet-string "-"))
20729 (bul-len (length bul))
20730 (ref-ind (org-get-indentation)))
20731 (skip-chars-forward " \t")
20732 (insert bul)
20733 (forward-line)
20734 (while (< (point) end)
20735 ;; Ensure that lines less indented than first one
20736 ;; still get included in item body.
20737 (funcall shift-text
20738 (+ ref-ind bul-len)
20739 (min end (save-excursion (or (outline-next-heading)
20740 (point)))))
20741 (forward-line))))
20742 ;; Case 4. Normal line without ARG: turn each non-item line
20743 ;; into an item.
20745 (while (< (point) end)
20746 (unless (or (org-at-heading-p) (org-at-item-p))
20747 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20748 (replace-match
20749 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20750 (forward-line))))))))
20752 (defun org-toggle-heading (&optional nstars)
20753 "Convert headings to normal text, or items or text to headings.
20754 If there is no active region, only convert the current line.
20756 With a \\[universal-argument] prefix, convert the whole list at
20757 point into heading.
20759 In a region:
20761 - If the first non blank line is a headline, remove the stars
20762 from all headlines in the region.
20764 - If it is a normal line, turn each and every normal line (i.e.,
20765 not an heading or an item) in the region into headings. If you
20766 want to convert only the first line of this region, use one
20767 universal prefix argument.
20769 - If it is a plain list item, turn all plain list items into headings.
20771 When converting a line into a heading, the number of stars is chosen
20772 such that the lines become children of the current entry. However,
20773 when a numeric prefix argument is given, its value determines the
20774 number of stars to add."
20775 (interactive "P")
20776 (let ((skip-blanks
20777 (function
20778 ;; Return beginning of first non-blank line, starting from
20779 ;; line at POS.
20780 (lambda (pos)
20781 (save-excursion
20782 (goto-char pos)
20783 (while (org-at-comment-p) (forward-line))
20784 (skip-chars-forward " \r\t\n")
20785 (point-at-bol)))))
20786 beg end toggled)
20787 ;; Determine boundaries of changes. If a universal prefix has
20788 ;; been given, put the list in a region. If region ends at a bol,
20789 ;; do not consider the last line to be in the region.
20791 (when (and current-prefix-arg (org-at-item-p))
20792 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20793 (org-mark-element))
20795 (if (org-region-active-p)
20796 (setq beg (funcall skip-blanks (region-beginning))
20797 end (copy-marker (save-excursion
20798 (goto-char (region-end))
20799 (if (bolp) (point) (point-at-eol)))))
20800 (setq beg (funcall skip-blanks (point-at-bol))
20801 end (copy-marker (point-at-eol))))
20802 ;; Ensure inline tasks don't count as headings.
20803 (org-with-limited-levels
20804 (save-excursion
20805 (goto-char beg)
20806 (cond
20807 ;; Case 1. Started at an heading: de-star headings.
20808 ((org-at-heading-p)
20809 (while (< (point) end)
20810 (when (org-at-heading-p t)
20811 (looking-at org-outline-regexp) (replace-match "")
20812 (setq toggled t))
20813 (forward-line)))
20814 ;; Case 2. Started at an item: change items into headlines.
20815 ;; One star will be added by `org-list-to-subtree'.
20816 ((org-at-item-p)
20817 (let* ((stars (make-string
20818 ;; subtract the star that will be added again by
20819 ;; `org-list-to-subtree'
20820 (if (numberp nstars) (1- nstars)
20821 (or (org-current-level) 0))
20822 ?*))
20823 (add-stars
20824 (cond (nstars "") ; stars from prefix only
20825 ((equal stars "") "") ; before first heading
20826 (org-odd-levels-only "*") ; inside heading, odd
20827 (t "")))) ; inside heading, oddeven
20828 (while (< (point) end)
20829 (when (org-at-item-p)
20830 ;; Pay attention to cases when region ends before list.
20831 (let* ((struct (org-list-struct))
20832 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20833 (save-restriction
20834 (narrow-to-region (point) list-end)
20835 (insert
20836 (org-list-to-subtree
20837 (org-list-parse-list t)
20838 '(:istart (concat stars add-stars (funcall get-stars depth))
20839 :icount (concat stars add-stars (funcall get-stars depth)))))))
20840 (setq toggled t))
20841 (forward-line))))
20842 ;; Case 3. Started at normal text: make every line an heading,
20843 ;; skipping headlines and items.
20844 (t (let* ((stars
20845 (make-string
20846 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20847 (add-stars
20848 (cond (nstars "") ; stars from prefix only
20849 ((equal stars "") "*") ; before first heading
20850 (org-odd-levels-only "**") ; inside heading, odd
20851 (t "*"))) ; inside heading, oddeven
20852 (rpl (concat stars add-stars " "))
20853 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20854 (while (< (point) (if (equal nstars '(4)) lend end))
20855 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20856 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20857 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20858 (forward-line)))))))
20859 (unless toggled (message "Cannot toggle heading from here"))))
20861 (defun org-meta-return (&optional arg)
20862 "Insert a new heading or wrap a region in a table.
20863 Calls `org-insert-heading' or `org-table-wrap-region', depending
20864 on context. See the individual commands for more information."
20865 (interactive "P")
20866 (org-check-before-invisible-edit 'insert)
20867 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20868 (let* ((element (org-element-at-point))
20869 (type (org-element-type element)))
20870 (when (eq type 'table-row)
20871 (setq element (org-element-property :parent element))
20872 (setq type 'table))
20873 (if (and (eq type 'table)
20874 (eq (org-element-property :type element) 'org)
20875 (>= (point) (org-element-property :contents-begin element))
20876 (< (point) (org-element-property :contents-end element)))
20877 (call-interactively 'org-table-wrap-region)
20878 (call-interactively 'org-insert-heading)))))
20880 ;;; Menu entries
20882 (defsubst org-in-subtree-not-table-p ()
20883 "Are we in a subtree and not in a table?"
20884 (and (not (org-before-first-heading-p))
20885 (not (org-at-table-p))))
20887 ;; Define the Org-mode menus
20888 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20889 '("Tbl"
20890 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20891 ["Next Field" org-cycle (org-at-table-p)]
20892 ["Previous Field" org-shifttab (org-at-table-p)]
20893 ["Next Row" org-return (org-at-table-p)]
20894 "--"
20895 ["Blank Field" org-table-blank-field (org-at-table-p)]
20896 ["Edit Field" org-table-edit-field (org-at-table-p)]
20897 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20898 "--"
20899 ("Column"
20900 ["Move Column Left" org-metaleft (org-at-table-p)]
20901 ["Move Column Right" org-metaright (org-at-table-p)]
20902 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20903 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20904 ("Row"
20905 ["Move Row Up" org-metaup (org-at-table-p)]
20906 ["Move Row Down" org-metadown (org-at-table-p)]
20907 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20908 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20909 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20910 "--"
20911 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20912 ("Rectangle"
20913 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20914 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20915 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20916 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20917 "--"
20918 ("Calculate"
20919 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20920 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20921 ["Edit Formulas" org-edit-special (org-at-table-p)]
20922 "--"
20923 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20924 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20925 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20926 "--"
20927 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20928 "--"
20929 ["Sum Column/Rectangle" org-table-sum
20930 (or (org-at-table-p) (org-region-active-p))]
20931 ["Which Column?" org-table-current-column (org-at-table-p)])
20932 ["Debug Formulas"
20933 org-table-toggle-formula-debugger
20934 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20935 ["Show Col/Row Numbers"
20936 org-table-toggle-coordinate-overlays
20937 :style toggle
20938 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20939 "--"
20940 ["Create" org-table-create (and (not (org-at-table-p))
20941 org-enable-table-editor)]
20942 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20943 ["Import from File" org-table-import (not (org-at-table-p))]
20944 ["Export to File" org-table-export (org-at-table-p)]
20945 "--"
20946 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20948 (easy-menu-define org-org-menu org-mode-map "Org menu"
20949 '("Org"
20950 ("Show/Hide"
20951 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20952 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20953 ["Sparse Tree..." org-sparse-tree t]
20954 ["Reveal Context" org-reveal t]
20955 ["Show All" show-all t]
20956 "--"
20957 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20958 "--"
20959 ["New Heading" org-insert-heading t]
20960 ("Navigate Headings"
20961 ["Up" outline-up-heading t]
20962 ["Next" outline-next-visible-heading t]
20963 ["Previous" outline-previous-visible-heading t]
20964 ["Next Same Level" outline-forward-same-level t]
20965 ["Previous Same Level" outline-backward-same-level t]
20966 "--"
20967 ["Jump" org-goto t])
20968 ("Edit Structure"
20969 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20970 "--"
20971 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20972 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20973 "--"
20974 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20975 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20976 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20977 "--"
20978 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20979 "--"
20980 ["Copy visible text" org-copy-visible t]
20981 "--"
20982 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20983 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20984 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20985 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20986 "--"
20987 ["Sort Region/Children" org-sort t]
20988 "--"
20989 ["Convert to odd levels" org-convert-to-odd-levels t]
20990 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20991 ("Editing"
20992 ["Emphasis..." org-emphasize t]
20993 ["Edit Source Example" org-edit-special t]
20994 "--"
20995 ["Footnote new/jump" org-footnote-action t]
20996 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20997 ("Archive"
20998 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20999 "--"
21000 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21001 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21002 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21004 "--"
21005 ("Hyperlinks"
21006 ["Store Link (Global)" org-store-link t]
21007 ["Find existing link to here" org-occur-link-in-agenda-files t]
21008 ["Insert Link" org-insert-link t]
21009 ["Follow Link" org-open-at-point t]
21010 "--"
21011 ["Next link" org-next-link t]
21012 ["Previous link" org-previous-link t]
21013 "--"
21014 ["Descriptive Links"
21015 org-toggle-link-display
21016 :style radio
21017 :selected org-descriptive-links
21019 ["Literal Links"
21020 org-toggle-link-display
21021 :style radio
21022 :selected (not org-descriptive-links)])
21023 "--"
21024 ("TODO Lists"
21025 ["TODO/DONE/-" org-todo t]
21026 ("Select keyword"
21027 ["Next keyword" org-shiftright (org-at-heading-p)]
21028 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21029 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21030 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21031 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21032 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21033 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21034 "--"
21035 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21036 :selected org-enforce-todo-dependencies :style toggle :active t]
21037 "Settings for tree at point"
21038 ["Do Children sequentially" org-toggle-ordered-property :style radio
21039 :selected (org-entry-get nil "ORDERED")
21040 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21041 ["Do Children parallel" org-toggle-ordered-property :style radio
21042 :selected (not (org-entry-get nil "ORDERED"))
21043 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21044 "--"
21045 ["Set Priority" org-priority t]
21046 ["Priority Up" org-shiftup t]
21047 ["Priority Down" org-shiftdown t]
21048 "--"
21049 ["Get news from all feeds" org-feed-update-all t]
21050 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21051 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21052 ("TAGS and Properties"
21053 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21054 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21055 "--"
21056 ["Set property" org-set-property (not (org-before-first-heading-p))]
21057 ["Column view of properties" org-columns t]
21058 ["Insert Column View DBlock" org-insert-columns-dblock t])
21059 ("Dates and Scheduling"
21060 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21061 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21062 ("Change Date"
21063 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21064 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21065 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21066 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21067 ["Compute Time Range" org-evaluate-time-range t]
21068 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21069 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21070 "--"
21071 ["Custom time format" org-toggle-time-stamp-overlays
21072 :style radio :selected org-display-custom-times]
21073 "--"
21074 ["Goto Calendar" org-goto-calendar t]
21075 ["Date from Calendar" org-date-from-calendar t]
21076 "--"
21077 ["Start/Restart Timer" org-timer-start t]
21078 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21079 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21080 ["Insert Timer String" org-timer t]
21081 ["Insert Timer Item" org-timer-item t])
21082 ("Logging work"
21083 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21084 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21085 ["Clock out" org-clock-out t]
21086 ["Clock cancel" org-clock-cancel t]
21087 "--"
21088 ["Mark as default task" org-clock-mark-default-task t]
21089 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21090 ["Goto running clock" org-clock-goto t]
21091 "--"
21092 ["Display times" org-clock-display t]
21093 ["Create clock table" org-clock-report t]
21094 "--"
21095 ["Record DONE time"
21096 (progn (setq org-log-done (not org-log-done))
21097 (message "Switching to %s will %s record a timestamp"
21098 (car org-done-keywords)
21099 (if org-log-done "automatically" "not")))
21100 :style toggle :selected org-log-done])
21101 "--"
21102 ["Agenda Command..." org-agenda t]
21103 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21104 ("File List for Agenda")
21105 ("Special views current file"
21106 ["TODO Tree" org-show-todo-tree t]
21107 ["Check Deadlines" org-check-deadlines t]
21108 ["Timeline" org-timeline t]
21109 ["Tags/Property tree" org-match-sparse-tree t])
21110 "--"
21111 ["Export/Publish..." org-export-dispatch t]
21112 ("LaTeX"
21113 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21114 :selected org-cdlatex-mode]
21115 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21116 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21117 ["Modify math symbol" org-cdlatex-math-modify
21118 (org-inside-LaTeX-fragment-p)]
21119 ["Insert citation" org-reftex-citation t]
21120 "--"
21121 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21122 "--"
21123 ("MobileOrg"
21124 ["Push Files and Views" org-mobile-push t]
21125 ["Get Captured and Flagged" org-mobile-pull t]
21126 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21127 "--"
21128 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21129 "--"
21130 ("Documentation"
21131 ["Show Version" org-version t]
21132 ["Info Documentation" org-info t])
21133 ("Customize"
21134 ["Browse Org Group" org-customize t]
21135 "--"
21136 ["Expand This Menu" org-create-customize-menu
21137 (fboundp 'customize-menu-create)])
21138 ["Send bug report" org-submit-bug-report t]
21139 "--"
21140 ("Refresh/Reload"
21141 ["Refresh setup current buffer" org-mode-restart t]
21142 ["Reload Org (after update)" org-reload t]
21143 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21146 (defun org-info (&optional node)
21147 "Read documentation for Org-mode in the info system.
21148 With optional NODE, go directly to that node."
21149 (interactive)
21150 (info (format "(org)%s" (or node ""))))
21152 ;;;###autoload
21153 (defun org-submit-bug-report ()
21154 "Submit a bug report on Org-mode via mail.
21156 Don't hesitate to report any problems or inaccurate documentation.
21158 If you don't have setup sending mail from (X)Emacs, please copy the
21159 output buffer into your mail program, as it gives us important
21160 information about your Org-mode version and configuration."
21161 (interactive)
21162 (require 'reporter)
21163 (org-load-modules-maybe)
21164 (org-require-autoloaded-modules)
21165 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21166 (reporter-submit-bug-report
21167 "emacs-orgmode@gnu.org"
21168 (org-version nil 'full)
21169 (let (list)
21170 (save-window-excursion
21171 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21172 (delete-other-windows)
21173 (erase-buffer)
21174 (insert "You are about to submit a bug report to the Org-mode mailing list.
21176 We would like to add your full Org-mode and Outline configuration to the
21177 bug report. This greatly simplifies the work of the maintainer and
21178 other experts on the mailing list.
21180 HOWEVER, some variables you have customized may contain private
21181 information. The names of customers, colleagues, or friends, might
21182 appear in the form of file names, tags, todo states, or search strings.
21183 If you answer yes to the prompt, you might want to check and remove
21184 such private information before sending the email.")
21185 (add-text-properties (point-min) (point-max) '(face org-warning))
21186 (when (yes-or-no-p "Include your Org-mode configuration ")
21187 (mapatoms
21188 (lambda (v)
21189 (and (boundp v)
21190 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21191 (or (and (symbol-value v)
21192 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21193 (and
21194 (get v 'custom-type) (get v 'standard-value)
21195 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21196 (push v list)))))
21197 (kill-buffer (get-buffer "*Warn about privacy*"))
21198 list))
21199 nil nil
21200 "Remember to cover the basics, that is, what you expected to happen and
21201 what in fact did happen. You don't know how to make a good report? See
21203 http://orgmode.org/manual/Feedback.html#Feedback
21205 Your bug report will be posted to the Org-mode mailing list.
21206 ------------------------------------------------------------------------")
21207 (save-excursion
21208 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21209 (replace-match "\\1Bug: \\3 [\\2]")))))
21212 (defun org-install-agenda-files-menu ()
21213 (let ((bl (buffer-list)))
21214 (save-excursion
21215 (while bl
21216 (set-buffer (pop bl))
21217 (if (derived-mode-p 'org-mode) (setq bl nil)))
21218 (when (derived-mode-p 'org-mode)
21219 (easy-menu-change
21220 '("Org") "File List for Agenda"
21221 (append
21222 (list
21223 ["Edit File List" (org-edit-agenda-file-list) t]
21224 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21225 ["Remove Current File from List" org-remove-file t]
21226 ["Cycle through agenda files" org-cycle-agenda-files t]
21227 ["Occur in all agenda files" org-occur-in-agenda-files t]
21228 "--")
21229 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21231 ;;;; Documentation
21233 (defun org-require-autoloaded-modules ()
21234 (interactive)
21235 (mapc 'require
21236 '(org-agenda org-archive org-attach org-clock org-colview org-id
21237 org-table org-timer)))
21239 ;;;###autoload
21240 (defun org-reload (&optional uncompiled)
21241 "Reload all org lisp files.
21242 With prefix arg UNCOMPILED, load the uncompiled versions."
21243 (interactive "P")
21244 (require 'loadhist)
21245 (let* ((org-dir (org-find-library-dir "org"))
21246 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21247 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21248 (remove-re (mapconcat 'identity
21249 (mapcar (lambda (f) (concat "^" f "$"))
21250 (list (if (featurep 'xemacs)
21251 "org-colview"
21252 "org-colview-xemacs")
21253 "org" "org-loaddefs" "org-version"))
21254 "\\|"))
21255 (feats (delete-dups
21256 (mapcar 'file-name-sans-extension
21257 (mapcar 'file-name-nondirectory
21258 (delq nil
21259 (mapcar 'feature-file
21260 features))))))
21261 (lfeat (append
21262 (sort
21263 (setq feats
21264 (delq nil (mapcar
21265 (lambda (f)
21266 (if (and (string-match feature-re f)
21267 (not (string-match remove-re f)))
21268 f nil))
21269 feats)))
21270 'string-lessp)
21271 (list "org-version" "org")))
21272 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21273 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21274 load-uncore load-misses)
21275 (setq load-misses
21276 (delq 't
21277 (mapcar (lambda (f)
21278 (or (org-load-noerror-mustsuffix (concat org-dir f))
21279 (and (string= org-dir contrib-dir)
21280 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21281 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21282 (add-to-list 'load-uncore f 'append)
21285 lfeat)))
21286 (if load-uncore
21287 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21288 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21289 (if load-misses
21290 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21291 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21292 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21294 ;;;###autoload
21295 (defun org-customize ()
21296 "Call the customize function with org as argument."
21297 (interactive)
21298 (org-load-modules-maybe)
21299 (org-require-autoloaded-modules)
21300 (customize-browse 'org))
21302 (defun org-create-customize-menu ()
21303 "Create a full customization menu for Org-mode, insert it into the menu."
21304 (interactive)
21305 (org-load-modules-maybe)
21306 (org-require-autoloaded-modules)
21307 (if (fboundp 'customize-menu-create)
21308 (progn
21309 (easy-menu-change
21310 '("Org") "Customize"
21311 `(["Browse Org group" org-customize t]
21312 "--"
21313 ,(customize-menu-create 'org)
21314 ["Set" Custom-set t]
21315 ["Save" Custom-save t]
21316 ["Reset to Current" Custom-reset-current t]
21317 ["Reset to Saved" Custom-reset-saved t]
21318 ["Reset to Standard Settings" Custom-reset-standard t]))
21319 (message "\"Org\"-menu now contains full customization menu"))
21320 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21322 ;;;; Miscellaneous stuff
21324 ;;; Generally useful functions
21326 (defun org-get-at-bol (property)
21327 "Get text property PROPERTY at beginning of line."
21328 (get-text-property (point-at-bol) property))
21330 (defun org-find-text-property-in-string (prop s)
21331 "Return the first non-nil value of property PROP in string S."
21332 (or (get-text-property 0 prop s)
21333 (get-text-property (or (next-single-property-change 0 prop s) 0)
21334 prop s)))
21336 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21337 "Display the given MESSAGE as a warning."
21338 (if (fboundp 'display-warning)
21339 (display-warning 'org message
21340 (if (featurep 'xemacs) 'warning :warning))
21341 (let ((buf (get-buffer-create "*Org warnings*")))
21342 (with-current-buffer buf
21343 (goto-char (point-max))
21344 (insert "Warning (Org): " message)
21345 (unless (bolp)
21346 (newline)))
21347 (display-buffer buf)
21348 (sit-for 0))))
21350 (defun org-eval (form)
21351 "Eval FORM and return result."
21352 (condition-case error
21353 (eval form)
21354 (error (format "%%![Error: %s]" error))))
21356 (defun org-in-clocktable-p ()
21357 "Check if the cursor is in a clocktable."
21358 (let ((pos (point)) start)
21359 (save-excursion
21360 (end-of-line 1)
21361 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21362 (setq start (match-beginning 0))
21363 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21364 (>= (match-end 0) pos)
21365 start))))
21367 (defun org-in-commented-line ()
21368 "Is point in a line starting with `#'?"
21369 (equal (char-after (point-at-bol)) ?#))
21371 (defun org-in-indented-comment-line ()
21372 "Is point in a line starting with `#' after some white space?"
21373 (save-excursion
21374 (save-match-data
21375 (goto-char (point-at-bol))
21376 (looking-at "[ \t]*#"))))
21378 (defun org-in-verbatim-emphasis ()
21379 (save-match-data
21380 (and (org-in-regexp org-emph-re 2)
21381 (>= (point) (match-beginning 3))
21382 (<= (point) (match-end 4))
21383 (member (match-string 3) '("=" "~")))))
21385 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21386 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21387 (if (and marker (marker-buffer marker)
21388 (buffer-live-p (marker-buffer marker)))
21389 (progn
21390 (org-pop-to-buffer-same-window (marker-buffer marker))
21391 (if (or (> marker (point-max)) (< marker (point-min)))
21392 (widen))
21393 (goto-char marker)
21394 (org-show-context 'org-goto))
21395 (if bookmark
21396 (bookmark-jump bookmark)
21397 (error "Cannot find location"))))
21399 (defun org-quote-csv-field (s)
21400 "Quote field for inclusion in CSV material."
21401 (if (string-match "[\",]" s)
21402 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21405 (defun org-force-self-insert (N)
21406 "Needed to enforce self-insert under remapping."
21407 (interactive "p")
21408 (self-insert-command N))
21410 (defun org-string-width (s)
21411 "Compute width of string, ignoring invisible characters.
21412 This ignores character with invisibility property `org-link', and also
21413 characters with property `org-cwidth', because these will become invisible
21414 upon the next fontification round."
21415 (let (b l)
21416 (when (or (eq t buffer-invisibility-spec)
21417 (assq 'org-link buffer-invisibility-spec))
21418 (while (setq b (text-property-any 0 (length s)
21419 'invisible 'org-link s))
21420 (setq s (concat (substring s 0 b)
21421 (substring s (or (next-single-property-change
21422 b 'invisible s) (length s)))))))
21423 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21424 (setq s (concat (substring s 0 b)
21425 (substring s (or (next-single-property-change
21426 b 'org-cwidth s) (length s))))))
21427 (setq l (string-width s) b -1)
21428 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21429 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21432 (defun org-shorten-string (s maxlength)
21433 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21434 If the string is shorter or has length MAXLENGTH, just return the
21435 original string. If it is longer, the functions finds a space in the
21436 string, breaks this string off at that locations and adds three dots
21437 as ellipsis. Including the ellipsis, the string will not be longer
21438 than MAXLENGTH. If finding a good breaking point in the string does
21439 not work, the string is just chopped off in the middle of a word
21440 if necessary."
21441 (if (<= (length s) maxlength)
21443 (let* ((n (max (- maxlength 4) 1))
21444 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21445 (if (string-match re s)
21446 (concat (match-string 1 s) "...")
21447 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21449 (defun org-get-indentation (&optional line)
21450 "Get the indentation of the current line, interpreting tabs.
21451 When LINE is given, assume it represents a line and compute its indentation."
21452 (if line
21453 (if (string-match "^ *" (org-remove-tabs line))
21454 (match-end 0))
21455 (save-excursion
21456 (beginning-of-line 1)
21457 (skip-chars-forward " \t")
21458 (current-column))))
21460 (defun org-get-string-indentation (s)
21461 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21462 (let ((n -1) (i 0) (w tab-width) c)
21463 (catch 'exit
21464 (while (< (setq n (1+ n)) (length s))
21465 (setq c (aref s n))
21466 (cond ((= c ?\ ) (setq i (1+ i)))
21467 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21468 (t (throw 'exit t)))))
21471 (defun org-remove-tabs (s &optional width)
21472 "Replace tabulators in S with spaces.
21473 Assumes that s is a single line, starting in column 0."
21474 (setq width (or width tab-width))
21475 (while (string-match "\t" s)
21476 (setq s (replace-match
21477 (make-string
21478 (- (* width (/ (+ (match-beginning 0) width) width))
21479 (match-beginning 0)) ?\ )
21480 t t s)))
21483 (defun org-fix-indentation (line ind)
21484 "Fix indentation in LINE.
21485 IND is a cons cell with target and minimum indentation.
21486 If the current indentation in LINE is smaller than the minimum,
21487 leave it alone. If it is larger than ind, set it to the target."
21488 (let* ((l (org-remove-tabs line))
21489 (i (org-get-indentation l))
21490 (i1 (car ind)) (i2 (cdr ind)))
21491 (if (>= i i2) (setq l (substring line i2)))
21492 (if (> i1 0)
21493 (concat (make-string i1 ?\ ) l)
21494 l)))
21496 (defun org-remove-indentation (code &optional n)
21497 "Remove the maximum common indentation from the lines in CODE.
21498 N may optionally be the number of spaces to remove."
21499 (with-temp-buffer
21500 (insert code)
21501 (org-do-remove-indentation n)
21502 (buffer-string)))
21504 (defun org-do-remove-indentation (&optional n)
21505 "Remove the maximum common indentation from the buffer."
21506 (untabify (point-min) (point-max))
21507 (let ((min 10000) re)
21508 (if n
21509 (setq min n)
21510 (goto-char (point-min))
21511 (while (re-search-forward "^ *[^ \n]" nil t)
21512 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21513 (unless (or (= min 0) (= min 10000))
21514 (setq re (format "^ \\{%d\\}" min))
21515 (goto-char (point-min))
21516 (while (re-search-forward re nil t)
21517 (replace-match "")
21518 (end-of-line 1))
21519 min)))
21521 (defun org-fill-template (template alist)
21522 "Find each %key of ALIST in TEMPLATE and replace it."
21523 (let ((case-fold-search nil)
21524 entry key value)
21525 (setq alist (sort (copy-sequence alist)
21526 (lambda (a b) (< (length (car a)) (length (car b))))))
21527 (while (setq entry (pop alist))
21528 (setq template
21529 (replace-regexp-in-string
21530 (concat "%" (regexp-quote (car entry)))
21531 (or (cdr entry) "") template t t)))
21532 template))
21534 (defun org-base-buffer (buffer)
21535 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21536 (if (not buffer)
21537 buffer
21538 (or (buffer-base-buffer buffer)
21539 buffer)))
21541 (defun org-trim (s)
21542 "Remove whitespace at beginning and end of string."
21543 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21544 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21547 (defun org-wrap (string &optional width lines)
21548 "Wrap string to either a number of lines, or a width in characters.
21549 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21550 that costs. If there is a word longer than WIDTH, the text is actually
21551 wrapped to the length of that word.
21552 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21553 many lines, whatever width that takes.
21554 The return value is a list of lines, without newlines at the end."
21555 (let* ((words (org-split-string string "[ \t\n]+"))
21556 (maxword (apply 'max (mapcar 'org-string-width words)))
21557 w ll)
21558 (cond (width
21559 (org-do-wrap words (max maxword width)))
21560 (lines
21561 (setq w maxword)
21562 (setq ll (org-do-wrap words maxword))
21563 (if (<= (length ll) lines)
21565 (setq ll words)
21566 (while (> (length ll) lines)
21567 (setq w (1+ w))
21568 (setq ll (org-do-wrap words w)))
21569 ll))
21570 (t (error "Cannot wrap this")))))
21572 (defun org-do-wrap (words width)
21573 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21574 (let (lines line)
21575 (while words
21576 (setq line (pop words))
21577 (while (and words (< (+ (length line) (length (car words))) width))
21578 (setq line (concat line " " (pop words))))
21579 (setq lines (push line lines)))
21580 (nreverse lines)))
21582 (defun org-split-string (string &optional separators)
21583 "Splits STRING into substrings at SEPARATORS.
21584 No empty strings are returned if there are matches at the beginning
21585 and end of string."
21586 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21587 (start 0)
21588 notfirst
21589 (list nil))
21590 (while (and (string-match rexp string
21591 (if (and notfirst
21592 (= start (match-beginning 0))
21593 (< start (length string)))
21594 (1+ start) start))
21595 (< (match-beginning 0) (length string)))
21596 (setq notfirst t)
21597 (or (eq (match-beginning 0) 0)
21598 (and (eq (match-beginning 0) (match-end 0))
21599 (eq (match-beginning 0) start))
21600 (setq list
21601 (cons (substring string start (match-beginning 0))
21602 list)))
21603 (setq start (match-end 0)))
21604 (or (eq start (length string))
21605 (setq list
21606 (cons (substring string start)
21607 list)))
21608 (nreverse list)))
21610 (defun org-quote-vert (s)
21611 "Replace \"|\" with \"\\vert\"."
21612 (while (string-match "|" s)
21613 (setq s (replace-match "\\vert" t t s)))
21616 (defun org-uuidgen-p (s)
21617 "Is S an ID created by UUIDGEN?"
21618 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21620 (defun org-in-src-block-p (&optional inside)
21621 "Whether point is in a code source block.
21622 When INSIDE is non-nil, don't consider we are within a src block
21623 when point is at #+BEGIN_SRC or #+END_SRC."
21624 (let ((case-fold-search t) ov)
21625 (or (and (setq ov (overlays-at (point)))
21626 (memq 'org-block-background
21627 (overlay-properties (car ov))))
21628 (and (not inside)
21629 (save-match-data
21630 (save-excursion
21631 (beginning-of-line)
21632 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21634 (defun org-context ()
21635 "Return a list of contexts of the current cursor position.
21636 If several contexts apply, all are returned.
21637 Each context entry is a list with a symbol naming the context, and
21638 two positions indicating start and end of the context. Possible
21639 contexts are:
21641 :headline anywhere in a headline
21642 :headline-stars on the leading stars in a headline
21643 :todo-keyword on a TODO keyword (including DONE) in a headline
21644 :tags on the TAGS in a headline
21645 :priority on the priority cookie in a headline
21646 :item on the first line of a plain list item
21647 :item-bullet on the bullet/number of a plain list item
21648 :checkbox on the checkbox in a plain list item
21649 :table in an org-mode table
21650 :table-special on a special filed in a table
21651 :table-table in a table.el table
21652 :clocktable in a clocktable
21653 :src-block in a source block
21654 :link on a hyperlink
21655 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21656 :target on a <<target>>
21657 :radio-target on a <<<radio-target>>>
21658 :latex-fragment on a LaTeX fragment
21659 :latex-preview on a LaTeX fragment with overlaid preview image
21661 This function expects the position to be visible because it uses font-lock
21662 faces as a help to recognize the following contexts: :table-special, :link,
21663 and :keyword."
21664 (let* ((f (get-text-property (point) 'face))
21665 (faces (if (listp f) f (list f)))
21666 (case-fold-search t)
21667 (p (point)) clist o)
21668 ;; First the large context
21669 (cond
21670 ((org-at-heading-p t)
21671 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21672 (when (progn
21673 (beginning-of-line 1)
21674 (looking-at org-todo-line-tags-regexp))
21675 (push (org-point-in-group p 1 :headline-stars) clist)
21676 (push (org-point-in-group p 2 :todo-keyword) clist)
21677 (push (org-point-in-group p 4 :tags) clist))
21678 (goto-char p)
21679 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21680 (if (looking-at "\\[#[A-Z0-9]\\]")
21681 (push (org-point-in-group p 0 :priority) clist)))
21683 ((org-at-item-p)
21684 (push (org-point-in-group p 2 :item-bullet) clist)
21685 (push (list :item (point-at-bol)
21686 (save-excursion (org-end-of-item) (point)))
21687 clist)
21688 (and (org-at-item-checkbox-p)
21689 (push (org-point-in-group p 0 :checkbox) clist)))
21691 ((org-at-table-p)
21692 (push (list :table (org-table-begin) (org-table-end)) clist)
21693 (if (memq 'org-formula faces)
21694 (push (list :table-special
21695 (previous-single-property-change p 'face)
21696 (next-single-property-change p 'face)) clist)))
21697 ((org-at-table-p 'any)
21698 (push (list :table-table) clist)))
21699 (goto-char p)
21701 (let ((case-fold-search t))
21702 ;; New the "medium" contexts: clocktables, source blocks
21703 (cond ((org-in-clocktable-p)
21704 (push (list :clocktable
21705 (and (or (looking-at "#\\+BEGIN: clocktable")
21706 (search-backward "#+BEGIN: clocktable" nil t))
21707 (match-beginning 0))
21708 (and (re-search-forward "#\\+END:?" nil t)
21709 (match-end 0))) clist))
21710 ((org-in-src-block-p)
21711 (push (list :src-block
21712 (and (or (looking-at "#\\+BEGIN_SRC")
21713 (search-backward "#+BEGIN_SRC" nil t))
21714 (match-beginning 0))
21715 (and (search-forward "#+END_SRC" nil t)
21716 (match-beginning 0))) clist))))
21717 (goto-char p)
21719 ;; Now the small context
21720 (cond
21721 ((org-at-timestamp-p)
21722 (push (org-point-in-group p 0 :timestamp) clist))
21723 ((memq 'org-link faces)
21724 (push (list :link
21725 (previous-single-property-change p 'face)
21726 (next-single-property-change p 'face)) clist))
21727 ((memq 'org-special-keyword faces)
21728 (push (list :keyword
21729 (previous-single-property-change p 'face)
21730 (next-single-property-change p 'face)) clist))
21731 ((org-at-target-p)
21732 (push (org-point-in-group p 0 :target) clist)
21733 (goto-char (1- (match-beginning 0)))
21734 (if (looking-at org-radio-target-regexp)
21735 (push (org-point-in-group p 0 :radio-target) clist))
21736 (goto-char p))
21737 ((setq o (car (delq nil
21738 (mapcar
21739 (lambda (x)
21740 (if (memq x org-latex-fragment-image-overlays) x))
21741 (overlays-at (point))))))
21742 (push (list :latex-fragment
21743 (overlay-start o) (overlay-end o)) clist)
21744 (push (list :latex-preview
21745 (overlay-start o) (overlay-end o)) clist))
21746 ((org-inside-LaTeX-fragment-p)
21747 ;; FIXME: positions wrong.
21748 (push (list :latex-fragment (point) (point)) clist)))
21750 (setq clist (nreverse (delq nil clist)))
21751 clist))
21753 ;; FIXME: Compare with at-regexp-p Do we need both?
21754 (defun org-in-regexp (re &optional nlines visually)
21755 "Check if point is inside a match of regexp.
21756 Normally only the current line is checked, but you can include NLINES extra
21757 lines both before and after point into the search.
21758 If VISUALLY is set, require that the cursor is not after the match but
21759 really on, so that the block visually is on the match."
21760 (catch 'exit
21761 (let ((pos (point))
21762 (eol (point-at-eol (+ 1 (or nlines 0))))
21763 (inc (if visually 1 0)))
21764 (save-excursion
21765 (beginning-of-line (- 1 (or nlines 0)))
21766 (while (re-search-forward re eol t)
21767 (if (and (<= (match-beginning 0) pos)
21768 (>= (+ inc (match-end 0)) pos))
21769 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21771 (defun org-at-regexp-p (regexp)
21772 "Is point inside a match of REGEXP in the current line?"
21773 (catch 'exit
21774 (save-excursion
21775 (let ((pos (point)) (end (point-at-eol)))
21776 (beginning-of-line 1)
21777 (while (re-search-forward regexp end t)
21778 (if (and (<= (match-beginning 0) pos)
21779 (>= (match-end 0) pos))
21780 (throw 'exit t)))
21781 nil))))
21783 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21784 "Non-nil when point is between matches of START-RE and END-RE.
21786 Also return a non-nil value when point is on one of the matches.
21788 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21789 buffer positions. Default values are the positions of headlines
21790 surrounding the point.
21792 The functions returns a cons cell whose car (resp. cdr) is the
21793 position before START-RE (resp. after END-RE)."
21794 (save-match-data
21795 (let ((pos (point))
21796 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21797 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21798 beg end)
21799 (save-excursion
21800 ;; Point is on a block when on START-RE or if START-RE can be
21801 ;; found before it...
21802 (and (or (org-at-regexp-p start-re)
21803 (re-search-backward start-re limit-up t))
21804 (setq beg (match-beginning 0))
21805 ;; ... and END-RE after it...
21806 (goto-char (match-end 0))
21807 (re-search-forward end-re limit-down t)
21808 (> (setq end (match-end 0)) pos)
21809 ;; ... without another START-RE in-between.
21810 (goto-char (match-beginning 0))
21811 (not (re-search-backward start-re (1+ beg) t))
21812 ;; Return value.
21813 (cons beg end))))))
21815 (defun org-in-block-p (names)
21816 "Non-nil when point belongs to a block whose name belongs to NAMES.
21818 NAMES is a list of strings containing names of blocks.
21820 Return first block name matched, or nil. Beware that in case of
21821 nested blocks, the returned name may not belong to the closest
21822 block from point."
21823 (save-match-data
21824 (catch 'exit
21825 (let ((case-fold-search t)
21826 (lim-up (save-excursion (outline-previous-heading)))
21827 (lim-down (save-excursion (outline-next-heading))))
21828 (mapc (lambda (name)
21829 (let ((n (regexp-quote name)))
21830 (when (org-between-regexps-p
21831 (concat "^[ \t]*#\\+begin_" n)
21832 (concat "^[ \t]*#\\+end_" n)
21833 lim-up lim-down)
21834 (throw 'exit n))))
21835 names))
21836 nil)))
21838 (defun org-in-drawer-p ()
21839 "Non-nil if point is within a drawer.
21840 If point is within a drawer, return it, as parsed data."
21841 (let ((element (save-match-data (org-element-at-point))))
21842 (while (and element (not (memq (org-element-type element)
21843 '(drawer property-drawer))))
21844 (setq element (org-element-property :parent element)))
21845 element))
21847 (defun org-occur-in-agenda-files (regexp &optional nlines)
21848 "Call `multi-occur' with buffers for all agenda files."
21849 (interactive "sOrg-files matching: \np")
21850 (let* ((files (org-agenda-files))
21851 (tnames (mapcar 'file-truename files))
21852 (extra org-agenda-text-search-extra-files)
21854 (when (eq (car extra) 'agenda-archives)
21855 (setq extra (cdr extra))
21856 (setq files (org-add-archive-files files)))
21857 (while (setq f (pop extra))
21858 (unless (member (file-truename f) tnames)
21859 (add-to-list 'files f 'append)
21860 (add-to-list 'tnames (file-truename f) 'append)))
21861 (multi-occur
21862 (mapcar (lambda (x)
21863 (with-current-buffer
21864 (or (get-file-buffer x) (find-file-noselect x))
21865 (widen)
21866 (current-buffer)))
21867 files)
21868 regexp)))
21870 (if (boundp 'occur-mode-find-occurrence-hook)
21871 ;; Emacs 23
21872 (add-hook 'occur-mode-find-occurrence-hook
21873 (lambda ()
21874 (when (derived-mode-p 'org-mode)
21875 (org-reveal))))
21876 ;; Emacs 22
21877 (defadvice occur-mode-goto-occurrence
21878 (after org-occur-reveal activate)
21879 (and (derived-mode-p 'org-mode) (org-reveal)))
21880 (defadvice occur-mode-goto-occurrence-other-window
21881 (after org-occur-reveal activate)
21882 (and (derived-mode-p 'org-mode) (org-reveal)))
21883 (defadvice occur-mode-display-occurrence
21884 (after org-occur-reveal activate)
21885 (when (derived-mode-p 'org-mode)
21886 (let ((pos (occur-mode-find-occurrence)))
21887 (with-current-buffer (marker-buffer pos)
21888 (save-excursion
21889 (goto-char pos)
21890 (org-reveal)))))))
21892 (defun org-occur-link-in-agenda-files ()
21893 "Create a link and search for it in the agendas.
21894 The link is not stored in `org-stored-links', it is just created
21895 for the search purpose."
21896 (interactive)
21897 (let ((link (condition-case nil
21898 (org-store-link nil)
21899 (error "Unable to create a link to here"))))
21900 (org-occur-in-agenda-files (regexp-quote link))))
21902 (defun org-reverse-string (string)
21903 "Return the reverse of STRING."
21904 (apply 'string (reverse (string-to-list string))))
21906 (defun org-uniquify-alist (alist)
21907 "Merge elements of ALIST with the same key.
21909 For example, in this alist:
21911 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21912 => '((a 1 3) (b 2))
21914 merge (a 1) and (a 3) into (a 1 3).
21916 The function returns the new ALIST."
21917 (let (rtn)
21918 (mapc
21919 (lambda (e)
21920 (let (n)
21921 (if (not (assoc (car e) rtn))
21922 (push e rtn)
21923 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21924 (setq rtn (assq-delete-all (car e) rtn))
21925 (push n rtn))))
21926 alist)
21927 rtn))
21929 (defun org-delete-all (elts list)
21930 "Remove all elements in ELTS from LIST."
21931 (while elts
21932 (setq list (delete (pop elts) list)))
21933 list)
21935 (defun org-count (cl-item cl-seq)
21936 "Count the number of occurrences of ITEM in SEQ.
21937 Taken from `count' in cl-seq.el with all keyword arguments removed."
21938 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21939 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21940 (while (< cl-start cl-end)
21941 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21942 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21943 (setq cl-start (1+ cl-start)))
21944 cl-count))
21946 (defun org-remove-if (predicate seq)
21947 "Remove everything from SEQ that fulfills PREDICATE."
21948 (let (res e)
21949 (while seq
21950 (setq e (pop seq))
21951 (if (not (funcall predicate e)) (push e res)))
21952 (nreverse res)))
21954 (defun org-remove-if-not (predicate seq)
21955 "Remove everything from SEQ that does not fulfill PREDICATE."
21956 (let (res e)
21957 (while seq
21958 (setq e (pop seq))
21959 (if (funcall predicate e) (push e res)))
21960 (nreverse res)))
21962 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21963 "Reduce two-argument FUNCTION across SEQ.
21964 Taken from `reduce' in cl-seq.el with all keyword arguments but
21965 \":initial-value\" removed."
21966 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21967 (cadr (memq :initial-value cl-keys)))
21968 (cl-seq (pop cl-seq))
21969 (t (funcall cl-func)))))
21970 (while cl-seq
21971 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21972 cl-accum))
21974 (defun org-every (pred seq)
21975 "Return true if PREDICATE is true of every element of SEQ.
21976 Adapted from `every' in cl.el."
21977 (catch 'org-every
21978 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21981 (defun org-some (pred seq)
21982 "Return true if PREDICATE is true of any element of SEQ.
21983 Adapted from `some' in cl.el."
21984 (catch 'org-some
21985 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21986 nil))
21988 (defun org-back-over-empty-lines ()
21989 "Move backwards over whitespace, to the beginning of the first empty line.
21990 Returns the number of empty lines passed."
21991 (let ((pos (point)))
21992 (if (cdr (assoc 'heading org-blank-before-new-entry))
21993 (skip-chars-backward " \t\n\r")
21994 (unless (eobp)
21995 (forward-line -1)))
21996 (beginning-of-line 2)
21997 (goto-char (min (point) pos))
21998 (count-lines (point) pos)))
22000 (defun org-skip-whitespace ()
22001 (skip-chars-forward " \t\n\r"))
22003 (defun org-point-in-group (point group &optional context)
22004 "Check if POINT is in match-group GROUP.
22005 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22006 match. If the match group does not exist or point is not inside it,
22007 return nil."
22008 (and (match-beginning group)
22009 (>= point (match-beginning group))
22010 (<= point (match-end group))
22011 (if context
22012 (list context (match-beginning group) (match-end group))
22013 t)))
22015 (defun org-switch-to-buffer-other-window (&rest args)
22016 "Switch to buffer in a second window on the current frame.
22017 In particular, do not allow pop-up frames.
22018 Returns the newly created buffer."
22019 (org-no-popups
22020 (apply 'switch-to-buffer-other-window args)))
22022 (defun org-combine-plists (&rest plists)
22023 "Create a single property list from all plists in PLISTS.
22024 The process starts by copying the first list, and then setting properties
22025 from the other lists. Settings in the last list are the most significant
22026 ones and overrule settings in the other lists."
22027 (let ((rtn (copy-sequence (pop plists)))
22028 p v ls)
22029 (while plists
22030 (setq ls (pop plists))
22031 (while ls
22032 (setq p (pop ls) v (pop ls))
22033 (setq rtn (plist-put rtn p v))))
22034 rtn))
22036 (defun org-replace-escapes (string table)
22037 "Replace %-escapes in STRING with values in TABLE.
22038 TABLE is an association list with keys like \"%a\" and string values.
22039 The sequences in STRING may contain normal field width and padding information,
22040 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22041 so values can contain further %-escapes if they are define later in TABLE."
22042 (let ((tbl (copy-alist table))
22043 (case-fold-search nil)
22044 (pchg 0)
22045 e re rpl)
22046 (while (setq e (pop tbl))
22047 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22048 (when (and (cdr e) (string-match re (cdr e)))
22049 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22050 (safe "SREF"))
22051 (add-text-properties 0 3 (list 'sref sref) safe)
22052 (setcdr e (replace-match safe t t (cdr e)))))
22053 (while (string-match re string)
22054 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22055 (cdr e)))
22056 (setq string (replace-match rpl t t string))))
22057 (while (setq pchg (next-property-change pchg string))
22058 (let ((sref (get-text-property pchg 'sref string)))
22059 (when (and sref (string-match "SREF" string pchg))
22060 (setq string (replace-match sref t t string)))))
22061 string))
22063 (defun org-sublist (list start end)
22064 "Return a section of LIST, from START to END.
22065 Counting starts at 1."
22066 (let (rtn (c start))
22067 (setq list (nthcdr (1- start) list))
22068 (while (and list (<= c end))
22069 (push (pop list) rtn)
22070 (setq c (1+ c)))
22071 (nreverse rtn)))
22073 (defun org-find-base-buffer-visiting (file)
22074 "Like `find-buffer-visiting' but always return the base buffer and
22075 not an indirect buffer."
22076 (let ((buf (or (get-file-buffer file)
22077 (find-buffer-visiting file))))
22078 (if buf
22079 (or (buffer-base-buffer buf) buf)
22080 nil)))
22082 (defun org-image-file-name-regexp (&optional extensions)
22083 "Return regexp matching the file names of images.
22084 If EXTENSIONS is given, only match these."
22085 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22086 (image-file-name-regexp)
22087 (let ((image-file-name-extensions
22088 (or extensions
22089 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22090 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22091 (concat "\\."
22092 (regexp-opt (nconc (mapcar 'upcase
22093 image-file-name-extensions)
22094 image-file-name-extensions)
22096 "\\'"))))
22098 (defun org-file-image-p (file &optional extensions)
22099 "Return non-nil if FILE is an image."
22100 (save-match-data
22101 (string-match (org-image-file-name-regexp extensions) file)))
22103 (defun org-get-cursor-date (&optional with-time)
22104 "Return the date at cursor in as a time.
22105 This works in the calendar and in the agenda, anywhere else it just
22106 returns the current time.
22107 If WITH-TIME is non-nil, returns the time of the event at point (in
22108 the agenda) or the current time of the day."
22109 (let (date day defd tp tm hod mod)
22110 (when with-time
22111 (setq tp (get-text-property (point) 'time))
22112 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22113 (setq hod (string-to-number (match-string 1 tp))
22114 mod (string-to-number (match-string 2 tp))))
22115 (or tp (setq hod (nth 2 (decode-time (current-time)))
22116 mod (nth 1 (decode-time (current-time))))))
22117 (cond
22118 ((eq major-mode 'calendar-mode)
22119 (setq date (calendar-cursor-to-date)
22120 defd (encode-time 0 (or mod 0) (or hod 0)
22121 (nth 1 date) (nth 0 date) (nth 2 date))))
22122 ((eq major-mode 'org-agenda-mode)
22123 (setq day (get-text-property (point) 'day))
22124 (if day
22125 (setq date (calendar-gregorian-from-absolute day)
22126 defd (encode-time 0 (or mod 0) (or hod 0)
22127 (nth 1 date) (nth 0 date) (nth 2 date))))))
22128 (or defd (current-time))))
22130 (defun org-mark-subtree (&optional up)
22131 "Mark the current subtree.
22132 This puts point at the start of the current subtree, and mark at
22133 the end. If a numeric prefix UP is given, move up into the
22134 hierarchy of headlines by UP levels before marking the subtree."
22135 (interactive "P")
22136 (org-with-limited-levels
22137 (cond ((org-at-heading-p) (beginning-of-line))
22138 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22139 (t (outline-previous-visible-heading 1))))
22140 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22141 (if (org-called-interactively-p 'any)
22142 (call-interactively 'org-mark-element)
22143 (org-mark-element)))
22146 ;;; Indentation
22148 (defun org-indent-line ()
22149 "Indent line depending on context."
22150 (interactive)
22151 (let* ((pos (point))
22152 (itemp (org-at-item-p))
22153 (case-fold-search t)
22154 (org-drawer-regexp (or org-drawer-regexp "\000"))
22155 (inline-task-p (and (featurep 'org-inlinetask)
22156 (org-inlinetask-in-task-p)))
22157 (inline-re (and inline-task-p
22158 (org-inlinetask-outline-regexp)))
22159 column)
22160 (if (and orgstruct-is-++ (eq pos (point)))
22161 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22162 (indent-according-to-mode))
22163 (beginning-of-line 1)
22164 (cond
22165 ;; Headings
22166 ((looking-at org-outline-regexp) (setq column 0))
22167 ;; Footnote definition
22168 ((looking-at org-footnote-definition-re) (setq column 0))
22169 ;; Literal examples
22170 ((looking-at "[ \t]*:\\( \\|$\\)")
22171 (setq column (org-get-indentation))) ; do nothing
22172 ;; Lists
22173 ((ignore-errors (goto-char (org-in-item-p)))
22174 (setq column (if itemp
22175 (org-get-indentation)
22176 (org-list-item-body-column (point))))
22177 (goto-char pos))
22178 ;; Drawers
22179 ((and (looking-at "[ \t]*:END:")
22180 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22181 (save-excursion
22182 (goto-char (1- (match-beginning 1)))
22183 (setq column (current-column))))
22184 ;; Special blocks
22185 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22186 (save-excursion
22187 (re-search-backward
22188 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22189 (setq column (org-get-indentation (match-string 0))))
22190 ((and (not (looking-at "[ \t]*#\\+begin_"))
22191 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22192 (save-excursion
22193 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22194 (setq column
22195 (cond ((equal (downcase (match-string 1)) "src")
22196 ;; src blocks: let `org-edit-src-exit' handle them
22197 (org-get-indentation))
22198 ((equal (downcase (match-string 1)) "example")
22199 (max (org-get-indentation)
22200 (org-get-indentation (match-string 0))))
22202 (org-get-indentation (match-string 0))))))
22203 ;; This line has nothing special, look at the previous relevant
22204 ;; line to compute indentation
22206 (beginning-of-line 0)
22207 (while (and (not (bobp))
22208 (not (looking-at org-table-line-regexp))
22209 (not (looking-at org-drawer-regexp))
22210 ;; When point started in an inline task, do not move
22211 ;; above task starting line.
22212 (not (and inline-task-p (looking-at inline-re)))
22213 ;; Skip drawers, blocks, empty lines, verbatim,
22214 ;; comments, tables, footnotes definitions, lists,
22215 ;; inline tasks.
22216 (or (and (looking-at "[ \t]*:END:")
22217 (re-search-backward org-drawer-regexp nil t))
22218 (and (looking-at "[ \t]*#\\+end_")
22219 (re-search-backward "[ \t]*#\\+begin_"nil t))
22220 (looking-at "[ \t]*[\n:#|]")
22221 (looking-at org-footnote-definition-re)
22222 (and (not inline-task-p)
22223 (featurep 'org-inlinetask)
22224 (org-inlinetask-in-task-p)
22225 (or (org-inlinetask-goto-beginning) t))))
22226 (beginning-of-line 0))
22227 (cond
22228 ;; There was a list item above.
22229 ((ignore-errors (goto-char (org-in-item-p)))
22230 (goto-char (org-list-get-top-point (org-list-struct)))
22231 (setq column (org-get-indentation)))
22232 ;; There was an heading above.
22233 ((looking-at "\\*+[ \t]+")
22234 (if (not org-adapt-indentation)
22235 (setq column 0)
22236 (goto-char (match-end 0))
22237 (setq column (current-column))))
22238 ;; A drawer had started and is unfinished
22239 ((looking-at org-drawer-regexp)
22240 (goto-char (1- (match-beginning 1)))
22241 (setq column (current-column)))
22242 ;; Else, nothing noticeable found: get indentation and go on.
22243 (t (setq column (org-get-indentation))))))
22244 ;; Now apply indentation and move cursor accordingly
22245 (goto-char pos)
22246 (if (<= (current-column) (current-indentation))
22247 (org-indent-line-to column)
22248 (save-excursion (org-indent-line-to column)))
22249 ;; Special polishing for properties, see `org-property-format'
22250 (setq column (current-column))
22251 (beginning-of-line 1)
22252 (if (looking-at org-property-re)
22253 (replace-match (concat (match-string 4)
22254 (format org-property-format
22255 (match-string 1) (match-string 3)))
22256 t t))
22257 (org-move-to-column column))))
22259 (defun org-indent-drawer ()
22260 "Indent the drawer at point."
22261 (interactive)
22262 (let ((p (point))
22263 (e (and (save-excursion (re-search-forward ":END:" nil t))
22264 (match-end 0)))
22265 (folded
22266 (save-excursion
22267 (end-of-line)
22268 (when (overlays-at (point))
22269 (member 'invisible (overlay-properties
22270 (car (overlays-at (point)))))))))
22271 (when folded (org-cycle))
22272 (indent-for-tab-command)
22273 (while (and (move-beginning-of-line 2) (< (point) e))
22274 (indent-for-tab-command))
22275 (goto-char p)
22276 (when folded (org-cycle)))
22277 (message "Drawer at point indented"))
22279 (defun org-indent-block ()
22280 "Indent the block at point."
22281 (interactive)
22282 (let ((p (point))
22283 (case-fold-search t)
22284 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22285 (match-end 0)))
22286 (folded
22287 (save-excursion
22288 (end-of-line)
22289 (when (overlays-at (point))
22290 (member 'invisible (overlay-properties
22291 (car (overlays-at (point)))))))))
22292 (when folded (org-cycle))
22293 (indent-for-tab-command)
22294 (while (and (move-beginning-of-line 2) (< (point) e))
22295 (indent-for-tab-command))
22296 (goto-char p)
22297 (when folded (org-cycle)))
22298 (message "Block at point indented"))
22300 (defun org-indent-region (start end)
22301 "Indent region."
22302 (interactive "r")
22303 (save-excursion
22304 (let ((line-end (org-current-line end)))
22305 (goto-char start)
22306 (while (< (org-current-line) line-end)
22307 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22308 (t (call-interactively 'org-indent-line)))
22309 (move-beginning-of-line 2)))))
22312 ;;; Filling
22314 ;; We use our own fill-paragraph and auto-fill functions.
22316 ;; `org-fill-paragraph' relies on adaptive filling and context
22317 ;; checking. Appropriate `fill-prefix' is computed with
22318 ;; `org-adaptive-fill-function'.
22320 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22321 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22322 ;; `org-adaptive-fill-function' value. Internally,
22323 ;; `org-comment-line-break-function' breaks the line.
22325 ;; `org-setup-filling' installs filling and auto-filling related
22326 ;; variables during `org-mode' initialization.
22328 (defvar org-element-paragraph-separate) ; org-element.el
22329 (defun org-setup-filling ()
22330 (require 'org-element)
22331 ;; Prevent auto-fill from inserting unwanted new items.
22332 (when (boundp 'fill-nobreak-predicate)
22333 (org-set-local
22334 'fill-nobreak-predicate
22335 (org-uniquify
22336 (append fill-nobreak-predicate
22337 '(org-fill-line-break-nobreak-p
22338 org-fill-paragraph-with-timestamp-nobreak-p)))))
22339 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22340 (org-set-local 'paragraph-start paragraph-ending)
22341 (org-set-local 'paragraph-separate paragraph-ending))
22342 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22343 (org-set-local 'auto-fill-inhibit-regexp nil)
22344 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22345 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22346 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22348 (defun org-fill-line-break-nobreak-p ()
22349 "Non-nil when a new line at point would create an Org line break."
22350 (save-excursion
22351 (skip-chars-backward "[ \t]")
22352 (skip-chars-backward "\\\\")
22353 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22355 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22356 "Non-nil when a new line at point would split a timestamp."
22357 (and (org-at-timestamp-p t)
22358 (not (looking-at org-ts-regexp-both))))
22360 (declare-function message-in-body-p "message" ())
22361 (defvar orgtbl-line-start-regexp) ; From org-table.el
22362 (defun org-adaptive-fill-function ()
22363 "Compute a fill prefix for the current line.
22364 Return fill prefix, as a string, or nil if current line isn't
22365 meant to be filled. For convenience, if `adaptive-fill-regexp'
22366 matches in paragraphs or comments, use it."
22367 (catch 'exit
22368 (when (derived-mode-p 'message-mode)
22369 (save-excursion
22370 (beginning-of-line)
22371 (cond ((or (not (message-in-body-p))
22372 (looking-at orgtbl-line-start-regexp))
22373 (throw 'exit nil))
22374 ((looking-at message-cite-prefix-regexp)
22375 (throw 'exit (match-string-no-properties 0)))
22376 ((looking-at org-outline-regexp)
22377 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22378 (org-with-wide-buffer
22379 (let* ((p (line-beginning-position))
22380 (element (save-excursion
22381 (beginning-of-line)
22382 (or (ignore-errors (org-element-at-point))
22383 (user-error "An element cannot be parsed line %d"
22384 (line-number-at-pos (point))))))
22385 (type (org-element-type element))
22386 (post-affiliated (org-element-property :post-affiliated element)))
22387 (unless (and post-affiliated (< p post-affiliated))
22388 (case type
22389 (comment
22390 (save-excursion
22391 (beginning-of-line)
22392 (looking-at "[ \t]*")
22393 (concat (match-string 0) "# ")))
22394 (footnote-definition "")
22395 ((item plain-list)
22396 (make-string (org-list-item-body-column
22397 (or post-affiliated
22398 (org-element-property :begin element)))
22399 ? ))
22400 (paragraph
22401 ;; Fill prefix is usually the same as the current line,
22402 ;; unless the paragraph is at the beginning of an item.
22403 (let ((parent (org-element-property :parent element)))
22404 (save-excursion
22405 (beginning-of-line)
22406 (cond ((eq (org-element-type parent) 'item)
22407 (make-string (org-list-item-body-column
22408 (org-element-property :begin parent))
22409 ? ))
22410 ((and adaptive-fill-regexp
22411 ;; Locally disable
22412 ;; `adaptive-fill-function' to let
22413 ;; `fill-context-prefix' handle
22414 ;; `adaptive-fill-regexp' variable.
22415 (let (adaptive-fill-function)
22416 (fill-context-prefix
22417 post-affiliated
22418 (org-element-property :end element)))))
22419 ((looking-at "[ \t]+") (match-string 0))
22420 (t "")))))
22421 (comment-block
22422 ;; Only fill contents if P is within block boundaries.
22423 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22424 (forward-line)
22425 (point)))
22426 (cend (save-excursion
22427 (goto-char (org-element-property :end element))
22428 (skip-chars-backward " \r\t\n")
22429 (line-beginning-position))))
22430 (when (and (>= p cbeg) (< p cend))
22431 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22432 (match-string 0)
22433 ""))))))))))
22435 (declare-function message-goto-body "message" ())
22436 (defvar message-cite-prefix-regexp) ; From message.el
22437 (defun org-fill-paragraph (&optional justify)
22438 "Fill element at point, when applicable.
22440 This function only applies to comment blocks, comments, example
22441 blocks and paragraphs. Also, as a special case, re-align table
22442 when point is at one.
22444 If JUSTIFY is non-nil (interactively, with prefix argument),
22445 justify as well. If `sentence-end-double-space' is non-nil, then
22446 period followed by one space does not end a sentence, so don't
22447 break a line there. The variable `fill-column' controls the
22448 width for filling.
22450 For convenience, when point is at a plain list, an item or
22451 a footnote definition, try to fill the first paragraph within."
22452 (interactive)
22453 (if (and (derived-mode-p 'message-mode)
22454 (or (not (message-in-body-p))
22455 (save-excursion (move-beginning-of-line 1)
22456 (looking-at message-cite-prefix-regexp))))
22457 ;; First ensure filling is correct in message-mode.
22458 (let ((fill-paragraph-function
22459 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22460 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22461 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22462 (paragraph-separate
22463 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22464 (fill-paragraph nil))
22465 (with-syntax-table org-mode-transpose-word-syntax-table
22466 ;; Move to end of line in order to get the first paragraph
22467 ;; within a plain list or a footnote definition.
22468 (let ((element (save-excursion
22469 (end-of-line)
22470 (or (ignore-errors (org-element-at-point))
22471 (user-error "An element cannot be parsed line %d"
22472 (line-number-at-pos (point)))))))
22473 ;; First check if point is in a blank line at the beginning of
22474 ;; the buffer. In that case, ignore filling.
22475 (case (org-element-type element)
22476 ;; Use major mode filling function is src blocks.
22477 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22478 ;; Align Org tables, leave table.el tables as-is.
22479 (table-row (org-table-align) t)
22480 (table
22481 (when (eq (org-element-property :type element) 'org)
22482 (save-excursion
22483 (goto-char (org-element-property :post-affiliated element))
22484 (org-table-align)))
22486 (paragraph
22487 ;; Paragraphs may contain `line-break' type objects.
22488 (let ((beg (max (point-min)
22489 (org-element-property :contents-begin element)))
22490 (end (min (point-max)
22491 (org-element-property :contents-end element))))
22492 ;; Do nothing if point is at an affiliated keyword.
22493 (if (< (line-end-position) beg) t
22494 (when (derived-mode-p 'message-mode)
22495 ;; In `message-mode', do not fill following citation
22496 ;; in current paragraph nor text before message body.
22497 (let ((body-start (save-excursion (message-goto-body))))
22498 (when body-start (setq beg (max body-start beg))))
22499 (when (save-excursion
22500 (re-search-forward
22501 (concat "^" message-cite-prefix-regexp) end t))
22502 (setq end (match-beginning 0))))
22503 ;; Fill paragraph, taking line breaks into account.
22504 ;; For that, slice the paragraph using line breaks as
22505 ;; separators, and fill the parts in reverse order to
22506 ;; avoid messing with markers.
22507 (save-excursion
22508 (goto-char end)
22509 (mapc
22510 (lambda (pos)
22511 (fill-region-as-paragraph pos (point) justify)
22512 (goto-char pos))
22513 ;; Find the list of ending positions for line breaks
22514 ;; in the current paragraph. Add paragraph
22515 ;; beginning to include first slice.
22516 (nreverse
22517 (cons beg
22518 (org-element-map
22519 (org-element--parse-objects
22520 beg end nil (org-element-restriction 'paragraph))
22521 'line-break
22522 (lambda (lb) (org-element-property :end lb)))))))
22523 t)))
22524 ;; Contents of `comment-block' type elements should be
22525 ;; filled as plain text, but only if point is within block
22526 ;; markers.
22527 (comment-block
22528 (let* ((case-fold-search t)
22529 (beg (save-excursion
22530 (goto-char (org-element-property :begin element))
22531 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22532 (forward-line)
22533 (point)))
22534 (end (save-excursion
22535 (goto-char (org-element-property :end element))
22536 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22537 (line-beginning-position))))
22538 (if (or (< (point) beg) (> (point) end)) t
22539 (fill-region-as-paragraph
22540 (save-excursion (end-of-line)
22541 (re-search-backward "^[ \t]*$" beg 'move)
22542 (line-beginning-position))
22543 (save-excursion (beginning-of-line)
22544 (re-search-forward "^[ \t]*$" end 'move)
22545 (line-beginning-position))
22546 justify))))
22547 ;; Fill comments.
22548 (comment
22549 (let ((begin (org-element-property :post-affiliated element))
22550 (end (org-element-property :end element)))
22551 (when (and (>= (point) begin) (<= (point) end))
22552 (let ((begin (save-excursion
22553 (end-of-line)
22554 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22555 (progn (forward-line) (point))
22556 begin)))
22557 (end (save-excursion
22558 (end-of-line)
22559 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22560 (1- (line-beginning-position))
22561 (skip-chars-backward " \r\t\n")
22562 (line-end-position)))))
22563 ;; Do not fill comments when at a blank line.
22564 (when (> end begin)
22565 (let ((fill-prefix
22566 (save-excursion
22567 (beginning-of-line)
22568 (looking-at "[ \t]*#")
22569 (let ((comment-prefix (match-string 0)))
22570 (goto-char (match-end 0))
22571 (if (looking-at adaptive-fill-regexp)
22572 (concat comment-prefix (match-string 0))
22573 (concat comment-prefix " "))))))
22574 (save-excursion
22575 (fill-region-as-paragraph begin end justify))))))
22577 ;; Ignore every other element.
22578 (otherwise t))))))
22580 (defun org-auto-fill-function ()
22581 "Auto-fill function."
22582 ;; Check if auto-filling is meaningful.
22583 (let ((fc (current-fill-column)))
22584 (when (and fc (> (current-column) fc))
22585 (let* ((fill-prefix (org-adaptive-fill-function))
22586 ;; Enforce empty fill prefix, if required. Otherwise, it
22587 ;; will be computed again.
22588 (adaptive-fill-mode (not (equal fill-prefix ""))))
22589 (when fill-prefix (do-auto-fill))))))
22591 (defun org-comment-line-break-function (&optional soft)
22592 "Break line at point and indent, continuing comment if within one.
22593 The inserted newline is marked hard if variable
22594 `use-hard-newlines' is true, unless optional argument SOFT is
22595 non-nil."
22596 (if soft (insert-and-inherit ?\n) (newline 1))
22597 (save-excursion (forward-char -1) (delete-horizontal-space))
22598 (delete-horizontal-space)
22599 (indent-to-left-margin)
22600 (insert-before-markers-and-inherit fill-prefix))
22603 ;;; Fixed Width Areas
22605 (defun org-toggle-fixed-width ()
22606 "Toggle fixed-width markup.
22608 Add or remove fixed-width markup on current line, whenever it
22609 makes sense. Return an error otherwise.
22611 If a region is active and if it contains only fixed-width areas
22612 or blank lines, remove all fixed-width markup in it. If the
22613 region contains anything else, convert all non-fixed-width lines
22614 to fixed-width ones.
22616 Blank lines at the end of the region are ignored unless the
22617 region only contains such lines."
22618 (interactive)
22619 (if (not (org-region-active-p))
22620 ;; No region:
22622 ;; Remove fixed width marker only in a fixed-with element.
22624 ;; Add fixed width maker in paragraphs, in blank lines after
22625 ;; elements or at the beginning of a headline or an inlinetask,
22626 ;; and before any one-line elements (e.g., a clock).
22627 (progn
22628 (beginning-of-line)
22629 (let* ((element (org-element-at-point))
22630 (type (org-element-type element)))
22631 (cond
22632 ((and (eq type 'fixed-width)
22633 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22634 (replace-match
22635 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22636 ((and (memq type '(babel-call clock comment diary-sexp headline
22637 horizontal-rule keyword paragraph
22638 planning))
22639 (or (not (org-element-property :post-affiliated element))
22640 (<= (org-element-property :post-affiliated element)
22641 (point))))
22642 (skip-chars-forward " \t")
22643 (insert ": "))
22644 ((and (org-looking-at-p "[ \t]*$")
22645 (or (eq type 'inlinetask)
22646 (save-excursion
22647 (skip-chars-forward " \r\t\n")
22648 (<= (org-element-property :end element) (point)))))
22649 (delete-region (point) (line-end-position))
22650 (org-indent-line)
22651 (insert ": "))
22652 (t (user-error "Cannot insert a fixed-width line here")))))
22653 ;; Region active.
22654 (let* ((begin (save-excursion
22655 (goto-char (region-beginning))
22656 (line-beginning-position)))
22657 (end (copy-marker
22658 (save-excursion
22659 (goto-char (region-end))
22660 (unless (eolp) (beginning-of-line))
22661 (if (save-excursion (re-search-backward "\\S-" begin t))
22662 (progn (skip-chars-backward " \r\t\n") (point))
22663 (point)))))
22664 (all-fixed-width-p
22665 (catch 'not-all-p
22666 (save-excursion
22667 (goto-char begin)
22668 (skip-chars-forward " \r\t\n")
22669 (when (eobp) (throw 'not-all-p nil))
22670 (while (< (point) end)
22671 (let ((element (org-element-at-point)))
22672 (if (eq (org-element-type element) 'fixed-width)
22673 (goto-char (org-element-property :end element))
22674 (throw 'not-all-p nil))))
22675 t))))
22676 (if all-fixed-width-p
22677 (save-excursion
22678 (goto-char begin)
22679 (while (< (point) end)
22680 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22681 (replace-match
22682 "" nil nil nil
22683 (if (= (line-end-position) (match-end 0)) 0 1)))
22684 (forward-line)))
22685 (let ((min-ind (point-max)))
22686 ;; Find minimum indentation across all lines.
22687 (save-excursion
22688 (goto-char begin)
22689 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22690 (setq min-ind 0)
22691 (catch 'zerop
22692 (while (< (point) end)
22693 (unless (org-looking-at-p "[ \t]*$")
22694 (let ((ind (org-get-indentation)))
22695 (setq min-ind (min min-ind ind))
22696 (when (zerop ind) (throw 'zerop t))))
22697 (forward-line)))))
22698 ;; Loop over all lines and add fixed-width markup everywhere
22699 ;; but in fixed-width lines.
22700 (save-excursion
22701 (goto-char begin)
22702 (while (< (point) end)
22703 (cond
22704 ((org-at-heading-p)
22705 (insert ": ")
22706 (forward-line)
22707 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
22708 (insert ":")
22709 (forward-line)))
22710 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
22711 (let* ((element (org-element-at-point))
22712 (element-end (org-element-property :end element)))
22713 (if (eq (org-element-type element) 'fixed-width)
22714 (progn (goto-char element-end)
22715 (skip-chars-backward " \r\t\n")
22716 (forward-line))
22717 (let ((limit (min end element-end)))
22718 (while (< (point) limit)
22719 (org-move-to-column min-ind t)
22720 (insert ": ")
22721 (forward-line))))))
22723 (org-move-to-column min-ind t)
22724 (insert ": ")
22725 (forward-line)))))))
22726 (set-marker end nil))))
22729 ;;; Comments
22731 ;; Org comments syntax is quite complex. It requires the entire line
22732 ;; to be just a comment. Also, even with the right syntax at the
22733 ;; beginning of line, some some elements (i.e. verse-block or
22734 ;; example-block) don't accept comments. Usual Emacs comment commands
22735 ;; cannot cope with those requirements. Therefore, Org replaces them.
22737 ;; Org still relies on `comment-dwim', but cannot trust
22738 ;; `comment-only-p'. So, `comment-region-function' and
22739 ;; `uncomment-region-function' both point
22740 ;; to`org-comment-or-uncomment-region'. Eventually,
22741 ;; `org-insert-comment' takes care of insertion of comments at the
22742 ;; beginning of line.
22744 ;; `org-setup-comments-handling' install comments related variables
22745 ;; during `org-mode' initialization.
22747 (defun org-setup-comments-handling ()
22748 (interactive)
22749 (org-set-local 'comment-use-syntax nil)
22750 (org-set-local 'comment-start "# ")
22751 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22752 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22753 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22754 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22756 (defun org-insert-comment ()
22757 "Insert an empty comment above current line.
22758 If the line is empty, insert comment at its beginning. When
22759 point is within a source block, comment according to the related
22760 major mode."
22761 (if (let ((element (org-element-at-point)))
22762 (and (eq (org-element-type element) 'src-block)
22763 (< (save-excursion
22764 (goto-char (org-element-property :post-affiliated element))
22765 (line-end-position))
22766 (point))
22767 (> (save-excursion
22768 (goto-char (org-element-property :end element))
22769 (skip-chars-backward " \r\t\n")
22770 (line-beginning-position))
22771 (point))))
22772 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22773 (beginning-of-line)
22774 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22775 (open-line 1))
22776 (org-indent-line)
22777 (insert "# ")))
22779 (defvar comment-empty-lines) ; From newcomment.el.
22780 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22781 "Comment or uncomment each non-blank line in the region.
22782 Uncomment each non-blank line between BEG and END if it only
22783 contains commented lines. Otherwise, comment them. If region is
22784 strictly within a source block, use appropriate comment syntax."
22785 (if (let ((element (org-element-at-point)))
22786 (and (eq (org-element-type element) 'src-block)
22787 (< (save-excursion
22788 (goto-char (org-element-property :post-affiliated element))
22789 (line-end-position))
22790 beg)
22791 (>= (save-excursion
22792 (goto-char (org-element-property :end element))
22793 (skip-chars-backward " \r\t\n")
22794 (line-beginning-position))
22795 end)))
22796 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22797 (save-restriction
22798 ;; Restrict region
22799 (narrow-to-region (save-excursion (goto-char beg)
22800 (skip-chars-forward " \r\t\n" end)
22801 (line-beginning-position))
22802 (save-excursion (goto-char end)
22803 (skip-chars-backward " \r\t\n" beg)
22804 (line-end-position)))
22805 (let ((uncommentp
22806 ;; UNCOMMENTP is non-nil when every non blank line between
22807 ;; BEG and END is a comment.
22808 (save-excursion
22809 (goto-char (point-min))
22810 (while (and (not (eobp))
22811 (let ((element (org-element-at-point)))
22812 (and (eq (org-element-type element) 'comment)
22813 (goto-char (min (point-max)
22814 (org-element-property
22815 :end element)))))))
22816 (eobp))))
22817 (if uncommentp
22818 ;; Only blank lines and comments in region: uncomment it.
22819 (save-excursion
22820 (goto-char (point-min))
22821 (while (not (eobp))
22822 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22823 (replace-match "" nil nil nil 1))
22824 (forward-line)))
22825 ;; Comment each line in region.
22826 (let ((min-indent (point-max)))
22827 ;; First find the minimum indentation across all lines.
22828 (save-excursion
22829 (goto-char (point-min))
22830 (while (and (not (eobp)) (not (zerop min-indent)))
22831 (unless (looking-at "[ \t]*$")
22832 (setq min-indent (min min-indent (current-indentation))))
22833 (forward-line)))
22834 ;; Then loop over all lines.
22835 (save-excursion
22836 (goto-char (point-min))
22837 (while (not (eobp))
22838 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22839 ;; Don't get fooled by invisible text (e.g. link path)
22840 ;; when moving to column MIN-INDENT.
22841 (let ((buffer-invisibility-spec nil))
22842 (org-move-to-column min-indent t))
22843 (insert comment-start))
22844 (forward-line)))))))))
22846 (defun org-comment-dwim (arg)
22847 (interactive "*P")
22848 "Call `comment-dwim' within a source edit buffer if needed."
22849 (if (org-in-src-block-p)
22850 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22851 (call-interactively #'comment-dwim)))
22854 ;;; Planning
22856 ;; This section contains tools to operate on timestamp objects, as
22857 ;; returned by, e.g. `org-element-context'.
22859 (defun org-timestamp-has-time-p (timestamp)
22860 "Non-nil when TIMESTAMP has a time specified."
22861 (org-element-property :hour-start timestamp))
22863 (defun org-timestamp-format (timestamp format &optional end utc)
22864 "Format a TIMESTAMP element into a string.
22866 FORMAT is a format specifier to be passed to
22867 `format-time-string'.
22869 When optional argument END is non-nil, use end of date-range or
22870 time-range, if possible.
22872 When optional argument UTC is non-nil, time will be expressed as
22873 Universal Time."
22874 (format-time-string
22875 format
22876 (apply 'encode-time
22877 (cons 0
22878 (mapcar
22879 (lambda (prop) (or (org-element-property prop timestamp) 0))
22880 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22881 '(:minute-start :hour-start :day-start :month-start
22882 :year-start)))))
22883 utc))
22885 (defun org-timestamp-split-range (timestamp &optional end)
22886 "Extract a timestamp object from a date or time range.
22888 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22889 the end of the range. Otherwise, extract its start.
22891 Return a new timestamp object sharing the same parent as
22892 TIMESTAMP."
22893 (let ((type (org-element-property :type timestamp)))
22894 (if (memq type '(active inactive diary)) timestamp
22895 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22896 ;; Set new type.
22897 (org-element-put-property
22898 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22899 ;; Copy start properties over end properties if END is
22900 ;; non-nil. Otherwise, copy end properties over `start' ones.
22901 (let ((p-alist '((:minute-start . :minute-end)
22902 (:hour-start . :hour-end)
22903 (:day-start . :day-end)
22904 (:month-start . :month-end)
22905 (:year-start . :year-end))))
22906 (dolist (p-cell p-alist)
22907 (org-element-put-property
22908 split-ts
22909 (funcall (if end 'car 'cdr) p-cell)
22910 (org-element-property
22911 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22912 ;; Eventually refresh `:raw-value'.
22913 (org-element-put-property split-ts :raw-value nil)
22914 (org-element-put-property
22915 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22917 (defun org-timestamp-translate (timestamp &optional boundary)
22918 "Apply `org-translate-time' on a TIMESTAMP object.
22919 When optional argument BOUNDARY is non-nil, it is either the
22920 symbol `start' or `end'. In this case, only translate the
22921 starting or ending part of TIMESTAMP if it is a date or time
22922 range. Otherwise, translate both parts."
22923 (if (and (not boundary)
22924 (memq (org-element-property :type timestamp)
22925 '(active-range inactive-range)))
22926 (concat
22927 (org-translate-time
22928 (org-element-property :raw-value
22929 (org-timestamp-split-range timestamp)))
22930 "--"
22931 (org-translate-time
22932 (org-element-property :raw-value
22933 (org-timestamp-split-range timestamp t))))
22934 (org-translate-time
22935 (org-element-property
22936 :raw-value
22937 (if (not boundary) timestamp
22938 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22942 ;;; Other stuff.
22944 (defun org-reftex-citation ()
22945 "Use reftex-citation to insert a citation into the buffer.
22946 This looks for a line like
22948 #+BIBLIOGRAPHY: foo plain option:-d
22950 and derives from it that foo.bib is the bibliography file relevant
22951 for this document. It then installs the necessary environment for RefTeX
22952 to work in this buffer and calls `reftex-citation' to insert a citation
22953 into the buffer.
22955 Export of such citations to both LaTeX and HTML is handled by the contributed
22956 package ox-bibtex by Taru Karttunen."
22957 (interactive)
22958 (let ((reftex-docstruct-symbol 'rds)
22959 (reftex-cite-format "\\cite{%l}")
22960 rds bib)
22961 (save-excursion
22962 (save-restriction
22963 (widen)
22964 (let ((case-fold-search t)
22965 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22966 (if (not (save-excursion
22967 (or (re-search-forward re nil t)
22968 (re-search-backward re nil t))))
22969 (error "No bibliography defined in file")
22970 (setq bib (concat (match-string 1) ".bib")
22971 rds (list (list 'bib bib)))))))
22972 (call-interactively 'reftex-citation)))
22974 ;;;; Functions extending outline functionality
22976 (defun org-beginning-of-line (&optional arg)
22977 "Go to the beginning of the current line. If that is invisible, continue
22978 to a visible line beginning. This makes the function of C-a more intuitive.
22979 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22980 first attempt, and only move to after the tags when the cursor is already
22981 beyond the end of the headline."
22982 (interactive "P")
22983 (let ((pos (point))
22984 (special (if (consp org-special-ctrl-a/e)
22985 (car org-special-ctrl-a/e)
22986 org-special-ctrl-a/e))
22987 deactivate-mark refpos)
22988 (if (org-bound-and-true-p visual-line-mode)
22989 (beginning-of-visual-line 1)
22990 (beginning-of-line 1))
22991 (if (and arg (fboundp 'move-beginning-of-line))
22992 (call-interactively 'move-beginning-of-line)
22993 (if (bobp)
22995 (backward-char 1)
22996 (if (org-truely-invisible-p)
22997 (while (and (not (bobp)) (org-truely-invisible-p))
22998 (backward-char 1)
22999 (beginning-of-line 1))
23000 (forward-char 1))))
23001 (when special
23002 (cond
23003 ((and (looking-at org-complex-heading-regexp)
23004 (= (char-after (match-end 1)) ?\ ))
23005 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23006 (point-at-eol)))
23007 (goto-char
23008 (if (eq special t)
23009 (cond ((> pos refpos) refpos)
23010 ((= pos (point)) refpos)
23011 (t (point)))
23012 (cond ((> pos (point)) (point))
23013 ((not (eq last-command this-command)) (point))
23014 (t refpos)))))
23015 ((org-at-item-p)
23016 ;; Being at an item and not looking at an the item means point
23017 ;; was previously moved to beginning of a visual line, which
23018 ;; doesn't contain the item. Therefore, do nothing special,
23019 ;; just stay here.
23020 (when (looking-at org-list-full-item-re)
23021 ;; Set special position at first white space character after
23022 ;; bullet, and check-box, if any.
23023 (let ((after-bullet
23024 (let ((box (match-end 3)))
23025 (if (not box) (match-end 1)
23026 (let ((after (char-after box)))
23027 (if (and after (= after ? )) (1+ box) box))))))
23028 ;; Special case: Move point to special position when
23029 ;; currently after it or at beginning of line.
23030 (if (eq special t)
23031 (when (or (> pos after-bullet) (= (point) pos))
23032 (goto-char after-bullet))
23033 ;; Reversed case: Move point to special position when
23034 ;; point was already at beginning of line and command is
23035 ;; repeated.
23036 (when (and (= (point) pos) (eq last-command this-command))
23037 (goto-char after-bullet))))))))
23038 (org-no-warnings
23039 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23040 (setq disable-point-adjustment
23041 (or (not (invisible-p (point)))
23042 (not (invisible-p (max (point-min) (1- (point))))))))
23044 (defun org-end-of-line (&optional arg)
23045 "Go to the end of the line.
23046 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23047 tags on the first attempt, and only move to after the tags when
23048 the cursor is already beyond the end of the headline."
23049 (interactive "P")
23050 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23051 org-special-ctrl-a/e))
23052 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23053 'end-of-visual-line)
23054 ((fboundp 'move-end-of-line) 'move-end-of-line)
23055 (t 'end-of-line)))
23056 deactivate-mark)
23057 (if (or (not special) arg) (call-interactively move-fun)
23058 (let* ((element (save-excursion (beginning-of-line)
23059 (org-element-at-point)))
23060 (type (org-element-type element)))
23061 (cond
23062 ((memq type '(headline inlinetask))
23063 (let ((pos (point)))
23064 (beginning-of-line 1)
23065 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23066 (if (eq special t)
23067 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23068 (goto-char (match-beginning 1))
23069 (goto-char (match-end 0)))
23070 (if (or (< pos (match-end 0))
23071 (not (eq this-command last-command)))
23072 (goto-char (match-end 0))
23073 (goto-char (match-beginning 1))))
23074 (call-interactively move-fun))))
23075 ((outline-invisible-p (line-end-position))
23076 ;; If element is hidden, `move-end-of-line' would put point
23077 ;; after it. Use `end-of-line' to stay on current line.
23078 (call-interactively 'end-of-line))
23079 (t (call-interactively move-fun)))))
23080 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23081 (setq disable-point-adjustment
23082 (or (not (invisible-p (point)))
23083 (not (invisible-p (max (point-min) (1- (point))))))))
23085 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23086 (define-key org-mode-map "\C-e" 'org-end-of-line)
23088 (defun org-backward-sentence (&optional arg)
23089 "Go to beginning of sentence, or beginning of table field.
23090 This will call `backward-sentence' or `org-table-beginning-of-field',
23091 depending on context."
23092 (interactive "P")
23093 (cond
23094 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
23095 (t (call-interactively 'backward-sentence))))
23097 (defun org-forward-sentence (&optional arg)
23098 "Go to end of sentence, or end of table field.
23099 This will call `forward-sentence' or `org-table-end-of-field',
23100 depending on context."
23101 (interactive "P")
23102 (cond
23103 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
23104 (t (call-interactively 'forward-sentence))))
23106 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23107 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23109 (defun org-kill-line (&optional arg)
23110 "Kill line, to tags or end of line."
23111 (interactive "P")
23112 (cond
23113 ((or (not org-special-ctrl-k)
23114 (bolp)
23115 (not (org-at-heading-p)))
23116 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23117 org-ctrl-k-protect-subtree)
23118 (if (or (eq org-ctrl-k-protect-subtree 'error)
23119 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23120 (user-error "C-k aborted as it would kill a hidden subtree")))
23121 (call-interactively
23122 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23123 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23124 (kill-region (point) (match-beginning 1))
23125 (org-set-tags nil t))
23126 (t (kill-region (point) (point-at-eol)))))
23128 (define-key org-mode-map "\C-k" 'org-kill-line)
23130 (defun org-yank (&optional arg)
23131 "Yank. If the kill is a subtree, treat it specially.
23132 This command will look at the current kill and check if is a single
23133 subtree, or a series of subtrees[1]. If it passes the test, and if the
23134 cursor is at the beginning of a line or after the stars of a currently
23135 empty headline, then the yank is handled specially. How exactly depends
23136 on the value of the following variables, both set by default.
23138 org-yank-folded-subtrees
23139 When set, the subtree(s) will be folded after insertion, but only
23140 if doing so would now swallow text after the yanked text.
23142 org-yank-adjusted-subtrees
23143 When set, the subtree will be promoted or demoted in order to
23144 fit into the local outline tree structure, which means that the level
23145 will be adjusted so that it becomes the smaller one of the two
23146 *visible* surrounding headings.
23148 Any prefix to this command will cause `yank' to be called directly with
23149 no special treatment. In particular, a simple \\[universal-argument] prefix \
23150 will just
23151 plainly yank the text as it is.
23153 \[1] The test checks if the first non-white line is a heading
23154 and if there are no other headings with fewer stars."
23155 (interactive "P")
23156 (org-yank-generic 'yank arg))
23158 (defun org-yank-generic (command arg)
23159 "Perform some yank-like command.
23161 This function implements the behavior described in the `org-yank'
23162 documentation. However, it has been generalized to work for any
23163 interactive command with similar behavior."
23165 ;; pretend to be command COMMAND
23166 (setq this-command command)
23168 (if arg
23169 (call-interactively command)
23171 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23172 (and (org-kill-is-subtree-p)
23173 (or (bolp)
23174 (and (looking-at "[ \t]*$")
23175 (string-match
23176 "\\`\\*+\\'"
23177 (buffer-substring (point-at-bol) (point)))))))
23178 swallowp)
23179 (cond
23180 ((and subtreep org-yank-folded-subtrees)
23181 (let ((beg (point))
23182 end)
23183 (if (and subtreep org-yank-adjusted-subtrees)
23184 (org-paste-subtree nil nil 'for-yank)
23185 (call-interactively command))
23187 (setq end (point))
23188 (goto-char beg)
23189 (when (and (bolp) subtreep
23190 (not (setq swallowp
23191 (org-yank-folding-would-swallow-text beg end))))
23192 (org-with-limited-levels
23193 (or (looking-at org-outline-regexp)
23194 (re-search-forward org-outline-regexp-bol end t))
23195 (while (and (< (point) end) (looking-at org-outline-regexp))
23196 (hide-subtree)
23197 (org-cycle-show-empty-lines 'folded)
23198 (condition-case nil
23199 (outline-forward-same-level 1)
23200 (error (goto-char end))))))
23201 (when swallowp
23202 (message
23203 "Inserted text not folded because that would swallow text"))
23205 (goto-char end)
23206 (skip-chars-forward " \t\n\r")
23207 (beginning-of-line 1)
23208 (push-mark beg 'nomsg)))
23209 ((and subtreep org-yank-adjusted-subtrees)
23210 (let ((beg (point-at-bol)))
23211 (org-paste-subtree nil nil 'for-yank)
23212 (push-mark beg 'nomsg)))
23214 (call-interactively command))))))
23216 (defun org-yank-folding-would-swallow-text (beg end)
23217 "Would hide-subtree at BEG swallow any text after END?"
23218 (let (level)
23219 (org-with-limited-levels
23220 (save-excursion
23221 (goto-char beg)
23222 (when (or (looking-at org-outline-regexp)
23223 (re-search-forward org-outline-regexp-bol end t))
23224 (setq level (org-outline-level)))
23225 (goto-char end)
23226 (skip-chars-forward " \t\r\n\v\f")
23227 (if (or (eobp)
23228 (and (bolp) (looking-at org-outline-regexp)
23229 (<= (org-outline-level) level)))
23230 nil ; Nothing would be swallowed
23231 t))))) ; something would swallow
23233 (define-key org-mode-map "\C-y" 'org-yank)
23235 (defun org-truely-invisible-p ()
23236 "Check if point is at a character currently not visible.
23237 This version does not only check the character property, but also
23238 `visible-mode'."
23239 ;; Early versions of noutline don't have `outline-invisible-p'.
23240 (if (org-bound-and-true-p visible-mode)
23242 (outline-invisible-p)))
23244 (defun org-invisible-p2 ()
23245 "Check if point is at a character currently not visible."
23246 (save-excursion
23247 (if (and (eolp) (not (bobp))) (backward-char 1))
23248 ;; Early versions of noutline don't have `outline-invisible-p'.
23249 (outline-invisible-p)))
23251 (defun org-back-to-heading (&optional invisible-ok)
23252 "Call `outline-back-to-heading', but provide a better error message."
23253 (condition-case nil
23254 (outline-back-to-heading invisible-ok)
23255 (error (error "Before first headline at position %d in buffer %s"
23256 (point) (current-buffer)))))
23258 (defun org-before-first-heading-p ()
23259 "Before first heading?"
23260 (save-excursion
23261 (end-of-line)
23262 (null (re-search-backward org-outline-regexp-bol nil t))))
23264 (defun org-at-heading-p (&optional ignored)
23265 (outline-on-heading-p t))
23266 ;; Compatibility alias with Org versions < 7.8.03
23267 (defalias 'org-on-heading-p 'org-at-heading-p)
23269 (defun org-at-comment-p nil
23270 "Is cursor in a line starting with a # character?"
23271 (save-excursion
23272 (beginning-of-line)
23273 (looking-at "^#")))
23275 (defun org-at-drawer-p nil
23276 "Is cursor at a drawer keyword?"
23277 (save-excursion
23278 (move-beginning-of-line 1)
23279 (looking-at org-drawer-regexp)))
23281 (defun org-at-block-p nil
23282 "Is cursor at a block keyword?"
23283 (save-excursion
23284 (move-beginning-of-line 1)
23285 (looking-at org-block-regexp)))
23287 (defun org-point-at-end-of-empty-headline ()
23288 "If point is at the end of an empty headline, return t, else nil.
23289 If the heading only contains a TODO keyword, it is still still considered
23290 empty."
23291 (and (looking-at "[ \t]*$")
23292 (when org-todo-line-regexp
23293 (save-excursion
23294 (beginning-of-line 1)
23295 (let ((case-fold-search nil))
23296 (looking-at org-todo-line-regexp)
23297 (string= (match-string 3) ""))))))
23299 (defun org-at-heading-or-item-p ()
23300 (or (org-at-heading-p) (org-at-item-p)))
23302 (defun org-at-target-p ()
23303 (or (org-in-regexp org-radio-target-regexp)
23304 (org-in-regexp org-target-regexp)))
23305 ;; Compatibility alias with Org versions < 7.8.03
23306 (defalias 'org-on-target-p 'org-at-target-p)
23308 (defun org-up-heading-all (arg)
23309 "Move to the heading line of which the present line is a subheading.
23310 This function considers both visible and invisible heading lines.
23311 With argument, move up ARG levels."
23312 (if (fboundp 'outline-up-heading-all)
23313 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23314 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23316 (defun org-up-heading-safe ()
23317 "Move to the heading line of which the present line is a subheading.
23318 This version will not throw an error. It will return the level of the
23319 headline found, or nil if no higher level is found.
23321 Also, this function will be a lot faster than `outline-up-heading',
23322 because it relies on stars being the outline starters. This can really
23323 make a significant difference in outlines with very many siblings."
23324 (let (start-level re)
23325 (org-back-to-heading t)
23326 (setq start-level (funcall outline-level))
23327 (if (equal start-level 1)
23329 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23330 (if (re-search-backward re nil t)
23331 (funcall outline-level)))))
23333 (defun org-first-sibling-p ()
23334 "Is this heading the first child of its parents?"
23335 (interactive)
23336 (let ((re org-outline-regexp-bol)
23337 level l)
23338 (unless (org-at-heading-p t)
23339 (user-error "Not at a heading"))
23340 (setq level (funcall outline-level))
23341 (save-excursion
23342 (if (not (re-search-backward re nil t))
23344 (setq l (funcall outline-level))
23345 (< l level)))))
23347 (defun org-goto-sibling (&optional previous)
23348 "Goto the next sibling, even if it is invisible.
23349 When PREVIOUS is set, go to the previous sibling instead. Returns t
23350 when a sibling was found. When none is found, return nil and don't
23351 move point."
23352 (let ((fun (if previous 're-search-backward 're-search-forward))
23353 (pos (point))
23354 (re org-outline-regexp-bol)
23355 level l)
23356 (when (condition-case nil (org-back-to-heading t) (error nil))
23357 (setq level (funcall outline-level))
23358 (catch 'exit
23359 (or previous (forward-char 1))
23360 (while (funcall fun re nil t)
23361 (setq l (funcall outline-level))
23362 (when (< l level) (goto-char pos) (throw 'exit nil))
23363 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23364 (goto-char pos)
23365 nil))))
23367 (defun org-show-siblings ()
23368 "Show all siblings of the current headline."
23369 (save-excursion
23370 (while (org-goto-sibling) (org-flag-heading nil)))
23371 (save-excursion
23372 (while (org-goto-sibling 'previous)
23373 (org-flag-heading nil))))
23375 (defun org-goto-first-child ()
23376 "Goto the first child, even if it is invisible.
23377 Return t when a child was found. Otherwise don't move point and
23378 return nil."
23379 (let (level (pos (point)) (re org-outline-regexp-bol))
23380 (when (condition-case nil (org-back-to-heading t) (error nil))
23381 (setq level (outline-level))
23382 (forward-char 1)
23383 (if (and (re-search-forward re nil t) (> (outline-level) level))
23384 (progn (goto-char (match-beginning 0)) t)
23385 (goto-char pos) nil))))
23387 (defun org-show-hidden-entry ()
23388 "Show an entry where even the heading is hidden."
23389 (save-excursion
23390 (org-show-entry)))
23392 (defun org-flag-heading (flag &optional entry)
23393 "Flag the current heading. FLAG non-nil means make invisible.
23394 When ENTRY is non-nil, show the entire entry."
23395 (save-excursion
23396 (org-back-to-heading t)
23397 ;; Check if we should show the entire entry
23398 (if entry
23399 (progn
23400 (org-show-entry)
23401 (save-excursion
23402 (and (outline-next-heading)
23403 (org-flag-heading nil))))
23404 (outline-flag-region (max (point-min) (1- (point)))
23405 (save-excursion (outline-end-of-heading) (point))
23406 flag))))
23408 (defun org-get-next-sibling ()
23409 "Move to next heading of the same level, and return point.
23410 If there is no such heading, return nil.
23411 This is like outline-next-sibling, but invisible headings are ok."
23412 (let ((level (funcall outline-level)))
23413 (outline-next-heading)
23414 (while (and (not (eobp)) (> (funcall outline-level) level))
23415 (outline-next-heading))
23416 (if (or (eobp) (< (funcall outline-level) level))
23418 (point))))
23420 (defun org-get-last-sibling ()
23421 "Move to previous heading of the same level, and return point.
23422 If there is no such heading, return nil."
23423 (let ((opoint (point))
23424 (level (funcall outline-level)))
23425 (outline-previous-heading)
23426 (when (and (/= (point) opoint) (outline-on-heading-p t))
23427 (while (and (> (funcall outline-level) level)
23428 (not (bobp)))
23429 (outline-previous-heading))
23430 (if (< (funcall outline-level) level)
23432 (point)))))
23434 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23435 "Goto to the end of a subtree."
23436 ;; This contains an exact copy of the original function, but it uses
23437 ;; `org-back-to-heading', to make it work also in invisible
23438 ;; trees. And is uses an invisible-ok argument.
23439 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23440 ;; Furthermore, when used inside Org, finding the end of a large subtree
23441 ;; with many children and grandchildren etc, this can be much faster
23442 ;; than the outline version.
23443 (org-back-to-heading invisible-ok)
23444 (let ((first t)
23445 (level (funcall outline-level)))
23446 (if (and (derived-mode-p 'org-mode) (< level 1000))
23447 ;; A true heading (not a plain list item), in Org-mode
23448 ;; This means we can easily find the end by looking
23449 ;; only for the right number of stars. Using a regexp to do
23450 ;; this is so much faster than using a Lisp loop.
23451 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23452 (forward-char 1)
23453 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23454 ;; something else, do it the slow way
23455 (while (and (not (eobp))
23456 (or first (> (funcall outline-level) level)))
23457 (setq first nil)
23458 (outline-next-heading)))
23459 (unless to-heading
23460 (if (memq (preceding-char) '(?\n ?\^M))
23461 (progn
23462 ;; Go to end of line before heading
23463 (forward-char -1)
23464 (if (memq (preceding-char) '(?\n ?\^M))
23465 ;; leave blank line before heading
23466 (forward-char -1))))))
23467 (point))
23469 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23470 "Use Org version in org-mode, for dramatic speed-up."
23471 (if (derived-mode-p 'org-mode)
23472 (progn
23473 (org-end-of-subtree nil t)
23474 (unless (eobp) (backward-char 1)))
23475 ad-do-it))
23477 (defun org-end-of-meta-data-and-drawers ()
23478 "Jump to the first text after meta data and drawers in the current entry.
23479 This will move over empty lines, lines with planning time stamps,
23480 clocking lines, and drawers."
23481 (org-back-to-heading t)
23482 (let ((end (save-excursion (outline-next-heading) (point)))
23483 (re (concat "\\(" org-drawer-regexp "\\)"
23484 "\\|" "[ \t]*" org-keyword-time-regexp)))
23485 (forward-line 1)
23486 (while (re-search-forward re end t)
23487 (if (not (match-end 1))
23488 ;; empty or planning line
23489 (forward-line 1)
23490 ;; a drawer, find the end
23491 (re-search-forward "^[ \t]*:END:" end 'move)
23492 (forward-line 1)))
23493 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23494 (point)))
23496 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23497 "Move forward to the ARG'th subheading at same level as this one.
23498 Stop at the first and last subheadings of a superior heading.
23499 Normally this only looks at visible headings, but when INVISIBLE-OK is
23500 non-nil it will also look at invisible ones."
23501 (interactive "p")
23502 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23503 (if (and arg (< arg 0))
23504 (goto-char (point-min))
23505 (outline-next-heading))
23506 (org-at-heading-p)
23507 (let ((level (- (match-end 0) (match-beginning 0) 1))
23508 (f (if (and arg (< arg 0))
23509 're-search-backward
23510 're-search-forward))
23511 (count (if arg (abs arg) 1))
23512 (result (point)))
23513 (while (and (prog1 (> count 0)
23514 (forward-char (if (and arg (< arg 0)) -1 1)))
23515 (funcall f org-outline-regexp-bol nil 'move))
23516 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23517 (cond ((< l level) (setq count 0))
23518 ((and (= l level)
23519 (or invisible-ok
23520 (progn
23521 (goto-char (line-beginning-position))
23522 (not (outline-invisible-p)))))
23523 (setq count (1- count))
23524 (when (eq l level)
23525 (setq result (point)))))))
23526 (goto-char result))
23527 (beginning-of-line 1)))
23529 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23530 "Move backward to the ARG'th subheading at same level as this one.
23531 Stop at the first and last subheadings of a superior heading."
23532 (interactive "p")
23533 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23535 (defun org-next-block (arg &optional backward block-regexp)
23536 "Jump to the next block.
23537 With a prefix argument ARG, jump forward ARG many source blocks.
23538 When BACKWARD is non-nil, jump to the previous block.
23539 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23540 (interactive "p")
23541 (let ((re (or block-regexp org-block-regexp))
23542 (re-search-fn (or (and backward 're-search-backward)
23543 're-search-forward)))
23544 (if (looking-at re) (forward-char 1))
23545 (condition-case nil
23546 (funcall re-search-fn re nil nil arg)
23547 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23548 (goto-char (match-beginning 0)) (org-show-context)))
23550 (defun org-previous-block (arg &optional block-regexp)
23551 "Jump to the previous block.
23552 With a prefix argument ARG, jump backward ARG many source blocks.
23553 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23554 (interactive "p")
23555 (org-next-block arg t block-regexp))
23557 (defun org-forward-paragraph ()
23558 "Move forward to beginning of next paragraph or equivalent.
23560 The function moves point to the beginning of the next visible
23561 structural element, which can be a paragraph, a table, a list
23562 item, etc. It also provides some special moves for convenience:
23564 - On an affiliated keyword, jump to the beginning of the
23565 relative element.
23566 - On an item or a footnote definition, move to the second
23567 element inside, if any.
23568 - On a table or a property drawer, jump after it.
23569 - On a verse or source block, stop after blank lines."
23570 (interactive)
23571 (when (eobp) (user-error "Cannot move further down"))
23572 (let* ((deactivate-mark nil)
23573 (element (org-element-at-point))
23574 (type (org-element-type element))
23575 (post-affiliated (org-element-property :post-affiliated element))
23576 (contents-begin (org-element-property :contents-begin element))
23577 (contents-end (org-element-property :contents-end element))
23578 (end (let ((end (org-element-property :end element)) (parent element))
23579 (while (and (setq parent (org-element-property :parent parent))
23580 (= (org-element-property :contents-end parent) end))
23581 (setq end (org-element-property :end parent)))
23582 end)))
23583 (cond ((not element)
23584 (skip-chars-forward " \r\t\n")
23585 (or (eobp) (beginning-of-line)))
23586 ;; On affiliated keywords, move to element's beginning.
23587 ((and post-affiliated (< (point) post-affiliated))
23588 (goto-char post-affiliated))
23589 ;; At a table row, move to the end of the table. Similarly,
23590 ;; at a node property, move to the end of the property
23591 ;; drawer.
23592 ((memq type '(node-property table-row))
23593 (goto-char (org-element-property
23594 :end (org-element-property :parent element))))
23595 ((memq type '(property-drawer table)) (goto-char end))
23596 ;; Consider blank lines as separators in verse and source
23597 ;; blocks to ease editing.
23598 ((memq type '(src-block verse-block))
23599 (when (eq type 'src-block)
23600 (setq contents-end
23601 (save-excursion (goto-char end)
23602 (skip-chars-backward " \r\t\n")
23603 (line-beginning-position))))
23604 (beginning-of-line)
23605 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23606 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23607 (goto-char end)
23608 (skip-chars-forward " \r\t\n")
23609 (if (= (point) contents-end) (goto-char end)
23610 (beginning-of-line))))
23611 ;; With no contents, just skip element.
23612 ((not contents-begin) (goto-char end))
23613 ;; If contents are invisible, skip the element altogether.
23614 ((outline-invisible-p (line-end-position))
23615 (case type
23616 (headline
23617 (org-with-limited-levels (outline-next-visible-heading 1)))
23618 ;; At a plain list, make sure we move to the next item
23619 ;; instead of skipping the whole list.
23620 (plain-list (forward-char)
23621 (org-forward-paragraph))
23622 (otherwise (goto-char end))))
23623 ((>= (point) contents-end) (goto-char end))
23624 ((>= (point) contents-begin)
23625 ;; This can only happen on paragraphs and plain lists.
23626 (case type
23627 (paragraph (goto-char end))
23628 ;; At a plain list, try to move to second element in
23629 ;; first item, if possible.
23630 (plain-list (end-of-line)
23631 (org-forward-paragraph))))
23632 ;; When contents start on the middle of a line (e.g. in
23633 ;; items and footnote definitions), try to reach first
23634 ;; element starting after current line.
23635 ((> (line-end-position) contents-begin)
23636 (end-of-line)
23637 (org-forward-paragraph))
23638 (t (goto-char contents-begin)))))
23640 (defun org-backward-paragraph ()
23641 "Move backward to start of previous paragraph or equivalent.
23643 The function moves point to the beginning of the current
23644 structural element, which can be a paragraph, a table, a list
23645 item, etc., or to the beginning of the previous visible one if
23646 point is already there. It also provides some special moves for
23647 convenience:
23649 - On an affiliated keyword, jump to the first one.
23650 - On a table or a property drawer, move to its beginning.
23651 - On a verse or source block, stop before blank lines."
23652 (interactive)
23653 (when (bobp) (user-error "Cannot move further up"))
23654 (let* ((deactivate-mark nil)
23655 (element (org-element-at-point))
23656 (type (org-element-type element))
23657 (contents-begin (org-element-property :contents-begin element))
23658 (contents-end (org-element-property :contents-end element))
23659 (post-affiliated (org-element-property :post-affiliated element))
23660 (begin (org-element-property :begin element)))
23661 (cond
23662 ((not element) (goto-char (point-min)))
23663 ((= (point) begin)
23664 (backward-char)
23665 (org-backward-paragraph))
23666 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23667 ((memq type '(node-property table-row))
23668 (goto-char (org-element-property
23669 :post-affiliated (org-element-property :parent element))))
23670 ((memq type '(property-drawer table)) (goto-char begin))
23671 ((memq type '(src-block verse-block))
23672 (when (eq type 'src-block)
23673 (setq contents-begin
23674 (save-excursion (goto-char begin) (forward-line) (point))))
23675 (if (= (point) contents-begin) (goto-char post-affiliated)
23676 ;; Inside a verse block, see blank lines as paragraph
23677 ;; separators.
23678 (let ((origin (point)))
23679 (skip-chars-backward " \r\t\n" contents-begin)
23680 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23681 (skip-chars-forward " \r\t\n" origin)
23682 (if (= (point) origin) (goto-char contents-begin)
23683 (beginning-of-line))))))
23684 ((not contents-begin) (goto-char (or post-affiliated begin)))
23685 ((eq type 'paragraph)
23686 (goto-char contents-begin)
23687 ;; When at first paragraph in an item or a footnote definition,
23688 ;; move directly to beginning of line.
23689 (let ((parent-contents
23690 (org-element-property
23691 :contents-begin (org-element-property :parent element))))
23692 (when (and parent-contents (= parent-contents contents-begin))
23693 (beginning-of-line))))
23694 ;; At the end of a greater element, move to the beginning of the
23695 ;; last element within.
23696 ((>= (point) contents-end)
23697 (goto-char (1- contents-end))
23698 (org-backward-paragraph))
23699 (t (goto-char (or post-affiliated begin))))
23700 ;; Ensure we never leave point invisible.
23701 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23703 (defun org-forward-element ()
23704 "Move forward by one element.
23705 Move to the next element at the same level, when possible."
23706 (interactive)
23707 (cond ((eobp) (user-error "Cannot move further down"))
23708 ((org-with-limited-levels (org-at-heading-p))
23709 (let ((origin (point)))
23710 (goto-char (org-end-of-subtree nil t))
23711 (unless (org-with-limited-levels (org-at-heading-p))
23712 (goto-char origin)
23713 (user-error "Cannot move further down"))))
23715 (let* ((elem (org-element-at-point))
23716 (end (org-element-property :end elem))
23717 (parent (org-element-property :parent elem)))
23718 (cond ((and parent (= (org-element-property :contents-end parent) end))
23719 (goto-char (org-element-property :end parent)))
23720 ((integer-or-marker-p end) (goto-char end))
23721 (t (message "No element at point")))))))
23723 (defun org-backward-element ()
23724 "Move backward by one element.
23725 Move to the previous element at the same level, when possible."
23726 (interactive)
23727 (cond ((bobp) (user-error "Cannot move further up"))
23728 ((org-with-limited-levels (org-at-heading-p))
23729 ;; At a headline, move to the previous one, if any, or stay
23730 ;; here.
23731 (let ((origin (point)))
23732 (org-with-limited-levels (org-backward-heading-same-level 1))
23733 ;; When current headline has no sibling above, move to its
23734 ;; parent.
23735 (when (= (point) origin)
23736 (or (org-with-limited-levels (org-up-heading-safe))
23737 (progn (goto-char origin)
23738 (user-error "Cannot move further up"))))))
23740 (let* ((elem (org-element-at-point))
23741 (beg (org-element-property :begin elem)))
23742 (cond
23743 ;; Move to beginning of current element if point isn't
23744 ;; there already.
23745 ((null beg) (message "No element at point"))
23746 ((/= (point) beg) (goto-char beg))
23747 (t (goto-char beg)
23748 (skip-chars-backward " \r\t\n")
23749 (unless (bobp)
23750 (let ((prev (org-element-at-point)))
23751 (goto-char (org-element-property :begin prev))
23752 (while (and (setq prev (org-element-property :parent prev))
23753 (<= (org-element-property :end prev) beg))
23754 (goto-char (org-element-property :begin prev)))))))))))
23756 (defun org-up-element ()
23757 "Move to upper element."
23758 (interactive)
23759 (if (org-with-limited-levels (org-at-heading-p))
23760 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23761 (let* ((elem (org-element-at-point))
23762 (parent (org-element-property :parent elem)))
23763 (if parent (goto-char (org-element-property :begin parent))
23764 (if (org-with-limited-levels (org-before-first-heading-p))
23765 (user-error "No surrounding element")
23766 (org-with-limited-levels (org-back-to-heading)))))))
23768 (defvar org-element-greater-elements)
23769 (defun org-down-element ()
23770 "Move to inner element."
23771 (interactive)
23772 (let ((element (org-element-at-point)))
23773 (cond
23774 ((memq (org-element-type element) '(plain-list table))
23775 (goto-char (org-element-property :contents-begin element))
23776 (forward-char))
23777 ((memq (org-element-type element) org-element-greater-elements)
23778 ;; If contents are hidden, first disclose them.
23779 (when (outline-invisible-p (line-end-position)) (org-cycle))
23780 (goto-char (or (org-element-property :contents-begin element)
23781 (user-error "No content for this element"))))
23782 (t (user-error "No inner element")))))
23784 (defun org-drag-element-backward ()
23785 "Move backward element at point."
23786 (interactive)
23787 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23788 (let* ((elem (org-element-at-point))
23789 (prev-elem
23790 (save-excursion
23791 (goto-char (org-element-property :begin elem))
23792 (skip-chars-backward " \r\t\n")
23793 (unless (bobp)
23794 (let* ((beg (org-element-property :begin elem))
23795 (prev (org-element-at-point))
23796 (up prev))
23797 (while (and (setq up (org-element-property :parent up))
23798 (<= (org-element-property :end prev) beg))
23799 (setq prev up))
23800 prev)))))
23801 ;; Error out if no previous element or previous element is
23802 ;; a parent of the current one.
23803 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23804 (user-error "Cannot drag element backward")
23805 (let ((pos (point)))
23806 (org-element-swap-A-B prev-elem elem)
23807 (goto-char (+ (org-element-property :begin prev-elem)
23808 (- pos (org-element-property :begin elem)))))))))
23810 (defun org-drag-element-forward ()
23811 "Move forward element at point."
23812 (interactive)
23813 (let* ((pos (point))
23814 (elem (org-element-at-point)))
23815 (when (= (point-max) (org-element-property :end elem))
23816 (user-error "Cannot drag element forward"))
23817 (goto-char (org-element-property :end elem))
23818 (let ((next-elem (org-element-at-point)))
23819 (when (or (org-element-nested-p elem next-elem)
23820 (and (eq (org-element-type next-elem) 'headline)
23821 (not (eq (org-element-type elem) 'headline))))
23822 (goto-char pos)
23823 (user-error "Cannot drag element forward"))
23824 ;; Compute new position of point: it's shifted by NEXT-ELEM
23825 ;; body's length (without final blanks) and by the length of
23826 ;; blanks between ELEM and NEXT-ELEM.
23827 (let ((size-next (- (save-excursion
23828 (goto-char (org-element-property :end next-elem))
23829 (skip-chars-backward " \r\t\n")
23830 (forward-line)
23831 ;; Small correction if buffer doesn't end
23832 ;; with a newline character.
23833 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23834 (org-element-property :begin next-elem)))
23835 (size-blank (- (org-element-property :end elem)
23836 (save-excursion
23837 (goto-char (org-element-property :end elem))
23838 (skip-chars-backward " \r\t\n")
23839 (forward-line)
23840 (point)))))
23841 (org-element-swap-A-B elem next-elem)
23842 (goto-char (+ pos size-next size-blank))))))
23844 (defun org-drag-line-forward (arg)
23845 "Drag the line at point ARG lines forward."
23846 (interactive "p")
23847 (dotimes (n (abs arg))
23848 (let ((c (current-column)))
23849 (if (< 0 arg)
23850 (progn
23851 (beginning-of-line 2)
23852 (transpose-lines 1)
23853 (beginning-of-line 0))
23854 (transpose-lines 1)
23855 (beginning-of-line -1))
23856 (org-move-to-column c))))
23858 (defun org-drag-line-backward (arg)
23859 "Drag the line at point ARG lines backward."
23860 (interactive "p")
23861 (org-drag-line-forward (- arg)))
23863 (defun org-mark-element ()
23864 "Put point at beginning of this element, mark at end.
23866 Interactively, if this command is repeated or (in Transient Mark
23867 mode) if the mark is active, it marks the next element after the
23868 ones already marked."
23869 (interactive)
23870 (let (deactivate-mark)
23871 (if (and (org-called-interactively-p 'any)
23872 (or (and (eq last-command this-command) (mark t))
23873 (and transient-mark-mode mark-active)))
23874 (set-mark
23875 (save-excursion
23876 (goto-char (mark))
23877 (goto-char (org-element-property :end (org-element-at-point)))))
23878 (let ((element (org-element-at-point)))
23879 (end-of-line)
23880 (push-mark (org-element-property :end element) t t)
23881 (goto-char (org-element-property :begin element))))))
23883 (defun org-narrow-to-element ()
23884 "Narrow buffer to current element."
23885 (interactive)
23886 (let ((elem (org-element-at-point)))
23887 (cond
23888 ((eq (car elem) 'headline)
23889 (narrow-to-region
23890 (org-element-property :begin elem)
23891 (org-element-property :end elem)))
23892 ((memq (car elem) org-element-greater-elements)
23893 (narrow-to-region
23894 (org-element-property :contents-begin elem)
23895 (org-element-property :contents-end elem)))
23897 (narrow-to-region
23898 (org-element-property :begin elem)
23899 (org-element-property :end elem))))))
23901 (defun org-transpose-element ()
23902 "Transpose current and previous elements, keeping blank lines between.
23903 Point is moved after both elements."
23904 (interactive)
23905 (org-skip-whitespace)
23906 (let ((end (org-element-property :end (org-element-at-point))))
23907 (org-drag-element-backward)
23908 (goto-char end)))
23910 (defun org-unindent-buffer ()
23911 "Un-indent the visible part of the buffer.
23912 Relative indentation (between items, inside blocks, etc.) isn't
23913 modified."
23914 (interactive)
23915 (unless (eq major-mode 'org-mode)
23916 (user-error "Cannot un-indent a buffer not in Org mode"))
23917 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23918 unindent-tree ; For byte-compiler.
23919 (unindent-tree
23920 (function
23921 (lambda (contents)
23922 (mapc
23923 (lambda (element)
23924 (if (memq (org-element-type element) '(headline section))
23925 (funcall unindent-tree (org-element-contents element))
23926 (save-excursion
23927 (save-restriction
23928 (narrow-to-region
23929 (org-element-property :begin element)
23930 (org-element-property :end element))
23931 (org-do-remove-indentation)))))
23932 (reverse contents))))))
23933 (funcall unindent-tree (org-element-contents parse-tree))))
23935 (defun org-show-subtree ()
23936 "Show everything after this heading at deeper levels."
23937 (interactive)
23938 (outline-flag-region
23939 (point)
23940 (save-excursion
23941 (org-end-of-subtree t t))
23942 nil))
23944 (defun org-show-entry ()
23945 "Show the body directly following this heading.
23946 Show the heading too, if it is currently invisible."
23947 (interactive)
23948 (save-excursion
23949 (condition-case nil
23950 (progn
23951 (org-back-to-heading t)
23952 (outline-flag-region
23953 (max (point-min) (1- (point)))
23954 (save-excursion
23955 (if (re-search-forward
23956 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23957 (match-beginning 1)
23958 (point-max)))
23959 nil)
23960 (org-cycle-hide-drawers 'children))
23961 (error nil))))
23963 (defun org-make-options-regexp (kwds &optional extra)
23964 "Make a regular expression for keyword lines."
23965 (concat
23966 "^#\\+\\("
23967 (mapconcat 'regexp-quote kwds "\\|")
23968 (if extra (concat "\\|" extra))
23969 "\\):[ \t]*\\(.*\\)"))
23971 ;; Make isearch reveal the necessary context
23972 (defun org-isearch-end ()
23973 "Reveal context after isearch exits."
23974 (when isearch-success ; only if search was successful
23975 (if (featurep 'xemacs)
23976 ;; Under XEmacs, the hook is run in the correct place,
23977 ;; we directly show the context.
23978 (org-show-context 'isearch)
23979 ;; In Emacs the hook runs *before* restoring the overlays.
23980 ;; So we have to use a one-time post-command-hook to do this.
23981 ;; (Emacs 22 has a special variable, see function `org-mode')
23982 (unless (and (boundp 'isearch-mode-end-hook-quit)
23983 isearch-mode-end-hook-quit)
23984 ;; Only when the isearch was not quitted.
23985 (org-add-hook 'post-command-hook 'org-isearch-post-command
23986 'append 'local)))
23987 (org-fix-ellipsis-at-bol)))
23989 (defun org-isearch-post-command ()
23990 "Remove self from hook, and show context."
23991 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23992 (org-show-context 'isearch))
23995 ;;;; Integration with and fixes for other packages
23997 ;;; Imenu support
23999 (defvar org-imenu-markers nil
24000 "All markers currently used by Imenu.")
24001 (make-variable-buffer-local 'org-imenu-markers)
24003 (defun org-imenu-new-marker (&optional pos)
24004 "Return a new marker for use by Imenu, and remember the marker."
24005 (let ((m (make-marker)))
24006 (move-marker m (or pos (point)))
24007 (push m org-imenu-markers)
24010 (defun org-imenu-get-tree ()
24011 "Produce the index for Imenu."
24012 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24013 (setq org-imenu-markers nil)
24014 (let* ((n org-imenu-depth)
24015 (re (concat "^" (org-get-limited-outline-regexp)))
24016 (subs (make-vector (1+ n) nil))
24017 (last-level 0)
24018 m level head0 head)
24019 (save-excursion
24020 (save-restriction
24021 (widen)
24022 (goto-char (point-max))
24023 (while (re-search-backward re nil t)
24024 (setq level (org-reduced-level (funcall outline-level)))
24025 (when (and (<= level n)
24026 (looking-at org-complex-heading-regexp)
24027 (setq head0 (org-match-string-no-properties 4)))
24028 (setq head (org-link-display-format head0)
24029 m (org-imenu-new-marker))
24030 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24031 (if (>= level last-level)
24032 (push (cons head m) (aref subs level))
24033 (push (cons head (aref subs (1+ level))) (aref subs level))
24034 (loop for i from (1+ level) to n do (aset subs i nil)))
24035 (setq last-level level)))))
24036 (aref subs 1)))
24038 (eval-after-load "imenu"
24039 '(progn
24040 (add-hook 'imenu-after-jump-hook
24041 (lambda ()
24042 (if (derived-mode-p 'org-mode)
24043 (org-show-context 'org-goto))))))
24045 (defun org-link-display-format (link)
24046 "Replace a link with its the description.
24047 If there is no description, use the link target."
24048 (save-match-data
24049 (if (string-match org-bracket-link-analytic-regexp link)
24050 (replace-match (if (match-end 5)
24051 (match-string 5 link)
24052 (concat (match-string 1 link)
24053 (match-string 3 link)))
24054 nil t link)
24055 link)))
24057 (defun org-toggle-link-display ()
24058 "Toggle the literal or descriptive display of links."
24059 (interactive)
24060 (if org-descriptive-links
24061 (progn (org-remove-from-invisibility-spec '(org-link))
24062 (org-restart-font-lock)
24063 (setq org-descriptive-links nil))
24064 (progn (add-to-invisibility-spec '(org-link))
24065 (org-restart-font-lock)
24066 (setq org-descriptive-links t))))
24068 ;; Speedbar support
24070 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24071 "Overlay marking the agenda restriction line in speedbar.")
24072 (overlay-put org-speedbar-restriction-lock-overlay
24073 'face 'org-agenda-restriction-lock)
24074 (overlay-put org-speedbar-restriction-lock-overlay
24075 'help-echo "Agendas are currently limited to this item.")
24076 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24078 (defun org-speedbar-set-agenda-restriction ()
24079 "Restrict future agenda commands to the location at point in speedbar.
24080 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24081 (interactive)
24082 (require 'org-agenda)
24083 (let (p m tp np dir txt)
24084 (cond
24085 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24086 'org-imenu t))
24087 (setq m (get-text-property p 'org-imenu-marker))
24088 (with-current-buffer (marker-buffer m)
24089 (goto-char m)
24090 (org-agenda-set-restriction-lock 'subtree)))
24091 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24092 'speedbar-function 'speedbar-find-file))
24093 (setq tp (previous-single-property-change
24094 (1+ p) 'speedbar-function)
24095 np (next-single-property-change
24096 tp 'speedbar-function)
24097 dir (speedbar-line-directory)
24098 txt (buffer-substring-no-properties (or tp (point-min))
24099 (or np (point-max))))
24100 (with-current-buffer (find-file-noselect
24101 (let ((default-directory dir))
24102 (expand-file-name txt)))
24103 (unless (derived-mode-p 'org-mode)
24104 (user-error "Cannot restrict to non-Org-mode file"))
24105 (org-agenda-set-restriction-lock 'file)))
24106 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24107 (move-overlay org-speedbar-restriction-lock-overlay
24108 (point-at-bol) (point-at-eol))
24109 (setq current-prefix-arg nil)
24110 (org-agenda-maybe-redo)))
24112 (defvar speedbar-file-key-map)
24113 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24114 (eval-after-load "speedbar"
24115 '(progn
24116 (speedbar-add-supported-extension ".org")
24117 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24118 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24119 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24120 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24121 (add-hook 'speedbar-visiting-tag-hook
24122 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24124 ;;; Fixes and Hacks for problems with other packages
24126 (defun org-mode-flyspell-verify ()
24127 "Function used for `flyspell-generic-check-word-predicate'."
24128 (if (org-at-heading-p)
24129 ;; At a headline or an inlinetask, check title only. This is
24130 ;; faster than relying on `org-element-at-point'.
24131 (and (save-excursion (beginning-of-line)
24132 (and (let ((case-fold-search t))
24133 (not (looking-at "\\*+ END[ \t]*$")))
24134 (looking-at org-complex-heading-regexp)))
24135 (match-beginning 4)
24136 (>= (point) (match-beginning 4))
24137 (or (not (match-beginning 5))
24138 (< (point) (match-beginning 5))))
24139 (let* ((element (org-element-at-point))
24140 (post-affiliated (org-element-property :post-affiliated element))
24141 (object-check
24142 (function
24143 ;; Non-nil if checks can be done for object at point.
24144 (lambda ()
24145 (let ((object (save-excursion
24146 (when (org-looking-at-p "\\>") (backward-char))
24147 (org-element-context element))))
24148 (case (org-element-type object)
24149 ;; Prevent checks in links due to keybinding conflict
24150 ;; with Flyspell.
24151 ((code entity export-snippet inline-babel-call
24152 inline-src-block line-break latex-fragment link macro
24153 statistics-cookie target timestamp verbatim)
24154 nil)
24155 (footnote-reference
24156 ;; Only in inline footnotes, within the definition.
24157 (and (eq (org-element-property :type object) 'inline)
24158 (< (save-excursion
24159 (goto-char (org-element-property :begin object))
24160 (search-forward ":" nil t 2))
24161 (point))))
24162 (otherwise t)))))))
24163 (cond
24164 ;; Ignore checks in all affiliated keywords but captions.
24165 ((and post-affiliated (< (point) post-affiliated))
24166 (and (save-excursion
24167 (beginning-of-line)
24168 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24169 (> (point) (match-end 0))
24170 (funcall object-check)))
24171 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24172 ((and org-log-into-drawer
24173 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24174 (parent element))
24175 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24176 (setq parent (org-element-property :parent parent)))
24177 (and parent
24178 (eq (compare-strings
24179 log nil nil
24180 (org-element-property :drawer-name parent) nil nil t)
24181 t))))
24182 nil)
24184 (case (org-element-type element)
24185 ((comment quote-section) t)
24186 (comment-block
24187 ;; Allow checks between block markers, not on them.
24188 (and (> (line-beginning-position)
24189 (org-element-property :post-affiliated element))
24190 (save-excursion
24191 (end-of-line)
24192 (skip-chars-forward " \r\t\n")
24193 (< (point) (org-element-property :end element)))))
24194 ;; Arbitrary list of keywords where checks are meaningful.
24195 ;; Make sure point is on the value part of the element.
24196 (keyword
24197 (and (member (org-element-property :key element)
24198 '("DESCRIPTION" "TITLE"))
24199 (< (save-excursion
24200 (beginning-of-line) (search-forward ":") (point))
24201 (point))))
24202 ;; Check is globally allowed in paragraphs verse blocks and
24203 ;; table rows (after affiliated keywords) but some objects
24204 ;; must not be affected.
24205 ((paragraph table-row verse-block)
24206 (and (>= (point) (org-element-property :contents-begin element))
24207 (< (point) (org-element-property :contents-end element))
24208 (funcall object-check)))))))))
24209 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24211 (defun org-remove-flyspell-overlays-in (beg end)
24212 "Remove flyspell overlays in region."
24213 (and (org-bound-and-true-p flyspell-mode)
24214 (fboundp 'flyspell-delete-region-overlays)
24215 (flyspell-delete-region-overlays beg end)))
24217 (defvar flyspell-delayed-commands)
24218 (eval-after-load "flyspell"
24219 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24221 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24222 (eval-after-load "bookmark"
24223 '(if (boundp 'bookmark-after-jump-hook)
24224 ;; We can use the hook
24225 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24226 ;; Hook not available, use advice
24227 (defadvice bookmark-jump (after org-make-visible activate)
24228 "Make the position visible."
24229 (org-bookmark-jump-unhide))))
24231 ;; Make sure saveplace shows the location if it was hidden
24232 (eval-after-load "saveplace"
24233 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24234 "Make the position visible."
24235 (org-bookmark-jump-unhide)))
24237 ;; Make sure ecb shows the location if it was hidden
24238 (eval-after-load "ecb"
24239 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24240 "Make hierarchy visible when jumping into location from ECB tree buffer."
24241 (if (derived-mode-p 'org-mode)
24242 (org-show-context))))
24244 (defun org-bookmark-jump-unhide ()
24245 "Unhide the current position, to show the bookmark location."
24246 (and (derived-mode-p 'org-mode)
24247 (or (outline-invisible-p)
24248 (save-excursion (goto-char (max (point-min) (1- (point))))
24249 (outline-invisible-p)))
24250 (org-show-context 'bookmark-jump)))
24252 ;; Make session.el ignore our circular variable
24253 (defvar session-globals-exclude)
24254 (eval-after-load "session"
24255 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24257 ;;;; Finish up
24259 (provide 'org)
24261 (run-hooks 'org-load-hook)
24263 ;;; org.el ends here