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.
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/>.
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
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
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
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
78 (require 'format-spec
)
80 (or (equal this-command
'eval-buffer
)
82 (load (concat (file-name-directory load-file-name
)
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
94 (declare-function cdlatex-environment
"ext:cdlatex" (environment item
))
96 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
97 ;; some places -- e.g. see the macro `org-with-limited-levels'.
99 ;; In Org buffers, the value of `outline-regexp' is that of
100 ;; `org-outline-regexp'. The only function still directly relying on
101 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
102 ;; job when `orgstruct-mode' is active.
103 (defvar org-outline-regexp
"\\*+ "
104 "Regexp to match Org headlines.")
106 (defvar org-outline-regexp-bol
"^\\*+ "
107 "Regexp to match Org headlines.
108 This is similar to `org-outline-regexp' but additionally makes
109 sure that we are at the beginning of the line.")
111 (defvar org-heading-regexp
"^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
112 "Matches a headline, putting stars and text into groups.
113 Stars are put in group 1 and the trimmed body in group 2.")
115 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
116 (unless (boundp 'calendar-view-holidays-initially-flag
)
117 (org-defvaralias 'calendar-view-holidays-initially-flag
118 'view-calendar-holidays-initially
))
119 (unless (boundp 'calendar-view-diary-initially-flag
)
120 (org-defvaralias 'calendar-view-diary-initially-flag
121 'view-diary-entries-initially
))
122 (unless (boundp 'diary-fancy-buffer
)
123 (org-defvaralias 'diary-fancy-buffer
'fancy-diary-buffer
))
125 (declare-function org-add-archive-files
"org-archive" (files))
127 (declare-function org-inlinetask-at-task-p
"org-inlinetask" ())
128 (declare-function org-inlinetask-outline-regexp
"org-inlinetask" ())
129 (declare-function org-inlinetask-toggle-visibility
"org-inlinetask" ())
130 (declare-function org-pop-to-buffer-same-window
"org-compat" (&optional buffer-or-name norecord label
))
131 (declare-function org-clock-get-last-clock-out-time
"org-clock" ())
132 (declare-function org-clock-timestamps-up
"org-clock" (&optional n
))
133 (declare-function org-clock-timestamps-down
"org-clock" (&optional n
))
134 (declare-function org-clock-remove-overlays
"org-clock" (&optional beg end noremove
))
135 (declare-function org-clock-sum
"org-clock" (&optional tstart tend headline-filter propname
))
136 (declare-function org-clock-sum-current-item
"org-clock" (&optional tstart
))
137 (declare-function org-clock-update-time-maybe
"org-clock" ())
138 (declare-function org-clocktable-shift
"org-clock" (dir n
))
140 (declare-function org-babel-tangle-file
"ob-tangle" (file &optional target-file lang
))
141 (declare-function org-babel-do-in-edit-buffer
"ob-core" (&rest body
))
142 (declare-function orgtbl-mode
"org-table" (&optional arg
))
143 (declare-function org-clock-out
"org-clock" (&optional switch-to-state fail-quietly at-time
))
144 (declare-function org-beamer-mode
"ox-beamer" ())
145 (declare-function org-table-blank-field
"org-table" ())
146 (declare-function org-table-edit-field
"org-table" (arg))
147 (declare-function org-table-insert-row
"org-table" (&optional arg
))
148 (declare-function org-table-justify-field-maybe
"org-table" (&optional new
))
149 (declare-function org-table-set-constants
"org-table" ())
150 (declare-function org-table-calc-current-TBLFM
"org-table" (&optional arg
))
151 (declare-function org-id-get-create
"org-id" (&optional force
))
152 (declare-function org-add-archive-files
"org-archive" (files))
153 (declare-function org-id-find-id-file
"org-id" (id))
154 (declare-function org-tags-view
"org-agenda" (&optional todo-only match
))
155 (declare-function org-agenda-list
"org-agenda" (&optional arg start-day span
))
156 (declare-function org-agenda-redo
"org-agenda" (&optional all
))
157 (declare-function org-table-align
"org-table" ())
158 (declare-function org-table-begin
"org-table" (&optional table-type
))
159 (declare-function org-table-blank-field
"org-table" ())
160 (declare-function org-table-end
"org-table" (&optional table-type
))
161 (declare-function org-table-end-of-field
"org-table" (&optional n
))
162 (declare-function org-table-insert-row
"org-table" (&optional arg
))
163 (declare-function org-table-paste-rectangle
"org-table" ())
164 (declare-function org-table-maybe-eval-formula
"org-table" ())
165 (declare-function org-table-maybe-recalculate-line
"org-table" ())
167 (declare-function org-element-at-point
"org-element" ())
168 (declare-function org-element-cache-reset
"org-element" (&optional all
))
169 (declare-function org-element-cache-refresh
"org-element" (pos))
170 (declare-function org-element-contents
"org-element" (element))
171 (declare-function org-element-context
"org-element" (&optional element
))
172 (declare-function org-element-interpret-data
"org-element"
173 (data &optional parent
))
174 (declare-function org-element-nested-p
"org-element" (elem-a elem-b
))
175 (declare-function org-element-parse-buffer
"org-element"
176 (&optional granularity visible-only
))
177 (declare-function org-element-property
"org-element" (property element
))
178 (declare-function org-element-put-property
"org-element"
179 (element property value
))
180 (declare-function org-element-swap-A-B
"org-element" (elem-a elem-b
))
181 (declare-function org-element-parse-buffer
"org-element"
182 (&optional granularity visible-only
))
183 (declare-function org-element-type
"org-element" (element))
185 (defsubst org-uniquify
(list)
186 "Non-destructively remove duplicate elements from LIST."
187 (let ((res (copy-sequence list
))) (delete-dups res
)))
189 (defsubst org-get-at-bol
(property)
190 "Get text property PROPERTY at the beginning of line."
191 (get-text-property (point-at-bol) property
))
193 (defsubst org-trim
(s)
194 "Remove whitespace at the beginning and the end of string S."
195 (replace-regexp-in-string
197 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s
)))
199 ;; load languages based on value of `org-babel-load-languages'
200 (defvar org-babel-load-languages
)
203 (defun org-babel-do-load-languages (sym value
)
204 "Load the languages defined in `org-babel-load-languages'."
205 (set-default sym value
)
207 (let ((active (cdr pair
)) (lang (symbol-name (car pair
))))
210 (require (intern (concat "ob-" lang
))))
212 (funcall 'fmakunbound
213 (intern (concat "org-babel-execute:" lang
)))
214 (funcall 'fmakunbound
215 (intern (concat "org-babel-expand-body:" lang
)))))))
216 org-babel-load-languages
))
218 (declare-function org-babel-tangle-file
"ob-tangle" (file &optional target-file lang
))
220 (defun org-babel-load-file (file &optional compile
)
221 "Load Emacs Lisp source code blocks in the Org-mode FILE.
222 This function exports the source code using `org-babel-tangle'
223 and then loads the resulting file using `load-file'. With prefix
224 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
225 file to byte-code before it is loaded."
226 (interactive "fFile to load: \nP")
227 (let* ((age (lambda (file)
229 (time-subtract (current-time)
230 (nth 5 (or (file-attributes (file-truename file
))
231 (file-attributes file
)))))))
232 (base-name (file-name-sans-extension file
))
233 (exported-file (concat base-name
".el")))
234 ;; tangle if the org-mode file is newer than the elisp file
235 (unless (and (file-exists-p exported-file
)
236 (> (funcall age file
) (funcall age exported-file
)))
238 (car (org-babel-tangle-file file exported-file
"emacs-lisp"))))
241 (progn (byte-compile-file exported-file
'load
)
242 "Compiled and loaded")
243 (progn (load-file exported-file
) "Loaded"))
246 (defcustom org-babel-load-languages
'((emacs-lisp . t
))
247 "Languages which can be evaluated in Org-mode buffers.
248 This list can be used to load support for any of the languages
249 below, note that each language will depend on a different set of
250 system executables and/or Emacs modes. When a language is
251 \"loaded\", then code blocks in that language can be evaluated
252 with `org-babel-execute-src-block' bound by default to C-c
253 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
254 be set to remove code block evaluation from the C-c C-c
255 keybinding. By default only Emacs Lisp (which has no
256 requirements) is loaded."
258 :set
'org-babel-do-load-languages
260 :type
'(alist :tag
"Babel Languages"
263 (const :tag
"Awk" awk
)
266 (const :tag
"Asymptote" asymptote
)
267 (const :tag
"Calc" calc
)
268 (const :tag
"Clojure" clojure
)
269 (const :tag
"CSS" css
)
270 (const :tag
"Ditaa" ditaa
)
271 (const :tag
"Dot" dot
)
272 (const :tag
"Emacs Lisp" emacs-lisp
)
273 (const :tag
"Forth" forth
)
274 (const :tag
"Fortran" fortran
)
275 (const :tag
"Gnuplot" gnuplot
)
276 (const :tag
"Haskell" haskell
)
279 (const :tag
"Java" java
)
280 (const :tag
"Javascript" js
)
281 (const :tag
"LaTeX" latex
)
282 (const :tag
"Ledger" ledger
)
283 (const :tag
"Lilypond" lilypond
)
284 (const :tag
"Lisp" lisp
)
285 (const :tag
"Makefile" makefile
)
286 (const :tag
"Maxima" maxima
)
287 (const :tag
"Matlab" matlab
)
288 (const :tag
"Mscgen" mscgen
)
289 (const :tag
"Ocaml" ocaml
)
290 (const :tag
"Octave" octave
)
291 (const :tag
"Org" org
)
292 (const :tag
"Perl" perl
)
293 (const :tag
"Pico Lisp" picolisp
)
294 (const :tag
"PlantUML" plantuml
)
295 (const :tag
"Python" python
)
296 (const :tag
"Ruby" ruby
)
297 (const :tag
"Sass" sass
)
298 (const :tag
"Scala" scala
)
299 (const :tag
"Scheme" scheme
)
300 (const :tag
"Screen" screen
)
301 (const :tag
"Shell Script" shell
)
302 (const :tag
"Shen" shen
)
303 (const :tag
"Sql" sql
)
304 (const :tag
"Sqlite" sqlite
)
305 (const :tag
"ebnf2ps" ebnf2ps
))
306 :value-type
(boolean :tag
"Activate" :value t
)))
308 ;;;; Customization variables
309 (defcustom org-clone-delete-id nil
310 "Remove ID property of clones of a subtree.
311 When non-nil, clones of a subtree don't inherit the ID property.
312 Otherwise they inherit the ID property with a new unique
322 (defun org-version (&optional here full message
)
323 "Show the org-mode version.
324 Interactively, or when MESSAGE is non-nil, show it in echo area.
325 With prefix argument, or when HERE is non-nil, insert it at point.
326 In non-interactive uses, a reduced version string is output unless
328 (interactive (list current-prefix-arg t
(not current-prefix-arg
)))
329 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
330 (save-load-suffixes (when (boundp 'load-suffixes
) load-suffixes
))
331 (load-suffixes (list ".el"))
332 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
334 (and (fboundp 'org-release
) (fboundp 'org-git-version
))
335 (org-load-noerror-mustsuffix (concat org-dir
"org-version"))))
336 (load-suffixes save-load-suffixes
)
337 (org-version (org-release))
338 (git-version (org-git-version))
339 (version (format "Org-mode version %s (%s @ %s)"
343 (if (string= org-dir org-install-dir
)
345 (concat "mixed installation! " org-install-dir
" and " org-dir
))
346 "org-loaddefs.el can not be found!")))
347 (version1 (if full version org-version
)))
348 (when here
(insert version1
))
349 (when message
(message "%s" version1
))
352 (defconst org-version
(org-version))
359 (defconst org-block-regexp
360 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
361 "Regular expression for hiding blocks.")
363 (defconst org-dblock-start-re
364 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
365 "Matches the start line of a dynamic block, with parameters.")
367 (defconst org-dblock-end-re
"^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
368 "Matches the end of a dynamic block.")
370 ;;;; Clock and Planning
372 (defconst org-clock-string
"CLOCK:"
373 "String used as prefix for timestamps clocking work hours on an item.")
375 (defconst org-closed-string
"CLOSED:"
376 "String used as the prefix for timestamps logging closing a TODO entry.")
378 (defconst org-deadline-string
"DEADLINE:"
379 "String to mark deadline entries.
380 A deadline is this string, followed by a time stamp. Should be a word,
381 terminated by a colon. You can insert a schedule keyword and
382 a timestamp with \\[org-deadline].")
384 (defconst org-scheduled-string
"SCHEDULED:"
385 "String to mark scheduled TODO entries.
386 A schedule is this string, followed by a time stamp. Should be a word,
387 terminated by a colon. You can insert a schedule keyword and
388 a timestamp with \\[org-schedule].")
390 (defconst org-planning-line-re
393 (list org-closed-string org-deadline-string org-scheduled-string
)
395 "Matches a line with planning info.
396 Matched keyword is in group 1.")
398 (defconst org-clock-line-re
399 (concat "^[ \t]*" org-clock-string
)
400 "Matches a line with clock info.")
404 (defconst org-drawer-regexp
"^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
405 "Matches first or last line of a hidden block.
406 Group 1 contains drawer's name or \"END\".")
408 (defconst org-property-start-re
"^[ \t]*:PROPERTIES:[ \t]*$"
409 "Regular expression matching the first line of a property drawer.")
411 (defconst org-property-end-re
"^[ \t]*:END:[ \t]*$"
412 "Regular expression matching the last line of a property drawer.")
414 (defconst org-clock-drawer-start-re
"^[ \t]*:CLOCK:[ \t]*$"
415 "Regular expression matching the first line of a clock drawer.")
417 (defconst org-clock-drawer-end-re
"^[ \t]*:END:[ \t]*$"
418 "Regular expression matching the last line of a clock drawer.")
420 (defconst org-property-drawer-re
421 (concat "\\(" org-property-start-re
"\\)[^\000]*?\\("
422 org-property-end-re
"\\)\n?")
423 "Matches an entire property drawer.")
425 (defconst org-clock-drawer-re
426 (concat "\\(" org-clock-drawer-start-re
"\\)[^\000]*?\\("
427 org-clock-drawer-end-re
"\\)\n?")
428 "Matches an entire clock drawer.")
432 (defconst org-heading-keyword-regexp-format
433 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
434 "Printf format for a regexp matching a headline with some keyword.
435 This regexp will match the headline of any node which has the
436 exact keyword that is put into the format. The keyword isn't in
437 any group by default, but the stars and the body are.")
439 (defconst org-heading-keyword-maybe-regexp-format
440 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
441 "Printf format for a regexp matching a headline, possibly with some keyword.
442 This regexp can match any headline with the specified keyword, or
443 without a keyword. The keyword isn't in any group by default,
444 but the stars and the body are.")
446 (defconst org-archive-tag
"ARCHIVE"
447 "The tag that marks a subtree as archived.
448 An archived subtree does not open during visibility cycling, and does
449 not contribute to the agenda listings.")
451 (defconst org-comment-string
"COMMENT"
452 "Entries starting with this keyword will never be exported.
453 An entry can be toggled between COMMENT and normal with
454 \\[org-toggle-comment].")
457 ;;;; LaTeX Environments and Fragments
459 (defconst org-latex-regexps
460 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t
)
461 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
462 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
463 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil
)
464 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil
)
465 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil
)
466 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil
)
467 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil
))
468 "Regular expressions for matching embedded LaTeX.")
472 (defconst org-effort-property
"Effort"
473 "The property that is being used to keep track of effort estimates.
474 Effort estimates given in this property need to have the format H:MM.")
478 (defconst org-table-any-line-regexp
"^[ \t]*\\(|\\|\\+-[-+]\\)"
479 "Detect an org-type or table-type table.")
481 (defconst org-table-line-regexp
"^[ \t]*|"
482 "Detect an org-type table line.")
484 (defconst org-table-dataline-regexp
"^[ \t]*|[^-]"
485 "Detect an org-type table line.")
487 (defconst org-table-hline-regexp
"^[ \t]*|-"
488 "Detect an org-type table hline.")
490 (defconst org-table1-hline-regexp
"^[ \t]*\\+-[-+]"
491 "Detect a table-type table hline.")
493 (defconst org-table-any-border-regexp
"^[ \t]*[^|+ \t]"
494 "Detect the first line outside a table when searching from within it.
495 This works for both table types.")
497 (defconst org-TBLFM-regexp
"^[ \t]*#\\+TBLFM: "
498 "Detect a #+TBLFM line.")
502 (defconst org-ts-regexp
"<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
503 "Regular expression for fast time stamp matching.")
505 (defconst org-ts-regexp-both
"[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
506 "Regular expression for fast time stamp matching.")
508 (defconst org-ts-regexp0
509 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
510 "Regular expression matching time strings for analysis.
511 This one does not require the space after the date, so it can be used
512 on a string that terminates immediately after the date.")
514 (defconst org-ts-regexp1
"\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
515 "Regular expression matching time strings for analysis.")
517 (defconst org-ts-regexp2
(concat "<" org-ts-regexp1
"[^>\n]\\{0,16\\}>")
518 "Regular expression matching time stamps, with groups.")
520 (defconst org-ts-regexp3
(concat "[[<]" org-ts-regexp1
"[^]>\n]\\{0,16\\}[]>]")
521 "Regular expression matching time stamps (also [..]), with groups.")
523 (defconst org-tr-regexp
(concat org-ts-regexp
"--?-?" org-ts-regexp
)
524 "Regular expression matching a time stamp range.")
526 (defconst org-tr-regexp-both
527 (concat org-ts-regexp-both
"--?-?" org-ts-regexp-both
)
528 "Regular expression matching a time stamp range.")
530 (defconst org-tsr-regexp
(concat org-ts-regexp
"\\(--?-?"
531 org-ts-regexp
"\\)?")
532 "Regular expression matching a time stamp or time stamp range.")
534 (defconst org-tsr-regexp-both
535 (concat org-ts-regexp-both
"\\(--?-?"
536 org-ts-regexp-both
"\\)?")
537 "Regular expression matching a time stamp or time stamp range.
538 The time stamps may be either active or inactive.")
540 (defconst org-repeat-re
541 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
542 "Regular expression for specifying repeated events.
543 After a match, group 1 contains the repeat expression.")
545 (defconst org-time-stamp-formats
'("<%Y-%m-%d %a>" .
"<%Y-%m-%d %a %H:%M>")
546 "Formats for `format-time-string' which are used for time stamps.")
549 ;;; The custom variables
552 "Outline-based notes management and organizer."
557 (defcustom org-mode-hook nil
558 "Mode hook for Org-mode, run after the mode was turned on."
562 (defcustom org-load-hook nil
563 "Hook that is run after org.el has been loaded."
567 (defcustom org-log-buffer-setup-hook nil
568 "Hook that is run after an Org log buffer is created."
573 (defvar org-modules
) ; defined below
574 (defvar org-modules-loaded nil
575 "Have the modules been loaded already?")
577 (defun org-load-modules-maybe (&optional force
)
578 "Load all extensions listed in `org-modules'."
579 (when (or force
(not org-modules-loaded
))
581 (condition-case nil
(require ext
)
582 (error (message "Problems while trying to load feature `%s'" ext
))))
584 (setq org-modules-loaded t
)))
586 (defun org-set-modules (var value
)
587 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
589 (when (featurep 'org
)
590 (org-load-modules-maybe 'force
)
591 (org-element-cache-reset 'all
)))
593 (defcustom org-modules
'(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail
)
594 "Modules that should always be loaded together with org.el.
596 If a description starts with <C>, the file is not part of Emacs
597 and loading it will require that you have downloaded and properly
598 installed the Org mode distribution.
600 You can also use this system to load external packages (i.e. neither Org
601 core modules, nor modules from the CONTRIB directory). Just add symbols
602 to the end of the list. If the package is called org-xyz.el, then you need
603 to add the symbol `xyz', and the package must have a call to:
607 For export specific modules, see also `org-export-backends'."
609 :set
'org-set-modules
611 :package-version
'(Org .
"8.0")
614 (const :tag
" bbdb: Links to BBDB entries" org-bbdb
)
615 (const :tag
" bibtex: Links to BibTeX entries" org-bibtex
)
616 (const :tag
" crypt: Encryption of subtrees" org-crypt
)
617 (const :tag
" ctags: Access to Emacs tags with links" org-ctags
)
618 (const :tag
" docview: Links to doc-view buffers" org-docview
)
619 (const :tag
" gnus: Links to GNUS folders/messages" org-gnus
)
620 (const :tag
" habit: Track your consistency with habits" org-habit
)
621 (const :tag
" id: Global IDs for identifying entries" org-id
)
622 (const :tag
" info: Links to Info nodes" org-info
)
623 (const :tag
" inlinetask: Tasks independent of outline hierarchy" org-inlinetask
)
624 (const :tag
" irc: Links to IRC/ERC chat sessions" org-irc
)
625 (const :tag
" mhe: Links to MHE folders/messages" org-mhe
)
626 (const :tag
" mouse: Additional mouse support" org-mouse
)
627 (const :tag
" protocol: Intercept calls from emacsclient" org-protocol
)
628 (const :tag
" rmail: Links to RMAIL folders/messages" org-rmail
)
629 (const :tag
" w3m: Special cut/paste from w3m to Org-mode." org-w3m
)
631 (const :tag
"C annotate-file: Annotate a file with org syntax" org-annotate-file
)
632 (const :tag
"C bookmark: Org-mode links to bookmarks" org-bookmark
)
633 (const :tag
"C bullets: Add overlays to headlines stars" org-bullets
)
634 (const :tag
"C checklist: Extra functions for checklists in repeated tasks" org-checklist
)
635 (const :tag
"C choose: Use TODO keywords to mark decisions states" org-choose
)
636 (const :tag
"C collector: Collect properties into tables" org-collector
)
637 (const :tag
"C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend
)
638 (const :tag
"C drill: Flashcards and spaced repetition for Org-mode" org-drill
)
639 (const :tag
"C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol
)
640 (const :tag
"C eshell Support for links to working directories in eshell" org-eshell
)
641 (const :tag
"C eval-light: Evaluate inbuffer-code on demand" org-eval-light
)
642 (const :tag
"C eval: Include command output as text" org-eval
)
643 (const :tag
"C expiry: Expiry mechanism for Org-mode entries" org-expiry
)
644 (const :tag
"C favtable: Lookup table of favorite references and links" org-favtable
)
645 (const :tag
"C git-link: Provide org links to specific file version" org-git-link
)
646 (const :tag
"C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query
)
647 (const :tag
"C invoice: Help manage client invoices in Org-mode" org-invoice
)
648 (const :tag
"C jira: Add a jira:ticket protocol to Org-mode" org-jira
)
649 (const :tag
"C learn: SuperMemo's incremental learning algorithm" org-learn
)
650 (const :tag
"C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal
)
651 (const :tag
"C mac-link: Grab links and url from various mac Applications" org-mac-link
)
652 (const :tag
"C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix
)
653 (const :tag
"C man: Support for links to manpages in Org-mode" org-man
)
654 (const :tag
"C mew: Links to Mew folders/messages" org-mew
)
655 (const :tag
"C mtags: Support for muse-like tags" org-mtags
)
656 (const :tag
"C notmuch: Provide org links to notmuch searches or messages" org-notmuch
)
657 (const :tag
"C panel: Simple routines for us with bad memory" org-panel
)
658 (const :tag
"C registry: A registry for Org-mode links" org-registry
)
659 (const :tag
"C screen: Visit screen sessions through Org-mode links" org-screen
)
660 (const :tag
"C secretary: Team management with org-mode" org-secretary
)
661 (const :tag
"C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert
)
662 (const :tag
"C toc: Table of contents for Org-mode buffer" org-toc
)
663 (const :tag
"C track: Keep up with Org-mode development" org-track
)
664 (const :tag
"C velocity Something like Notational Velocity for Org" org-velocity
)
665 (const :tag
"C vm: Links to VM folders/messages" org-vm
)
666 (const :tag
"C wikinodes: CamelCase wiki-like links" org-wikinodes
)
667 (const :tag
"C wl: Links to Wanderlust folders/messages" org-wl
)
668 (repeat :tag
"External packages" :inline t
(symbol :tag
"Package"))))
670 (defvar org-export--registered-backends
) ; From ox.el.
671 (declare-function org-export-derived-backend-p
"ox" (backend &rest backends
))
672 (declare-function org-export-backend-name
"ox" (backend))
673 (defcustom org-export-backends
'(ascii html icalendar latex
)
674 "List of export back-ends that should be always available.
676 If a description starts with <C>, the file is not part of Emacs
677 and loading it will require that you have downloaded and properly
678 installed the Org mode distribution.
680 Unlike to `org-modules', libraries in this list will not be
681 loaded along with Org, but only once the export framework is
684 This variable needs to be set before org.el is loaded. If you
685 need to make a change while Emacs is running, use the customize
686 interface or run the following code, where VAL stands for the new
687 value of the variable, after updating it:
690 \(setq org-export--registered-backends
693 \(let ((name (org-export-backend-name backend)))
697 \(and (org-export-derived-backend-p b name)
698 \(throw 'parentp t)))))))
699 org-export--registered-backends))
700 \(let ((new-list (mapcar 'org-export-backend-name
701 org-export--registered-backends)))
702 \(dolist (backend val)
704 \((not (load (format \"ox-%s\" backend) t t))
705 \(message \"Problems while trying to load export back-end `%s'\"
707 \((not (memq backend new-list)) (push backend new-list))))
708 \(set-default 'org-export-backends new-list)))
710 Adding a back-end to this list will also pull the back-end it
715 :package-version
'(Org .
"8.0")
716 :initialize
'custom-initialize-set
717 :set
(lambda (var val
)
718 (if (not (featurep 'ox
)) (set-default var val
)
719 ;; Any back-end not required anymore (not present in VAL and not
720 ;; a parent of any back-end in the new value) is removed from the
721 ;; list of registered back-ends.
722 (setq org-export--registered-backends
725 (let ((name (org-export-backend-name backend
)))
729 (and (org-export-derived-backend-p b name
)
730 (throw 'parentp t
)))))))
731 org-export--registered-backends
))
732 ;; Now build NEW-LIST of both new back-ends and required
734 (let ((new-list (mapcar 'org-export-backend-name
735 org-export--registered-backends
)))
736 (dolist (backend val
)
738 ((not (load (format "ox-%s" backend
) t t
))
739 (message "Problems while trying to load export back-end `%s'"
741 ((not (memq backend new-list
)) (push backend new-list
))))
742 ;; Set VAR to that list with fixed dependencies.
743 (set-default var new-list
))))
744 :type
'(set :greedy t
745 (const :tag
" ascii Export buffer to ASCII format" ascii
)
746 (const :tag
" beamer Export buffer to Beamer presentation" beamer
)
747 (const :tag
" html Export buffer to HTML format" html
)
748 (const :tag
" icalendar Export buffer to iCalendar format" icalendar
)
749 (const :tag
" latex Export buffer to LaTeX format" latex
)
750 (const :tag
" man Export buffer to MAN format" man
)
751 (const :tag
" md Export buffer to Markdown format" md
)
752 (const :tag
" odt Export buffer to ODT format" odt
)
753 (const :tag
" org Export buffer to Org format" org
)
754 (const :tag
" texinfo Export buffer to Texinfo format" texinfo
)
755 (const :tag
"C confluence Export buffer to Confluence Wiki format" confluence
)
756 (const :tag
"C deck Export buffer to deck.js presentations" deck
)
757 (const :tag
"C freemind Export buffer to Freemind mindmap format" freemind
)
758 (const :tag
"C groff Export buffer to Groff format" groff
)
759 (const :tag
"C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter
)
760 (const :tag
"C RSS 2.0 Export buffer to RSS 2.0 format" rss
)
761 (const :tag
"C s5 Export buffer to s5 presentations" s5
)
762 (const :tag
"C taskjuggler Export buffer to TaskJuggler format" taskjuggler
)))
767 (condition-case nil
(require (intern (format "ox-%s" backend
)))
768 (error (message "Problems while trying to load export back-end `%s'"
770 org-export-backends
))
772 (defcustom org-support-shift-select nil
773 "Non-nil means make shift-cursor commands select text when possible.
775 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
776 start selecting a region, or enlarge regions started in this way.
777 In Org-mode, in special contexts, these same keys are used for
778 other purposes, important enough to compete with shift selection.
779 Org tries to balance these needs by supporting `shift-select-mode'
780 outside these special contexts, under control of this variable.
782 The default of this variable is nil, to avoid confusing behavior. Shifted
783 cursor keys will then execute Org commands in the following contexts:
784 - on a headline, changing TODO state (left/right) and priority (up/down)
785 - on a time stamp, changing the time
786 - in a plain list item, changing the bullet type
787 - in a property definition line, switching between allowed values
788 - in the BEGIN line of a clock table (changing the time block).
789 Outside these contexts, the commands will throw an error.
791 When this variable is t and the cursor is not in a special
792 context, Org-mode will support shift-selection for making and
793 enlarging regions. To make this more effective, the bullet
794 cycling will no longer happen anywhere in an item line, but only
795 if the cursor is exactly on the bullet.
797 If you set this variable to the symbol `always', then the keys
798 will not be special in headlines, property lines, and item lines,
799 to make shift selection work there as well. If this is what you
800 want, you can use the following alternative commands: `C-c C-t'
801 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
802 can be used to switch TODO sets, `C-c -' to cycle item bullet
803 types, and properties can be edited by hand or in column view.
805 However, when the cursor is on a timestamp, shift-cursor commands
806 will still edit the time stamp - this is just too good to give up.
808 XEmacs user should have this variable set to nil, because
809 `shift-select-mode' is in Emacs 23 or later only."
812 (const :tag
"Never" nil
)
813 (const :tag
"When outside special context" t
)
814 (const :tag
"Everywhere except timestamps" always
)))
816 (defcustom org-loop-over-headlines-in-active-region nil
817 "Shall some commands act upon headlines in the active region?
819 When set to `t', some commands will be performed in all headlines
820 within the active region.
822 When set to `start-level', some commands will be performed in all
823 headlines within the active region, provided that these headlines
824 are of the same level than the first one.
826 When set to a string, those commands will be performed on the
827 matching headlines within the active region. Such string must be
828 a tags/property/todo match as it is used in the agenda tags view.
830 The list of commands is: `org-schedule', `org-deadline',
831 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
832 `org-archive-to-archive-sibling'. The archiving commands skip
833 already archived entries."
834 :type
'(choice (const :tag
"Don't loop" nil
)
835 (const :tag
"All headlines in active region" t
)
836 (const :tag
"In active region, headlines at the same level than the first one" start-level
)
837 (string :tag
"Tags/Property/Todo matcher"))
842 (defgroup org-startup nil
843 "Options concerning startup of Org-mode."
847 (defcustom org-startup-folded t
848 "Non-nil means entering Org-mode will switch to OVERVIEW.
849 This can also be configured on a per-file basis by adding one of
850 the following lines anywhere in the buffer:
852 #+STARTUP: fold (or `overview', this is equivalent)
853 #+STARTUP: nofold (or `showall', this is equivalent)
855 #+STARTUP: showeverything
857 By default, this option is ignored when Org opens agenda files
858 for the first time. If you want the agenda to honor the startup
859 option, set `org-agenda-inhibit-startup' to nil."
862 (const :tag
"nofold: show all" nil
)
863 (const :tag
"fold: overview" t
)
864 (const :tag
"content: all headlines" content
)
865 (const :tag
"show everything, even drawers" showeverything
)))
867 (defcustom org-startup-truncated t
868 "Non-nil means entering Org-mode will set `truncate-lines'.
869 This is useful since some lines containing links can be very long and
870 uninteresting. Also tables look terrible when wrapped."
874 (defcustom org-startup-indented nil
875 "Non-nil means turn on `org-indent-mode' on startup.
876 This can also be configured on a per-file basis by adding one of
877 the following lines anywhere in the buffer:
881 :group
'org-structure
883 (const :tag
"Not" nil
)
884 (const :tag
"Globally (slow on startup in large files)" t
)))
886 (defcustom org-use-sub-superscripts t
887 "Non-nil means interpret \"_\" and \"^\" for display.
889 If you want to control how Org exports those characters, see
890 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
891 used to be an alias for `org-export-with-sub-superscripts' in
892 Org <8.0, it is not anymore.
894 When this option is turned on, you can use TeX-like syntax for
895 sub- and superscripts within the buffer. Several characters after
896 \"_\" or \"^\" will be considered as a single item - so grouping
897 with {} is normally not needed. For example, the following things
898 will be parsed as single sub- or superscripts:
900 10^24 or 10^tau several digits will be considered 1 item.
901 10^-12 or 10^-tau a leading sign with digits or a word
902 x^2-y^3 will be read as x^2 - y^3, because items are
903 terminated by almost any nonword/nondigit char.
904 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
906 Still, ambiguity is possible. So when in doubt, use {} to enclose
907 the sub/superscript. If you set this variable to the symbol `{}',
908 the braces are *required* in order to trigger interpretations as
909 sub/superscript. This can be helpful in documents that need \"_\"
910 frequently in plain text."
913 :package-version
'(Org .
"8.0")
915 (const :tag
"Always interpret" t
)
916 (const :tag
"Only with braces" {})
917 (const :tag
"Never interpret" nil
)))
919 (defcustom org-startup-with-beamer-mode nil
920 "Non-nil means turn on `org-beamer-mode' on startup.
921 This can also be configured on a per-file basis by adding one of
922 the following lines anywhere in the buffer:
929 (defcustom org-startup-align-all-tables nil
930 "Non-nil means align all tables when visiting a file.
931 This is useful when the column width in tables is forced with <N> cookies
932 in table fields. Such tables will look correct only after the first re-align.
933 This can also be configured on a per-file basis by adding one of
934 the following lines anywhere in the buffer:
940 (defcustom org-startup-with-inline-images nil
941 "Non-nil means show inline images when loading a new Org file.
942 This can also be configured on a per-file basis by adding one of
943 the following lines anywhere in the buffer:
944 #+STARTUP: inlineimages
945 #+STARTUP: noinlineimages"
950 (defcustom org-startup-with-latex-preview nil
951 "Non-nil means preview LaTeX fragments when loading a new Org file.
953 This can also be configured on a per-file basis by adding one of
954 the following lines anywhere in the buffer:
955 #+STARTUP: latexpreview
956 #+STARTUP: nolatexpreview"
959 :package-version
'(Org .
"8.0")
962 (defcustom org-insert-mode-line-in-empty-file nil
963 "Non-nil means insert the first line setting Org-mode in empty files.
964 When the function `org-mode' is called interactively in an empty file, this
965 normally means that the file name does not automatically trigger Org-mode.
966 To ensure that the file will always be in Org-mode in the future, a
967 line enforcing Org-mode will be inserted into the buffer, if this option
972 (defcustom org-replace-disputed-keys nil
973 "Non-nil means use alternative key bindings for some keys.
974 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
975 These keys are also used by other packages like shift-selection-mode'
976 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
977 If you want to use Org-mode together with one of these other modes,
978 or more generally if you would like to move some Org-mode commands to
979 other keys, set this variable and configure the keys with the variable
982 This option is only relevant at load-time of Org-mode, and must be set
983 *before* org.el is loaded. Changing it requires a restart of Emacs to
988 (defcustom org-use-extra-keys nil
989 "Non-nil means use extra key sequence definitions for certain commands.
990 This happens automatically if you run XEmacs or if `window-system'
991 is nil. This variable lets you do the same manually. You must
992 set it before loading org.
994 Example: on Carbon Emacs 22 running graphically, with an external
995 keyboard on a Powerbook, the default way of setting M-left might
996 not work for either Alt or ESC. Setting this variable will make
1001 (org-defvaralias 'org-CUA-compatible
'org-replace-disputed-keys
)
1003 (defcustom org-disputed-keys
1004 '(([(shift up
)] .
[(meta p
)])
1005 ([(shift down
)] .
[(meta n
)])
1006 ([(shift left
)] .
[(meta -
)])
1007 ([(shift right
)] .
[(meta +)])
1008 ([(control shift right
)] .
[(meta shift
+)])
1009 ([(control shift left
)] .
[(meta shift -
)]))
1010 "Keys for which Org-mode and other modes compete.
1011 This is an alist, cars are the default keys, second element specifies
1012 the alternative to use when `org-replace-disputed-keys' is t.
1014 Keys can be specified in any syntax supported by `define-key'.
1015 The value of this option takes effect only at Org-mode's startup,
1016 therefore you'll have to restart Emacs to apply it after changing."
1020 (defun org-key (key)
1021 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1022 Or return the original if not disputed.
1023 Also apply the translations defined in `org-xemacs-key-equivalents'."
1024 (when org-replace-disputed-keys
1025 (let* ((nkey (key-description key
))
1026 (x (org-find-if (lambda (x)
1027 (equal (key-description (car x
)) nkey
))
1028 org-disputed-keys
)))
1029 (setq key
(if x
(cdr x
) key
))))
1030 (when (featurep 'xemacs
)
1031 (setq key
(or (cdr (assoc key org-xemacs-key-equivalents
)) key
)))
1034 (defun org-find-if (predicate seq
)
1037 (if (funcall predicate
(car seq
))
1038 (throw 'exit
(car seq
))
1041 (defun org-defkey (keymap key def
)
1042 "Define a key, possibly translated, as returned by `org-key'."
1043 (define-key keymap
(org-key key
) def
))
1045 (defcustom org-ellipsis nil
1046 "The ellipsis to use in the Org-mode outline.
1047 When nil, just use the standard three dots.
1048 When a string, use that string instead.
1049 When a face, use the standard 3 dots, but with the specified face.
1050 The change affects only Org-mode (which will then use its own display table).
1051 Changing this requires executing \\[org-mode] in a buffer to become
1054 :type
'(choice (const :tag
"Default" nil
)
1055 (face :tag
"Face" :value org-warning
)
1056 (string :tag
"String" :value
"...#")))
1058 (defvar org-display-table nil
1059 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1061 (defgroup org-keywords nil
1062 "Keywords in Org-mode."
1066 (defcustom org-closed-keep-when-no-todo nil
1067 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1069 :group
'org-keywords
1071 :package-version
'(Org .
"8.0")
1074 (defgroup org-structure nil
1075 "Options concerning the general structure of Org-mode files."
1076 :tag
"Org Structure"
1079 (defgroup org-reveal-location nil
1080 "Options about how to make context of a location visible."
1081 :tag
"Org Reveal Location"
1082 :group
'org-structure
)
1084 (defconst org-context-choice
1086 (const :tag
"Always" t
)
1087 (const :tag
"Never" nil
)
1088 (repeat :greedy t
:tag
"Individual contexts"
1090 (choice :tag
"Context"
1097 (const bookmark-jump
)
1101 "Contexts for the reveal options.")
1103 (defcustom org-show-hierarchy-above
'((default . t
))
1104 "Non-nil means show full hierarchy when revealing a location.
1105 Org-mode often shows locations in an org-mode file which might have
1106 been invisible before. When this is set, the hierarchy of headings
1107 above the exposed location is shown.
1108 Turning this off for example for sparse trees makes them very compact.
1109 Instead of t, this can also be an alist specifying this option for different
1110 contexts. Valid contexts are
1111 agenda when exposing an entry from the agenda
1112 org-goto when using the command `org-goto' on key C-c C-j
1113 occur-tree when using the command `org-occur' on key C-c /
1114 tags-tree when constructing a sparse tree based on tags matches
1115 link-search when exposing search matches associated with a link
1116 mark-goto when exposing the jump goal of a mark
1117 bookmark-jump when exposing a bookmark location
1118 isearch when exiting from an incremental search
1119 default default for all contexts not set explicitly"
1120 :group
'org-reveal-location
1121 :type org-context-choice
)
1123 (defcustom org-show-following-heading
'((default . nil
))
1124 "Non-nil means show following heading when revealing a location.
1125 Org-mode often shows locations in an org-mode file which might have
1126 been invisible before. When this is set, the heading following the
1128 Turning this off for example for sparse trees makes them very compact,
1129 but makes it harder to edit the location of the match. In such a case,
1130 use the command \\[org-reveal] to show more context.
1131 Instead of t, this can also be an alist specifying this option for different
1132 contexts. See `org-show-hierarchy-above' for valid contexts."
1133 :group
'org-reveal-location
1134 :type org-context-choice
)
1136 (defcustom org-show-siblings
'((default . nil
) (isearch t
) (bookmark-jump t
))
1137 "Non-nil means show all sibling heading when revealing a location.
1138 Org-mode often shows locations in an org-mode file which might have
1139 been invisible before. When this is set, the sibling of the current entry
1140 heading are all made visible. If `org-show-hierarchy-above' is t,
1141 the same happens on each level of the hierarchy above the current entry.
1143 By default this is on for the isearch context, off for all other contexts.
1144 Turning this off for example for sparse trees makes them very compact,
1145 but makes it harder to edit the location of the match. In such a case,
1146 use the command \\[org-reveal] to show more context.
1147 Instead of t, this can also be an alist specifying this option for different
1148 contexts. See `org-show-hierarchy-above' for valid contexts."
1149 :group
'org-reveal-location
1150 :type org-context-choice
1152 :package-version
'(Org .
"8.0"))
1154 (defcustom org-show-entry-below
'((default . nil
))
1155 "Non-nil means show the entry below a headline when revealing a location.
1156 Org-mode often shows locations in an org-mode file which might have
1157 been invisible before. When this is set, the text below the headline that is
1158 exposed is also shown.
1160 By default this is off for all contexts.
1161 Instead of t, this can also be an alist specifying this option for different
1162 contexts. See `org-show-hierarchy-above' for valid contexts."
1163 :group
'org-reveal-location
1164 :type org-context-choice
)
1166 (defcustom org-indirect-buffer-display
'other-window
1167 "How should indirect tree buffers be displayed?
1168 This applies to indirect buffers created with the commands
1169 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1171 current-window Display in the current window
1172 other-window Just display in another window.
1173 dedicated-frame Create one new frame, and re-use it each time.
1174 new-frame Make a new frame each time. Note that in this case
1175 previously-made indirect buffers are kept, and you need to
1176 kill these buffers yourself."
1177 :group
'org-structure
1178 :group
'org-agenda-windows
1180 (const :tag
"In current window" current-window
)
1181 (const :tag
"In current frame, other window" other-window
)
1182 (const :tag
"Each time a new frame" new-frame
)
1183 (const :tag
"One dedicated frame" dedicated-frame
)))
1185 (defcustom org-use-speed-commands nil
1186 "Non-nil means activate single letter commands at beginning of a headline.
1187 This may also be a function to test for appropriate locations where speed
1188 commands should be active.
1190 For example, to activate speed commands when the point is on any
1191 star at the beginning of the headline, you can do this:
1193 (setq org-use-speed-commands
1194 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1195 :group
'org-structure
1197 (const :tag
"Never" nil
)
1198 (const :tag
"At beginning of headline stars" t
)
1201 (defcustom org-speed-commands-user nil
1202 "Alist of additional speed commands.
1203 This list will be checked before `org-speed-commands-default'
1204 when the variable `org-use-speed-commands' is non-nil
1205 and when the cursor is at the beginning of a headline.
1206 The car if each entry is a string with a single letter, which must
1207 be assigned to `self-insert-command' in the global map.
1208 The cdr is either a command to be called interactively, a function
1209 to be called, or a form to be evaluated.
1210 An entry that is just a list with a single string will be interpreted
1211 as a descriptive headline that will be added when listing the speed
1212 commands in the Help buffer using the `?' speed command."
1213 :group
'org-structure
1214 :type
'(repeat :value
("k" . ignore
)
1215 (choice :value
("k" . ignore
)
1216 (list :tag
"Descriptive Headline" (string :tag
"Headline"))
1217 (cons :tag
"Letter and Command"
1218 (string :tag
"Command letter")
1223 (defcustom org-bookmark-names-plist
1224 '(:last-capture
"org-capture-last-stored"
1225 :last-refile
"org-refile-last-stored"
1226 :last-capture-marker
"org-capture-last-stored-marker")
1227 "Names for bookmarks automatically set by some Org commands.
1228 This can provide strings as names for a number of bookmarks Org sets
1229 automatically. The following keys are currently implemented:
1231 :last-capture-marker
1233 When a key does not show up in the property list, the corresponding bookmark
1235 :group
'org-structure
1238 (defgroup org-cycle nil
1239 "Options concerning visibility cycling in Org-mode."
1241 :group
'org-structure
)
1243 (defcustom org-cycle-skip-children-state-if-no-children t
1244 "Non-nil means skip CHILDREN state in entries that don't have any."
1248 (defcustom org-cycle-max-level nil
1249 "Maximum level which should still be subject to visibility cycling.
1250 Levels higher than this will, for cycling, be treated as text, not a headline.
1251 When `org-odd-levels-only' is set, a value of N in this variable actually
1252 means 2N-1 stars as the limiting headline.
1253 When nil, cycle all levels.
1254 Note that the limiting level of cycling is also influenced by
1255 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1256 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1260 (const :tag
"No limit" nil
)
1261 (integer :tag
"Maximum level")))
1263 (defcustom org-hide-block-startup nil
1264 "Non-nil means entering Org-mode will fold all blocks.
1265 This can also be set in on a per-file basis with
1267 #+STARTUP: hideblocks
1268 #+STARTUP: showblocks"
1273 (defcustom org-cycle-global-at-bob nil
1274 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1275 This makes it possible to do global cycling without having to use S-TAB or
1276 \\[universal-argument] TAB. For this special case to work, the first line
1277 of the buffer must not be a headline -- it may be empty or some other text.
1278 When used in this way, `org-cycle-hook' is disabled temporarily to make
1279 sure the cursor stays at the beginning of the buffer. When this option is
1280 nil, don't do anything special at the beginning of the buffer."
1284 (defcustom org-cycle-level-after-item
/entry-creation t
1285 "Non-nil means cycle entry level or item indentation in new empty entries.
1287 When the cursor is at the end of an empty headline, i.e., with only stars
1288 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1289 and then all possible ancestor states, before returning to the original state.
1290 This makes data entry extremely fast: M-RET to create a new headline,
1291 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1293 When the cursor is at the end of an empty plain list item, one TAB will
1294 make it a subitem, two or more tabs will back up to make this an item
1295 higher up in the item hierarchy."
1299 (defcustom org-cycle-emulate-tab t
1300 "Where should `org-cycle' emulate TAB.
1302 white Only in completely white lines
1303 whitestart Only at the beginning of lines, before the first non-white char
1304 t Everywhere except in headlines
1305 exc-hl-bol Everywhere except at the start of a headline
1306 If TAB is used in a place where it does not emulate TAB, the current subtree
1307 visibility is cycled."
1309 :type
'(choice (const :tag
"Never" nil
)
1310 (const :tag
"Only in completely white lines" white
)
1311 (const :tag
"Before first char in a line" whitestart
)
1312 (const :tag
"Everywhere except in headlines" t
)
1313 (const :tag
"Everywhere except at bol in headlines" exc-hl-bol
)))
1315 (defcustom org-cycle-separator-lines
2
1316 "Number of empty lines needed to keep an empty line between collapsed trees.
1317 If you leave an empty line between the end of a subtree and the following
1318 headline, this empty line is hidden when the subtree is folded.
1319 Org-mode will leave (exactly) one empty line visible if the number of
1320 empty lines is equal or larger to the number given in this variable.
1321 So the default 2 means at least 2 empty lines after the end of a subtree
1322 are needed to produce free space between a collapsed subtree and the
1325 If the number is negative, and the number of empty lines is at least -N,
1326 all empty lines are shown.
1328 Special case: when 0, never leave empty lines in collapsed view."
1331 (put 'org-cycle-separator-lines
'safe-local-variable
'integerp
)
1333 (defcustom org-pre-cycle-hook nil
1334 "Hook that is run before visibility cycling is happening.
1335 The function(s) in this hook must accept a single argument which indicates
1336 the new state that will be set right after running this hook. The
1337 argument is a symbol. Before a global state change, it can have the values
1338 `overview', `content', or `all'. Before a local state change, it can have
1339 the values `folded', `children', or `subtree'."
1343 (defcustom org-cycle-hook
'(org-cycle-hide-archived-subtrees
1344 org-cycle-hide-drawers
1345 org-cycle-hide-inline-tasks
1346 org-cycle-show-empty-lines
1347 org-optimize-window-after-visibility-change
)
1348 "Hook that is run after `org-cycle' has changed the buffer visibility.
1349 The function(s) in this hook must accept a single argument which indicates
1350 the new state that was set by the most recent `org-cycle' command. The
1351 argument is a symbol. After a global state change, it can have the values
1352 `overview', `contents', or `all'. After a local state change, it can have
1353 the values `folded', `children', or `subtree'."
1357 (defgroup org-edit-structure nil
1358 "Options concerning structure editing in Org-mode."
1359 :tag
"Org Edit Structure"
1360 :group
'org-structure
)
1362 (defcustom org-odd-levels-only nil
1363 "Non-nil means skip even levels and only use odd levels for the outline.
1364 This has the effect that two stars are being added/taken away in
1365 promotion/demotion commands. It also influences how levels are
1366 handled by the exporters.
1367 Changing it requires restart of `font-lock-mode' to become effective
1368 for fontification also in regions already fontified.
1369 You may also set this on a per-file basis by adding one of the following
1370 lines to the buffer:
1374 :group
'org-edit-structure
1375 :group
'org-appearance
1378 (defcustom org-adapt-indentation t
1379 "Non-nil means adapt indentation to outline node level.
1381 When this variable is set, Org assumes that you write outlines by
1382 indenting text in each node to align with the headline (after the stars).
1383 The following issues are influenced by this variable:
1385 - When this is set and the *entire* text in an entry is indented, the
1386 indentation is increased by one space in a demotion command, and
1387 decreased by one in a promotion command. If any line in the entry
1388 body starts with text at column 0, indentation is not changed at all.
1390 - Property drawers and planning information is inserted indented when
1391 this variable s set. When nil, they will not be indented.
1393 - TAB indents a line relative to context. The lines below a headline
1394 will be indented when this variable is set.
1396 Note that this is all about true indentation, by adding and removing
1397 space characters. See also `org-indent.el' which does level-dependent
1398 indentation in a virtual way, i.e. at display time in Emacs."
1399 :group
'org-edit-structure
1402 (defcustom org-special-ctrl-a
/e nil
1403 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1405 When t, `C-a' will bring back the cursor to the beginning of the
1406 headline text, i.e. after the stars and after a possible TODO
1407 keyword. In an item, this will be the position after bullet and
1408 check-box, if any. When the cursor is already at that position,
1409 another `C-a' will bring it to the beginning of the line.
1411 `C-e' will jump to the end of the headline, ignoring the presence
1412 of tags in the headline. A second `C-e' will then jump to the
1413 true end of the line, after any tags. This also means that, when
1414 this variable is non-nil, `C-e' also will never jump beyond the
1415 end of the heading of a folded section, i.e. not after the
1418 When set to the symbol `reversed', the first `C-a' or `C-e' works
1419 normally, going to the true line boundary first. Only a directly
1420 following, identical keypress will bring the cursor to the
1423 This may also be a cons cell where the behavior for `C-a' and
1424 `C-e' is set separately."
1425 :group
'org-edit-structure
1427 (const :tag
"off" nil
)
1428 (const :tag
"on: after stars/bullet and before tags first" t
)
1429 (const :tag
"reversed: true line boundary first" reversed
)
1430 (cons :tag
"Set C-a and C-e separately"
1431 (choice :tag
"Special C-a"
1432 (const :tag
"off" nil
)
1433 (const :tag
"on: after stars/bullet first" t
)
1434 (const :tag
"reversed: before stars/bullet first" reversed
))
1435 (choice :tag
"Special C-e"
1436 (const :tag
"off" nil
)
1437 (const :tag
"on: before tags first" t
)
1438 (const :tag
"reversed: after tags first" reversed
)))))
1439 (org-defvaralias 'org-special-ctrl-a
'org-special-ctrl-a
/e
)
1441 (defcustom org-special-ctrl-k nil
1442 "Non-nil means `C-k' will behave specially in headlines.
1443 When nil, `C-k' will call the default `kill-line' command.
1444 When t, the following will happen while the cursor is in the headline:
1446 - When the cursor is at the beginning of a headline, kill the entire
1447 line and possible the folded subtree below the line.
1448 - When in the middle of the headline text, kill the headline up to the tags.
1449 - When after the headline text, kill the tags."
1450 :group
'org-edit-structure
1453 (defcustom org-ctrl-k-protect-subtree nil
1454 "Non-nil means, do not delete a hidden subtree with C-k.
1455 When set to the symbol `error', simply throw an error when C-k is
1456 used to kill (part-of) a headline that has hidden text behind it.
1457 Any other non-nil value will result in a query to the user, if it is
1458 OK to kill that hidden subtree. When nil, kill without remorse."
1459 :group
'org-edit-structure
1462 (const :tag
"Do not protect hidden subtrees" nil
)
1463 (const :tag
"Protect hidden subtrees with a security query" t
)
1464 (const :tag
"Never kill a hidden subtree with C-k" error
)))
1466 (defcustom org-special-ctrl-o t
1467 "Non-nil means, make `C-o' insert a row in tables."
1468 :group
'org-edit-structure
1471 (defcustom org-catch-invisible-edits nil
1472 "Check if in invisible region before inserting or deleting a character.
1475 nil Do not check, so just do invisible edits.
1476 error Throw an error and do nothing.
1477 show Make point visible, and do the requested edit.
1478 show-and-error Make point visible, then throw an error and abort the edit.
1479 smart Make point visible, and do insertion/deletion if it is
1480 adjacent to visible text and the change feels predictable.
1481 Never delete a previously invisible character or add in the
1482 middle or right after an invisible region. Basically, this
1483 allows insertion and backward-delete right before ellipses.
1484 FIXME: maybe in this case we should not even show?"
1485 :group
'org-edit-structure
1488 (const :tag
"Do not check" nil
)
1489 (const :tag
"Throw error when trying to edit" error
)
1490 (const :tag
"Unhide, but do not do the edit" show-and-error
)
1491 (const :tag
"Show invisible part and do the edit" show
)
1492 (const :tag
"Be smart and do the right thing" smart
)))
1494 (defcustom org-yank-folded-subtrees t
1495 "Non-nil means when yanking subtrees, fold them.
1496 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1497 it starts with a heading and all other headings in it are either children
1498 or siblings, then fold all the subtrees. However, do this only if no
1499 text after the yank would be swallowed into a folded tree by this action."
1500 :group
'org-edit-structure
1503 (defcustom org-yank-adjusted-subtrees nil
1504 "Non-nil means when yanking subtrees, adjust the level.
1505 With this setting, `org-paste-subtree' is used to insert the subtree, see
1506 this function for details."
1507 :group
'org-edit-structure
1510 (defcustom org-M-RET-may-split-line
'((default . t
))
1511 "Non-nil means M-RET will split the line at the cursor position.
1512 When nil, it will go to the end of the line before making a
1514 You may also set this option in a different way for different
1515 contexts. Valid contexts are:
1517 headline when creating a new headline
1518 item when creating a new item
1519 table in a table field
1520 default the value to be used for all contexts not explicitly
1522 :group
'org-structure
1525 (const :tag
"Always" t
)
1526 (const :tag
"Never" nil
)
1527 (repeat :greedy t
:tag
"Individual contexts"
1529 (choice :tag
"Context"
1537 (defcustom org-insert-heading-respect-content nil
1538 "Non-nil means insert new headings after the current subtree.
1539 When nil, the new heading is created directly after the current line.
1540 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1541 this variable on for the duration of the command."
1542 :group
'org-structure
1545 (defcustom org-blank-before-new-entry
'((heading . auto
)
1546 (plain-list-item . auto
))
1547 "Should `org-insert-heading' leave a blank line before new heading/item?
1548 The value is an alist, with `heading' and `plain-list-item' as CAR,
1549 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1550 which case Org will look at the surrounding headings/items and try to
1551 make an intelligent decision whether to insert a blank line or not.
1553 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1554 the setting here is ignored and no empty line is inserted to avoid breaking
1555 the list structure."
1556 :group
'org-edit-structure
1558 (cons (const heading
)
1559 (choice (const :tag
"Never" nil
)
1560 (const :tag
"Always" t
)
1561 (const :tag
"Auto" auto
)))
1562 (cons (const plain-list-item
)
1563 (choice (const :tag
"Never" nil
)
1564 (const :tag
"Always" t
)
1565 (const :tag
"Auto" auto
)))))
1567 (defcustom org-insert-heading-hook nil
1568 "Hook being run after inserting a new heading."
1569 :group
'org-edit-structure
1572 (defcustom org-enable-fixed-width-editor t
1573 "Non-nil means lines starting with \":\" are treated as fixed-width.
1574 This currently only means they are never auto-wrapped.
1575 When nil, such lines will be treated like ordinary lines."
1576 :group
'org-edit-structure
1579 (defcustom org-goto-auto-isearch t
1580 "Non-nil means typing characters in `org-goto' starts incremental search.
1581 When nil, you can use these keybindings to navigate the buffer:
1583 q Quit the org-goto interface
1584 n Go to the next visible heading
1585 p Go to the previous visible heading
1586 f Go one heading forward on same level
1587 b Go one heading backward on same level
1588 u Go one heading up"
1589 :group
'org-edit-structure
1592 (defgroup org-sparse-trees nil
1593 "Options concerning sparse trees in Org-mode."
1594 :tag
"Org Sparse Trees"
1595 :group
'org-structure
)
1597 (defcustom org-highlight-sparse-tree-matches t
1598 "Non-nil means highlight all matches that define a sparse tree.
1599 The highlights will automatically disappear the next time the buffer is
1600 changed by an edit command."
1601 :group
'org-sparse-trees
1604 (defcustom org-remove-highlights-with-change t
1605 "Non-nil means any change to the buffer will remove temporary highlights.
1606 Such highlights are created by `org-occur' and `org-clock-display'.
1607 When nil, `C-c C-c' needs to be used to get rid of the highlights.
1608 The highlights created by `org-toggle-latex-fragment' always need
1609 `C-c C-x C-l' to be removed."
1610 :group
'org-sparse-trees
1615 (defcustom org-occur-hook
'(org-first-headline-recenter)
1616 "Hook that is run after `org-occur' has constructed a sparse tree.
1617 This can be used to recenter the window to show as much of the structure
1619 :group
'org-sparse-trees
1622 (defgroup org-imenu-and-speedbar nil
1623 "Options concerning imenu and speedbar in Org-mode."
1624 :tag
"Org Imenu and Speedbar"
1625 :group
'org-structure
)
1627 (defcustom org-imenu-depth
2
1628 "The maximum level for Imenu access to Org-mode headlines.
1629 This also applied for speedbar access."
1630 :group
'org-imenu-and-speedbar
1633 (defgroup org-table nil
1634 "Options concerning tables in Org-mode."
1638 (defcustom org-enable-table-editor
'optimized
1639 "Non-nil means lines starting with \"|\" are handled by the table editor.
1640 When nil, such lines will be treated like ordinary lines.
1642 When equal to the symbol `optimized', the table editor will be optimized to
1644 - Automatic overwrite mode in front of whitespace in table fields.
1645 This makes the structure of the table stay in tact as long as the edited
1646 field does not exceed the column width.
1647 - Minimize the number of realigns. Normally, the table is aligned each time
1648 TAB or RET are pressed to move to another field. With optimization this
1649 happens only if changes to a field might have changed the column width.
1650 Optimization requires replacing the functions `self-insert-command',
1651 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1652 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1653 very good at guessing when a re-align will be necessary, but you can always
1654 force one with \\[org-ctrl-c-ctrl-c].
1656 If you would like to use the optimized version in Org-mode, but the
1657 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1659 This variable can be used to turn on and off the table editor during a session,
1660 but in order to toggle optimization, a restart is required.
1662 See also the variable `org-table-auto-blank-field'."
1665 (const :tag
"off" nil
)
1667 (const :tag
"on, optimized" optimized
)))
1669 (defcustom org-self-insert-cluster-for-undo
(or (featurep 'xemacs
)
1670 (version<= emacs-version
"24.1"))
1671 "Non-nil means cluster self-insert commands for undo when possible.
1672 If this is set, then, like in the Emacs command loop, 20 consecutive
1673 characters will be undone together.
1674 This is configurable, because there is some impact on typing performance."
1678 (defcustom org-table-tab-recognizes-table.el t
1679 "Non-nil means TAB will automatically notice a table.el table.
1680 When it sees such a table, it moves point into it and - if necessary -
1681 calls `table-recognize-table'."
1682 :group
'org-table-editing
1685 (defgroup org-link nil
1686 "Options concerning links in Org-mode."
1690 (defvar org-link-abbrev-alist-local nil
1691 "Buffer-local version of `org-link-abbrev-alist', which see.
1692 The value of this is taken from the #+LINK lines.")
1693 (make-variable-buffer-local 'org-link-abbrev-alist-local
)
1695 (defcustom org-link-abbrev-alist nil
1696 "Alist of link abbreviations.
1697 The car of each element is a string, to be replaced at the start of a link.
1698 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1699 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1701 [[linkkey:tag][description]]
1703 The 'linkkey' must be a word word, starting with a letter, followed
1704 by letters, numbers, '-' or '_'.
1706 If REPLACE is a string, the tag will simply be appended to create the link.
1707 If the string contains \"%s\", the tag will be inserted there. If the string
1708 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1709 at that point (see the function `url-hexify-string'). If the string contains
1710 the specifier \"%(my-function)\", then the custom function `my-function' will
1711 be invoked: this function takes the tag as its only argument and must return
1714 REPLACE may also be a function that will be called with the tag as the
1715 only argument to create the link, which should be returned as a string.
1717 See the manual for examples."
1721 (string :tag
"Protocol")
1723 (string :tag
"Format")
1726 (defcustom org-descriptive-links t
1727 "Non-nil means Org will display descriptive links.
1728 E.g. [[http://orgmode.org][Org website]] will be displayed as
1729 \"Org Website\", hiding the link itself and just displaying its
1730 description. When set to `nil', Org will display the full links
1733 You can interactively set the value of this variable by calling
1734 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1738 (defcustom org-link-file-path-type
'adaptive
1739 "How the path name in file links should be stored.
1742 relative Relative to the current directory, i.e. the directory of the file
1743 into which the link is being inserted.
1744 absolute Absolute path, if possible with ~ for home directory.
1745 noabbrev Absolute path, no abbreviation of home directory.
1746 adaptive Use relative path for files in the current directory and sub-
1747 directories of it. For other files, use an absolute path."
1755 (defvaralias 'org-activate-links
'org-highlight-links
)
1756 (defcustom org-highlight-links
'(bracket angle plain radio tag date footnote
)
1757 "Types of links that should be highlighted in Org-mode files.
1759 This is a list of symbols, each one of them leading to the
1760 highlighting of a certain link type.
1762 You can still open links that are not highlighted.
1764 In principle, it does not hurt to turn on highlighting for all
1765 link types. There may be a small gain when turning off unused
1766 link types. The types are:
1768 bracket The recommended [[link][description]] or [[link]] links with hiding.
1769 angle Links in angular brackets that may contain whitespace like
1770 <bbdb:Carsten Dominik>.
1771 plain Plain links in normal text, no whitespace, like http://google.com.
1772 radio Text that is matched by a radio target, see manual for details.
1773 tag Tag settings in a headline (link to tag search).
1774 date Time stamps (link to calendar).
1775 footnote Footnote labels.
1777 If you set this variable during an Emacs session, use `org-mode-restart'
1778 in the Org buffer so that the change takes effect."
1780 :group
'org-appearance
1781 :type
'(set :greedy t
1782 (const :tag
"Double bracket links" bracket
)
1783 (const :tag
"Angular bracket links" angle
)
1784 (const :tag
"Plain text links" plain
)
1785 (const :tag
"Radio target matches" radio
)
1786 (const :tag
"Tags" tag
)
1787 (const :tag
"Timestamps" date
)
1788 (const :tag
"Footnotes" footnote
)))
1790 (defcustom org-make-link-description-function nil
1791 "Function to use for generating link descriptions from links.
1792 When nil, the link location will be used. This function must take
1793 two parameters: the first one is the link, the second one is the
1794 description generated by `org-insert-link'. The function should
1795 return the description to use."
1797 :type
'(choice (const nil
) (function)))
1799 (defgroup org-link-store nil
1800 "Options concerning storing links in Org-mode."
1801 :tag
"Org Store Link"
1804 (defcustom org-url-hexify-p t
1805 "When non-nil, hexify URL when creating a link."
1808 :group
'org-link-store
)
1810 (defcustom org-email-link-description-format
"Email %c: %.30s"
1811 "Format of the description part of a link to an email or usenet message.
1812 The following %-escapes will be replaced by corresponding information:
1814 %F full \"From\" field
1815 %f name, taken from \"From\" field, address if no name
1816 %T full \"To\" field
1817 %t first name in \"To\" field, address if no name
1818 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1819 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1824 You may use normal field width specification between the % and the letter.
1825 This is for example useful to limit the length of the subject.
1827 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1828 :group
'org-link-store
1831 (defcustom org-from-is-user-regexp
1833 (when (and user-mail-address
(not (string= user-mail-address
"")))
1834 (setq r1
(concat "\\<" (regexp-quote user-mail-address
) "\\>")))
1835 (when (and user-full-name
(not (string= user-full-name
"")))
1836 (setq r2
(concat "\\<" (regexp-quote user-full-name
) "\\>")))
1837 (if (and r1 r2
) (concat r1
"\\|" r2
) (or r1 r2
)))
1838 "Regexp matched against the \"From:\" header of an email or usenet message.
1839 It should match if the message is from the user him/herself."
1840 :group
'org-link-store
1843 (defcustom org-context-in-file-links t
1844 "Non-nil means file links from `org-store-link' contain context.
1845 A search string will be added to the file name with :: as separator and
1846 used to find the context when the link is activated by the command
1847 `org-open-at-point'. When this option is t, the entire active region
1848 will be placed in the search string of the file link. If set to a
1849 positive integer, only the first n lines of context will be stored.
1851 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1852 negates this setting for the duration of the command."
1853 :group
'org-link-store
1854 :type
'(choice boolean integer
))
1856 (defcustom org-keep-stored-link-after-insertion nil
1857 "Non-nil means keep link in list for entire session.
1859 The command `org-store-link' adds a link pointing to the current
1860 location to an internal list. These links accumulate during a session.
1861 The command `org-insert-link' can be used to insert links into any
1862 Org-mode file (offering completion for all stored links). When this
1863 option is nil, every link which has been inserted once using \\[org-insert-link]
1864 will be removed from the list, to make completing the unused links
1866 :group
'org-link-store
1869 (defgroup org-link-follow nil
1870 "Options concerning following links in Org-mode."
1871 :tag
"Org Follow Link"
1874 (defcustom org-link-translation-function nil
1875 "Function to translate links with different syntax to Org syntax.
1876 This can be used to translate links created for example by the Planner
1877 or emacs-wiki packages to Org syntax.
1878 The function must accept two parameters, a TYPE containing the link
1879 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1880 which is everything after the link protocol. It should return a cons
1881 with possibly modified values of type and path.
1882 Org contains a function for this, so if you set this variable to
1883 `org-translate-link-from-planner', you should be able follow many
1884 links created by planner."
1885 :group
'org-link-follow
1886 :type
'(choice (const nil
) (function)))
1888 (defcustom org-follow-link-hook nil
1889 "Hook that is run after a link has been followed."
1890 :group
'org-link-follow
1893 (defcustom org-tab-follows-link nil
1894 "Non-nil means on links TAB will follow the link.
1895 Needs to be set before org.el is loaded.
1896 This really should not be used, it does not make sense, and the
1897 implementation is bad."
1898 :group
'org-link-follow
1901 (defcustom org-return-follows-link nil
1902 "Non-nil means on links RET will follow the link.
1903 In tables, the special behavior of RET has precedence."
1904 :group
'org-link-follow
1907 (defcustom org-mouse-1-follows-link
1908 (if (boundp 'mouse-1-click-follows-link
) mouse-1-click-follows-link t
)
1909 "Non-nil means mouse-1 on a link will follow the link.
1910 A longer mouse click will still set point. Does not work on XEmacs.
1911 Needs to be set before org.el is loaded."
1912 :group
'org-link-follow
1914 :package-version
'(Org .
"8.3")
1916 (const :tag
"A double click follows the link" double
)
1917 (const :tag
"Unconditionally follow the link with mouse-1" t
)
1918 (integer :tag
"mouse-1 click does not follow the link if longer than N ms" 450)))
1920 (defcustom org-mark-ring-length
4
1921 "Number of different positions to be recorded in the ring.
1922 Changing this requires a restart of Emacs to work correctly."
1923 :group
'org-link-follow
1926 (defcustom org-link-search-must-match-exact-headline
'query-to-create
1927 "Non-nil means internal links in Org files must exactly match a headline.
1928 When nil, the link search tries to match a phrase with all words
1929 in the search text."
1930 :group
'org-link-follow
1933 (const :tag
"Use fuzzy text search" nil
)
1934 (const :tag
"Match only exact headline" t
)
1935 (const :tag
"Match exact headline or query to create it"
1938 (defcustom org-link-frame-setup
1939 '((vm . vm-visit-folder-other-frame
)
1940 (vm-imap . vm-visit-imap-folder-other-frame
)
1941 (gnus . org-gnus-no-new-news
)
1942 (file . find-file-other-window
)
1943 (wl . wl-other-frame
))
1944 "Setup the frame configuration for following links.
1945 When following a link with Emacs, it may often be useful to display
1946 this link in another window or frame. This variable can be used to
1947 set this up for the different types of links.
1950 `vm-visit-folder-other-window'
1951 `vm-visit-folder-other-frame'
1952 For Gnus, use any of
1955 `org-gnus-no-new-news'
1956 For FILE, use any of
1958 `find-file-other-window'
1959 `find-file-other-frame'
1960 For Wanderlust use any of
1963 For the calendar, use the variable `calendar-setup'.
1964 For BBDB, it is currently only possible to display the matches in
1966 :group
'org-link-follow
1970 (const vm-visit-folder
)
1971 (const vm-visit-folder-other-window
)
1972 (const vm-visit-folder-other-frame
)))
1973 (cons (const vm-imap
)
1975 (const vm-visit-imap-folder
)
1976 (const vm-visit-imap-folder-other-window
)
1977 (const vm-visit-imap-folder-other-frame
)))
1981 (const gnus-other-frame
)
1982 (const org-gnus-no-new-news
)))
1986 (const find-file-other-window
)
1987 (const find-file-other-frame
)))
1991 (const wl-other-frame
)))))
1993 (defcustom org-display-internal-link-with-indirect-buffer nil
1994 "Non-nil means use indirect buffer to display infile links.
1995 Activating internal links (from one location in a file to another location
1996 in the same file) normally just jumps to the location. When the link is
1997 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1999 another window. When this option is set, the other window actually displays
2000 an indirect buffer clone of the current buffer, to avoid any visibility
2001 changes to the current buffer."
2002 :group
'org-link-follow
2005 (defcustom org-open-non-existing-files nil
2006 "Non-nil means `org-open-file' will open non-existing files.
2007 When nil, an error will be generated.
2008 This variable applies only to external applications because they
2009 might choke on non-existing files. If the link is to a file that
2010 will be opened in Emacs, the variable is ignored."
2011 :group
'org-link-follow
2014 (defcustom org-open-directory-means-index-dot-org nil
2015 "Non-nil means a link to a directory really means to index.org.
2016 When nil, following a directory link will run dired or open a finder/explorer
2017 window on that directory."
2018 :group
'org-link-follow
2021 (defcustom org-confirm-shell-link-function
'yes-or-no-p
2022 "Non-nil means ask for confirmation before executing shell links.
2023 Shell links can be dangerous: just think about a link
2025 [[shell:rm -rf ~/*][Google Search]]
2027 This link would show up in your Org-mode document as \"Google Search\",
2028 but really it would remove your entire home directory.
2029 Therefore we advise against setting this variable to nil.
2030 Just change it to `y-or-n-p' if you want to confirm with a
2031 single keystroke rather than having to type \"yes\"."
2032 :group
'org-link-follow
2034 (const :tag
"with yes-or-no (safer)" yes-or-no-p
)
2035 (const :tag
"with y-or-n (faster)" y-or-n-p
)
2036 (const :tag
"no confirmation (dangerous)" nil
)))
2037 (put 'org-confirm-shell-link-function
2038 'safe-local-variable
2039 (lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
2041 (defcustom org-confirm-shell-link-not-regexp
""
2042 "A regexp to skip confirmation for shell links."
2043 :group
'org-link-follow
2047 (defcustom org-confirm-elisp-link-function
'yes-or-no-p
2048 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2049 Elisp links can be dangerous: just think about a link
2051 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2053 This link would show up in your Org-mode document as \"Google Search\",
2054 but really it would remove your entire home directory.
2055 Therefore we advise against setting this variable to nil.
2056 Just change it to `y-or-n-p' if you want to confirm with a
2057 single keystroke rather than having to type \"yes\"."
2058 :group
'org-link-follow
2060 (const :tag
"with yes-or-no (safer)" yes-or-no-p
)
2061 (const :tag
"with y-or-n (faster)" y-or-n-p
)
2062 (const :tag
"no confirmation (dangerous)" nil
)))
2063 (put 'org-confirm-shell-link-function
2064 'safe-local-variable
2065 (lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
2067 (defcustom org-confirm-elisp-link-not-regexp
""
2068 "A regexp to skip confirmation for Elisp links."
2069 :group
'org-link-follow
2073 (defconst org-file-apps-defaults-gnu
2077 "Default file applications on a UNIX or GNU/Linux system.
2078 See `org-file-apps'.")
2080 (defconst org-file-apps-defaults-macosx
2083 (system .
"open %s")
2085 ("eps.gz" .
"gv %s")
2087 ("fig" .
"xfig %s"))
2088 "Default file applications on a MacOS X system.
2089 The system \"open\" is known as a default, but we use X11 applications
2090 for some files for which the OS does not have a good default.
2091 See `org-file-apps'.")
2093 (defconst org-file-apps-defaults-windowsnt
2097 (list (if (featurep 'xemacs
)
2098 'mswindows-shell-execute
2102 (list (if (featurep 'xemacs
)
2103 'mswindows-shell-execute
2106 "Default file applications on a Windows NT system.
2107 The system \"open\" is used for most files.
2108 See `org-file-apps'.")
2110 (defcustom org-file-apps
2111 '((auto-mode . emacs
)
2112 ("\\.mm\\'" . default
)
2113 ("\\.x?html?\\'" . default
)
2114 ("\\.pdf\\'" . default
))
2115 "External applications for opening `file:path' items in a document.
2116 Org-mode uses system defaults for different file types, but
2117 you can use this variable to set the application for a given file
2118 extension. The entries in this list are cons cells where the car identifies
2119 files and the cdr the corresponding command. Possible values for the
2121 \"string\" A string as a file identifier can be interpreted in different
2122 ways, depending on its contents:
2124 - Alphanumeric characters only:
2125 Match links with this file extension.
2126 Example: (\"pdf\" . \"evince %s\")
2127 to open PDFs with evince.
2129 - Regular expression: Match links where the
2130 filename matches the regexp. If you want to
2131 use groups here, use shy groups.
2133 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2134 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2135 to open *.html and *.xhtml with firefox.
2137 - Regular expression which contains (non-shy) groups:
2138 Match links where the whole link, including \"::\", and
2139 anything after that, matches the regexp.
2140 In a custom command string, %1, %2, etc. are replaced with
2141 the parts of the link that were matched by the groups.
2142 For backwards compatibility, if a command string is given
2143 that does not use any of the group matches, this case is
2144 handled identically to the second one (i.e. match against
2146 In a custom lisp form, you can access the group matches with
2147 (match-string n link).
2149 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2150 to open [[file:document.pdf::5]] with evince at page 5.
2152 `directory' Matches a directory
2153 `remote' Matches a remote file, accessible through tramp or efs.
2154 Remote files most likely should be visited through Emacs
2155 because external applications cannot handle such paths.
2156 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2157 so all files Emacs knows how to handle. Using this with
2158 command `emacs' will open most files in Emacs. Beware that this
2159 will also open html files inside Emacs, unless you add
2160 (\"html\" . default) to the list as well.
2161 t Default for files not matched by any of the other options.
2162 `system' The system command to open files, like `open' on Windows
2163 and Mac OS X, and mailcap under GNU/Linux. This is the command
2164 that will be selected if you call `C-c C-o' with a double
2165 \\[universal-argument] \\[universal-argument] prefix.
2167 Possible values for the command are:
2168 `emacs' The file will be visited by the current Emacs process.
2169 `default' Use the default application for this file type, which is the
2170 association for t in the list, most likely in the system-specific
2172 This can be used to overrule an unwanted setting in the
2173 system-specific variable.
2174 `system' Use the system command for opening files, like \"open\".
2175 This command is specified by the entry whose car is `system'.
2176 Most likely, the system-specific version of this variable
2177 does define this command, but you can overrule/replace it
2179 string A command to be executed by a shell; %s will be replaced
2180 by the path to the file.
2181 sexp A Lisp form which will be evaluated. The file path will
2182 be available in the Lisp variable `file'.
2183 For more examples, see the system specific constants
2184 `org-file-apps-defaults-macosx'
2185 `org-file-apps-defaults-windowsnt'
2186 `org-file-apps-defaults-gnu'."
2187 :group
'org-link-follow
2189 (cons (choice :value
""
2190 (string :tag
"Extension")
2191 (const :tag
"System command to open files" system
)
2192 (const :tag
"Default for unrecognized files" t
)
2193 (const :tag
"Remote file" remote
)
2194 (const :tag
"Links to a directory" directory
)
2195 (const :tag
"Any files that have Emacs modes"
2198 (const :tag
"Visit with Emacs" emacs
)
2199 (const :tag
"Use default" default
)
2200 (const :tag
"Use the system command" system
)
2201 (string :tag
"Command")
2202 (sexp :tag
"Lisp form")))))
2204 (defcustom org-doi-server-url
"http://dx.doi.org/"
2205 "The URL of the DOI server."
2208 :group
'org-link-follow
)
2210 (defgroup org-refile nil
2211 "Options concerning refiling entries in Org-mode."
2215 (defcustom org-directory
"~/org"
2216 "Directory with org files.
2217 This is just a default location to look for Org files. There is no need
2218 at all to put your files into this directory. It is only used in the
2219 following situations:
2221 1. When a capture template specifies a target file that is not an
2222 absolute path. The path will then be interpreted relative to
2224 2. When a capture note is filed away in an interactive way (when exiting the
2225 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2226 with `org-directory' as the default path."
2231 (defcustom org-default-notes-file
(convert-standard-filename "~/.notes")
2232 "Default target for storing notes.
2233 Used as a fall back file for org-capture.el, for templates that
2234 do not specify a target file."
2238 (const :tag
"Default from remember-data-file" nil
)
2241 (defcustom org-goto-interface
'outline
2242 "The default interface to be used for `org-goto'.
2244 outline The interface shows an outline of the relevant file
2245 and the correct heading is found by moving through
2246 the outline or by searching with incremental search.
2247 outline-path-completion Headlines in the current buffer are offered via
2248 completion. This is the interface also used by
2249 the refile command."
2252 (const :tag
"Outline" outline
)
2253 (const :tag
"Outline-path-completion" outline-path-completion
)))
2255 (defcustom org-goto-max-level
5
2256 "Maximum target level when running `org-goto' with refile interface."
2260 (defcustom org-reverse-note-order nil
2261 "Non-nil means store new notes at the beginning of a file or entry.
2262 When nil, new notes will be filed to the end of a file or entry.
2263 This can also be a list with cons cells of regular expressions that
2264 are matched against file names, and values."
2268 (const :tag
"Reverse always" t
)
2269 (const :tag
"Reverse never" nil
)
2270 (repeat :tag
"By file name regexp"
2271 (cons regexp boolean
))))
2273 (defcustom org-log-refile nil
2274 "Information to record when a task is refiled.
2276 Possible values are:
2278 nil Don't add anything
2279 time Add a time stamp to the task
2280 note Prompt for a note and add it with template `org-log-note-headings'
2282 This option can also be set with on a per-file-basis with
2284 #+STARTUP: nologrefile
2285 #+STARTUP: logrefile
2286 #+STARTUP: lognoterefile
2288 You can have local logging settings for a subtree by setting the LOGGING
2289 property to one or more of these keywords.
2291 When bulk-refiling from the agenda, the value `note' is forbidden and
2292 will temporarily be changed to `time'."
2294 :group
'org-progress
2297 (const :tag
"No logging" nil
)
2298 (const :tag
"Record timestamp" time
)
2299 (const :tag
"Record timestamp with note." note
)))
2301 (defcustom org-refile-targets nil
2302 "Targets for refiling entries with \\[org-refile].
2303 This is a list of cons cells. Each cell contains:
2304 - a specification of the files to be considered, either a list of files,
2305 or a symbol whose function or variable value will be used to retrieve
2306 a file name or a list of file names. If you use `org-agenda-files' for
2307 that, all agenda files will be scanned for targets. Nil means consider
2308 headings in the current buffer.
2309 - A specification of how to find candidate refile targets. This may be
2311 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2312 This tag has to be present in all target headlines, inheritance will
2314 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2316 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2317 headlines that are refiling targets.
2318 - a cons cell (:level . N). Any headline of level N is considered a target.
2319 Note that, when `org-odd-levels-only' is set, level corresponds to
2320 order in hierarchy, not to the number of stars.
2321 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2322 Note that, when `org-odd-levels-only' is set, level corresponds to
2323 order in hierarchy, not to the number of stars.
2325 Each element of this list generates a set of possible targets.
2326 The union of these sets is presented (with completion) to
2327 the user by `org-refile'.
2329 You can set the variable `org-refile-target-verify-function' to a function
2330 to verify each headline found by the simple criteria above.
2332 When this variable is nil, all top-level headlines in the current buffer
2333 are used, equivalent to the value `((nil . (:level . 1))'."
2337 (choice :value org-agenda-files
2338 (const :tag
"All agenda files" org-agenda-files
)
2339 (const :tag
"Current buffer" nil
)
2340 (function) (variable) (file))
2341 (choice :tag
"Identify target headline by"
2342 (cons :tag
"Specific tag" (const :value
:tag
) (string))
2343 (cons :tag
"TODO keyword" (const :value
:todo
) (string))
2344 (cons :tag
"Regular expression" (const :value
:regexp
) (regexp))
2345 (cons :tag
"Level number" (const :value
:level
) (integer))
2346 (cons :tag
"Max Level number" (const :value
:maxlevel
) (integer))))))
2348 (defcustom org-refile-target-verify-function nil
2349 "Function to verify if the headline at point should be a refile target.
2350 The function will be called without arguments, with point at the
2351 beginning of the headline. It should return t and leave point
2352 where it is if the headline is a valid target for refiling.
2354 If the target should not be selected, the function must return nil.
2355 In addition to this, it may move point to a place from where the search
2356 should be continued. For example, the function may decide that the entire
2357 subtree of the current entry should be excluded and move point to the end
2364 (defcustom org-refile-use-cache nil
2365 "Non-nil means cache refile targets to speed up the process.
2366 The cache for a particular file will be updated automatically when
2367 the buffer has been killed, or when any of the marker used for flagging
2368 refile targets no longer points at a live buffer.
2369 If you have added new entries to a buffer that might themselves be targets,
2370 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2371 find that easier, `C-u C-u C-u C-c C-w'."
2376 (defcustom org-refile-use-outline-path nil
2377 "Non-nil means provide refile targets as paths.
2378 So a level 3 headline will be available as level1/level2/level3.
2380 When the value is `file', also include the file name (without directory)
2381 into the path. In this case, you can also stop the completion after
2382 the file name, to get entries inserted as top level in the file.
2384 When `full-file-path', include the full file path."
2387 (const :tag
"Not" nil
)
2388 (const :tag
"Yes" t
)
2389 (const :tag
"Start with file name" file
)
2390 (const :tag
"Start with full file path" full-file-path
)))
2392 (defcustom org-outline-path-complete-in-steps t
2393 "Non-nil means complete the outline path in hierarchical steps.
2394 When Org-mode uses the refile interface to select an outline path
2395 \(see variable `org-refile-use-outline-path'), the completion of
2396 the path can be done is a single go, or if can be done in steps down
2397 the headline hierarchy. Going in steps is probably the best if you
2398 do not use a special completion package like `ido' or `icicles'.
2399 However, when using these packages, going in one step can be very
2400 fast, while still showing the whole path to the entry."
2404 (defcustom org-refile-allow-creating-parent-nodes nil
2405 "Non-nil means allow to create new nodes as refile targets.
2406 New nodes are then created by adding \"/new node name\" to the completion
2407 of an existing node. When the value of this variable is `confirm',
2408 new node creation must be confirmed by the user (recommended).
2409 When nil, the completion must match an existing entry.
2411 Note that, if the new heading is not seen by the criteria
2412 listed in `org-refile-targets', multiple instances of the same
2413 heading would be created by trying again to file under the new
2417 (const :tag
"Never" nil
)
2418 (const :tag
"Always" t
)
2419 (const :tag
"Prompt for confirmation" confirm
)))
2421 (defcustom org-refile-active-region-within-subtree nil
2422 "Non-nil means also refile active region within a subtree.
2424 By default `org-refile' doesn't allow refiling regions if they
2425 don't contain a set of subtrees, but it might be convenient to
2426 do so sometimes: in that case, the first line of the region is
2427 converted to a headline before refiling."
2432 (defgroup org-todo nil
2433 "Options concerning TODO items in Org-mode."
2437 (defgroup org-progress nil
2438 "Options concerning Progress logging in Org-mode."
2442 (defvar org-todo-interpretation-widgets
2443 '((:tag
"Sequence (cycling hits every state)" sequence
)
2444 (:tag
"Type (cycling directly to DONE)" type
))
2445 "The available interpretation symbols for customizing `org-todo-keywords'.
2446 Interested libraries should add to this list.")
2448 (defcustom org-todo-keywords
'((sequence "TODO" "DONE"))
2449 "List of TODO entry keyword sequences and their interpretation.
2450 \\<org-mode-map>This is a list of sequences.
2452 Each sequence starts with a symbol, either `sequence' or `type',
2453 indicating if the keywords should be interpreted as a sequence of
2454 action steps, or as different types of TODO items. The first
2455 keywords are states requiring action - these states will select a headline
2456 for inclusion into the global TODO list Org-mode produces. If one of
2457 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2458 signify that no further action is necessary. If \"|\" is not found,
2459 the last keyword is treated as the only DONE state of the sequence.
2461 The command \\[org-todo] cycles an entry through these states, and one
2462 additional state where no keyword is present. For details about this
2463 cycling, see the manual.
2465 TODO keywords and interpretation can also be set on a per-file basis with
2466 the special #+SEQ_TODO and #+TYP_TODO lines.
2468 Each keyword can optionally specify a character for fast state selection
2469 \(in combination with the variable `org-use-fast-todo-selection')
2470 and specifiers for state change logging, using the same syntax that
2471 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2472 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2473 indicates to record a time stamp each time this state is selected.
2475 Each keyword may also specify if a timestamp or a note should be
2476 recorded when entering or leaving the state, by adding additional
2477 characters in the parenthesis after the keyword. This looks like this:
2478 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2479 record only the time of the state change. With X and Y being either
2480 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2481 Y when leaving the state if and only if the *target* state does not
2482 define X. You may omit any of the fast-selection key or X or /Y,
2483 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2485 For backward compatibility, this variable may also be just a list
2486 of keywords. In this case the interpretation (sequence or type) will be
2487 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2489 :group
'org-keywords
2491 (repeat :tag
"Old syntax, just keywords"
2492 (string :tag
"Keyword"))
2493 (repeat :tag
"New syntax"
2496 :tag
"Interpretation"
2497 ;;Quick and dirty way to see
2498 ;;`org-todo-interpretations'. This takes the
2499 ;;place of item arguments
2507 org-todo-interpretation-widgets
))
2510 (string :tag
"Keyword"))))))
2512 (defvar org-todo-keywords-1 nil
2513 "All TODO and DONE keywords active in a buffer.")
2514 (make-variable-buffer-local 'org-todo-keywords-1
)
2515 (defvar org-todo-keywords-for-agenda nil
)
2516 (defvar org-done-keywords-for-agenda nil
)
2517 (defvar org-todo-keyword-alist-for-agenda nil
)
2518 (defvar org-tag-alist-for-agenda nil
2519 "Alist of all tags from all agenda files.")
2520 (defvar org-tag-groups-alist-for-agenda nil
2521 "Alist of all groups tags from all current agenda files.")
2522 (defvar org-tag-groups-alist nil
)
2523 (make-variable-buffer-local 'org-tag-groups-alist
)
2524 (defvar org-agenda-contributing-files nil
)
2525 (defvar org-not-done-keywords nil
)
2526 (make-variable-buffer-local 'org-not-done-keywords
)
2527 (defvar org-done-keywords nil
)
2528 (make-variable-buffer-local 'org-done-keywords
)
2529 (defvar org-todo-heads nil
)
2530 (make-variable-buffer-local 'org-todo-heads
)
2531 (defvar org-todo-sets nil
)
2532 (make-variable-buffer-local 'org-todo-sets
)
2533 (defvar org-todo-log-states nil
)
2534 (make-variable-buffer-local 'org-todo-log-states
)
2535 (defvar org-todo-kwd-alist nil
)
2536 (make-variable-buffer-local 'org-todo-kwd-alist
)
2537 (defvar org-todo-key-alist nil
)
2538 (make-variable-buffer-local 'org-todo-key-alist
)
2539 (defvar org-todo-key-trigger nil
)
2540 (make-variable-buffer-local 'org-todo-key-trigger
)
2542 (defcustom org-todo-interpretation
'sequence
2543 "Controls how TODO keywords are interpreted.
2544 This variable is in principle obsolete and is only used for
2545 backward compatibility, if the interpretation of todo keywords is
2546 not given already in `org-todo-keywords'. See that variable for
2549 :group
'org-keywords
2550 :type
'(choice (const sequence
)
2553 (defcustom org-use-fast-todo-selection t
2554 "Non-nil means use the fast todo selection scheme with C-c C-t.
2555 This variable describes if and under what circumstances the cycling
2556 mechanism for TODO keywords will be replaced by a single-key, direct
2559 When nil, fast selection is never used.
2561 When the symbol `prefix', it will be used when `org-todo' is called
2562 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2563 `C-u t' in an agenda buffer.
2565 When t, fast selection is used by default. In this case, the prefix
2566 argument forces cycling instead.
2568 In all cases, the special interface is only used if access keys have
2569 actually been assigned by the user, i.e. if keywords in the configuration
2570 are followed by a letter in parenthesis, like TODO(t)."
2573 (const :tag
"Never" nil
)
2574 (const :tag
"By default" t
)
2575 (const :tag
"Only with C-u C-c C-t" prefix
)))
2577 (defcustom org-provide-todo-statistics t
2578 "Non-nil means update todo statistics after insert and toggle.
2579 ALL-HEADLINES means update todo statistics by including headlines
2580 with no TODO keyword as well, counting them as not done.
2581 A list of TODO keywords means the same, but skip keywords that are
2583 When set to a list of two lists, the first list contains keywords
2584 to consider as TODO keywords, the second list contains keywords
2585 to consider as DONE keywords.
2587 When this is set, todo statistics is updated in the parent of the
2588 current entry each time a todo state is changed."
2591 (const :tag
"Yes, only for TODO entries" t
)
2592 (const :tag
"Yes, including all entries" all-headlines
)
2593 (repeat :tag
"Yes, for TODOs in this list"
2594 (string :tag
"TODO keyword"))
2595 (list :tag
"Yes, for TODOs and DONEs in these lists"
2596 (repeat (string :tag
"TODO keyword"))
2597 (repeat (string :tag
"DONE keyword")))
2598 (other :tag
"No TODO statistics" nil
)))
2600 (defcustom org-hierarchical-todo-statistics t
2601 "Non-nil means TODO statistics covers just direct children.
2602 When nil, all entries in the subtree are considered.
2603 This has only an effect if `org-provide-todo-statistics' is set.
2604 To set this to nil for only a single subtree, use a COOKIE_DATA
2605 property and include the word \"recursive\" into the value."
2609 (defcustom org-after-todo-state-change-hook nil
2610 "Hook which is run after the state of a TODO item was changed.
2611 The new state (a string with a TODO keyword, or nil) is available in the
2612 Lisp variable `org-state'."
2616 (defvar org-blocker-hook nil
2617 "Hook for functions that are allowed to block a state change.
2619 Functions in this hook should not modify the buffer.
2620 Each function gets as its single argument a property list,
2621 see `org-trigger-hook' for more information about this list.
2623 If any of the functions in this hook returns nil, the state change
2626 (defvar org-trigger-hook nil
2627 "Hook for functions that are triggered by a state change.
2629 Each function gets as its single argument a property list with at
2630 least the following elements:
2632 (:type type-of-change :position pos-at-entry-start
2633 :from old-state :to new-state)
2635 Depending on the type, more properties may be present.
2637 This mechanism is currently implemented for:
2641 :type todo-state-change
2642 :from previous state (keyword as a string), or nil, or a symbol
2643 'todo' or 'done', to indicate the general type of state.
2644 :to new state, like in :from")
2646 (defcustom org-enforce-todo-dependencies nil
2647 "Non-nil means undone TODO entries will block switching the parent to DONE.
2648 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2649 be blocked if any prior sibling is not yet done.
2650 Finally, if the parent is blocked because of ordered siblings of its own,
2651 the child will also be blocked."
2652 :set
(lambda (var val
)
2655 (add-hook 'org-blocker-hook
2656 'org-block-todo-from-children-or-siblings-or-parent
)
2657 (remove-hook 'org-blocker-hook
2658 'org-block-todo-from-children-or-siblings-or-parent
)))
2662 (defcustom org-enforce-todo-checkbox-dependencies nil
2663 "Non-nil means unchecked boxes will block switching the parent to DONE.
2664 When this is nil, checkboxes have no influence on switching TODO states.
2665 When non-nil, you first need to check off all check boxes before the TODO
2666 entry can be switched to DONE.
2667 This variable needs to be set before org.el is loaded, and you need to
2668 restart Emacs after a change to make the change effective. The only way
2669 to change is while Emacs is running is through the customize interface."
2670 :set
(lambda (var val
)
2673 (add-hook 'org-blocker-hook
2674 'org-block-todo-from-checkboxes
)
2675 (remove-hook 'org-blocker-hook
2676 'org-block-todo-from-checkboxes
)))
2680 (defcustom org-treat-insert-todo-heading-as-state-change nil
2681 "Non-nil means inserting a TODO heading is treated as state change.
2682 So when the command \\[org-insert-todo-heading] is used, state change
2683 logging will apply if appropriate. When nil, the new TODO item will
2684 be inserted directly, and no logging will take place."
2688 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2689 "Non-nil means switching TODO states with S-cursor counts as state change.
2690 This is the default behavior. However, setting this to nil allows a
2691 convenient way to select a TODO state and bypass any logging associated
2696 (defcustom org-todo-state-tags-triggers nil
2697 "Tag changes that should be triggered by TODO state changes.
2698 This is a list. Each entry is
2700 (state-change (tag . flag) .......)
2702 State-change can be a string with a state, and empty string to indicate the
2703 state that has no TODO keyword, or it can be one of the symbols `todo'
2704 or `done', meaning any not-done or done state, respectively."
2708 (cons (choice :tag
"When changing to"
2709 (const :tag
"Not-done state" todo
)
2710 (const :tag
"Done state" done
)
2711 (string :tag
"State"))
2713 (cons :tag
"Tag action"
2715 (choice (const :tag
"Add" t
) (const :tag
"Remove" nil
)))))))
2717 (defcustom org-log-done nil
2718 "Information to record when a task moves to the DONE state.
2720 Possible values are:
2722 nil Don't add anything, just change the keyword
2723 time Add a time stamp to the task
2724 note Prompt for a note and add it with template `org-log-note-headings'
2726 This option can also be set with on a per-file-basis with
2728 #+STARTUP: nologdone
2730 #+STARTUP: lognotedone
2732 You can have local logging settings for a subtree by setting the LOGGING
2733 property to one or more of these keywords."
2735 :group
'org-progress
2737 (const :tag
"No logging" nil
)
2738 (const :tag
"Record CLOSED timestamp" time
)
2739 (const :tag
"Record CLOSED timestamp with note." note
)))
2741 ;; Normalize old uses of org-log-done.
2743 ((eq org-log-done t
) (setq org-log-done
'time
))
2744 ((and (listp org-log-done
) (memq 'done org-log-done
))
2745 (setq org-log-done
'note
)))
2747 (defcustom org-log-reschedule nil
2748 "Information to record when the scheduling date of a tasks is modified.
2750 Possible values are:
2752 nil Don't add anything, just change the date
2753 time Add a time stamp to the task
2754 note Prompt for a note and add it with template `org-log-note-headings'
2756 This option can also be set with on a per-file-basis with
2758 #+STARTUP: nologreschedule
2759 #+STARTUP: logreschedule
2760 #+STARTUP: lognotereschedule"
2762 :group
'org-progress
2764 (const :tag
"No logging" nil
)
2765 (const :tag
"Record timestamp" time
)
2766 (const :tag
"Record timestamp with note." note
)))
2768 (defcustom org-log-redeadline nil
2769 "Information to record when the deadline date of a tasks is modified.
2771 Possible values are:
2773 nil Don't add anything, just change the date
2774 time Add a time stamp to the task
2775 note Prompt for a note and add it with template `org-log-note-headings'
2777 This option can also be set with on a per-file-basis with
2779 #+STARTUP: nologredeadline
2780 #+STARTUP: logredeadline
2781 #+STARTUP: lognoteredeadline
2783 You can have local logging settings for a subtree by setting the LOGGING
2784 property to one or more of these keywords."
2786 :group
'org-progress
2788 (const :tag
"No logging" nil
)
2789 (const :tag
"Record timestamp" time
)
2790 (const :tag
"Record timestamp with note." note
)))
2792 (defcustom org-log-note-clock-out nil
2793 "Non-nil means record a note when clocking out of an item.
2794 This can also be configured on a per-file basis by adding one of
2795 the following lines anywhere in the buffer:
2797 #+STARTUP: lognoteclock-out
2798 #+STARTUP: nolognoteclock-out"
2800 :group
'org-progress
2803 (defcustom org-log-done-with-time t
2804 "Non-nil means the CLOSED time stamp will contain date and time.
2805 When nil, only the date will be recorded."
2806 :group
'org-progress
2809 (defcustom org-log-note-headings
2810 '((done .
"CLOSING NOTE %t")
2811 (state .
"State %-12s from %-12S %t")
2812 (note .
"Note taken on %t")
2813 (reschedule .
"Rescheduled from %S on %t")
2814 (delschedule .
"Not scheduled, was %S on %t")
2815 (redeadline .
"New deadline from %S on %t")
2816 (deldeadline .
"Removed deadline, was %S on %t")
2817 (refile .
"Refiled on %t")
2819 "Headings for notes added to entries.
2820 The value is an alist, with the car being a symbol indicating the note
2821 context, and the cdr is the heading to be used. The heading may also be the
2823 %t in the heading will be replaced by a time stamp.
2824 %T will be an active time stamp instead the default inactive one
2825 %d will be replaced by a short-format time stamp.
2826 %D will be replaced by an active short-format time stamp.
2827 %s will be replaced by the new TODO state, in double quotes.
2828 %S will be replaced by the old TODO state, in double quotes.
2829 %u will be replaced by the user name.
2830 %U will be replaced by the full user name.
2832 In fact, it is not a good idea to change the `state' entry, because
2833 agenda log mode depends on the format of these entries."
2835 :group
'org-progress
2836 :type
'(list :greedy t
2837 (cons (const :tag
"Heading when closing an item" done
) string
)
2839 "Heading when changing todo state (todo sequence only)"
2841 (cons (const :tag
"Heading when just taking a note" note
) string
)
2842 (cons (const :tag
"Heading when rescheduling" reschedule
) string
)
2843 (cons (const :tag
"Heading when an item is no longer scheduled" delschedule
) string
)
2844 (cons (const :tag
"Heading when changing deadline" redeadline
) string
)
2845 (cons (const :tag
"Heading when deleting a deadline" deldeadline
) string
)
2846 (cons (const :tag
"Heading when refiling" refile
) string
)
2847 (cons (const :tag
"Heading when clocking out" clock-out
) string
)))
2849 (unless (assq 'note org-log-note-headings
)
2850 (push '(note .
"%t") org-log-note-headings
))
2852 (defcustom org-log-into-drawer nil
2853 "Non-nil means insert state change notes and time stamps into a drawer.
2854 When nil, state changes notes will be inserted after the headline and
2855 any scheduling and clock lines, but not inside a drawer.
2857 The value of this variable should be the name of the drawer to use.
2858 LOGBOOK is proposed as the default drawer for this purpose, you can
2859 also set this to a string to define the drawer of your choice.
2861 A value of t is also allowed, representing \"LOGBOOK\".
2863 A value of t or nil can also be set with on a per-file-basis with
2865 #+STARTUP: logdrawer
2866 #+STARTUP: nologdrawer
2868 If this variable is set, `org-log-state-notes-insert-after-drawers'
2871 You can set the property LOG_INTO_DRAWER to overrule this setting for
2874 :group
'org-progress
2876 (const :tag
"Not into a drawer" nil
)
2877 (const :tag
"LOGBOOK" t
)
2878 (string :tag
"Other")))
2880 (org-defvaralias 'org-log-state-notes-into-drawer
'org-log-into-drawer
)
2882 (defun org-log-into-drawer ()
2883 "Return the value of `org-log-into-drawer', but let properties overrule.
2884 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2885 used instead of the default value."
2886 (let ((p (org-entry-get nil
"LOG_INTO_DRAWER" 'inherit t
)))
2888 ((not p
) org-log-into-drawer
)
2889 ((equal p
"nil") nil
)
2890 ((equal p
"t") "LOGBOOK")
2893 (defcustom org-log-state-notes-insert-after-drawers nil
2894 "Non-nil means insert state change notes after any drawers in entry.
2895 Only the drawers that *immediately* follow the headline and the
2896 deadline/scheduled line are skipped.
2897 When nil, insert notes right after the heading and perhaps the line
2898 with deadline/scheduling if present.
2900 This variable will have no effect if `org-log-into-drawer' is
2903 :group
'org-progress
2906 (defcustom org-log-states-order-reversed t
2907 "Non-nil means the latest state note will be directly after heading.
2908 When nil, the state change notes will be ordered according to time.
2910 This option can also be set with on a per-file-basis with
2912 #+STARTUP: logstatesreversed
2913 #+STARTUP: nologstatesreversed"
2915 :group
'org-progress
2918 (defcustom org-todo-repeat-to-state nil
2919 "The TODO state to which a repeater should return the repeating task.
2920 By default this is the first task in a TODO sequence, or the previous state
2921 in a TODO_TYP set. But you can specify another task here.
2922 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2925 :type
'(choice (const :tag
"Head of sequence" nil
)
2926 (string :tag
"Specific state")))
2928 (defcustom org-log-repeat
'time
2929 "Non-nil means record moving through the DONE state when triggering repeat.
2930 An auto-repeating task is immediately switched back to TODO when
2931 marked DONE. If you are not logging state changes (by adding \"@\"
2932 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2933 record a closing note, there will be no record of the task moving
2934 through DONE. This variable forces taking a note anyway.
2936 nil Don't force a record
2937 time Record a time stamp
2938 note Prompt for a note and add it with template `org-log-note-headings'
2940 This option can also be set with on a per-file-basis with
2942 #+STARTUP: nologrepeat
2943 #+STARTUP: logrepeat
2944 #+STARTUP: lognoterepeat
2946 You can have local logging settings for a subtree by setting the LOGGING
2947 property to one or more of these keywords."
2949 :group
'org-progress
2951 (const :tag
"Don't force a record" nil
)
2952 (const :tag
"Force recording the DONE state" time
)
2953 (const :tag
"Force recording a note with the DONE state" note
)))
2956 (defgroup org-priorities nil
2957 "Priorities in Org-mode."
2958 :tag
"Org Priorities"
2961 (defcustom org-enable-priority-commands t
2962 "Non-nil means priority commands are active.
2963 When nil, these commands will be disabled, so that you never accidentally
2965 :group
'org-priorities
2968 (defcustom org-highest-priority ?A
2969 "The highest priority of TODO items. A character like ?A, ?B etc.
2970 Must have a smaller ASCII number than `org-lowest-priority'."
2971 :group
'org-priorities
2974 (defcustom org-lowest-priority ?C
2975 "The lowest priority of TODO items. A character like ?A, ?B etc.
2976 Must have a larger ASCII number than `org-highest-priority'."
2977 :group
'org-priorities
2980 (defcustom org-default-priority ?B
2981 "The default priority of TODO items.
2982 This is the priority an item gets if no explicit priority is given.
2983 When starting to cycle on an empty priority the first step in the cycle
2984 depends on `org-priority-start-cycle-with-default'. The resulting first
2985 step priority must not exceed the range from `org-highest-priority' to
2986 `org-lowest-priority' which means that `org-default-priority' has to be
2987 in this range exclusive or inclusive the range boundaries. Else the
2988 first step refuses to set the default and the second will fall back
2989 to (depending on the command used) the highest or lowest priority."
2990 :group
'org-priorities
2993 (defcustom org-priority-start-cycle-with-default t
2994 "Non-nil means start with default priority when starting to cycle.
2995 When this is nil, the first step in the cycle will be (depending on the
2996 command used) one higher or lower than the default priority.
2997 See also `org-default-priority'."
2998 :group
'org-priorities
3001 (defcustom org-get-priority-function nil
3002 "Function to extract the priority from a string.
3003 The string is normally the headline. If this is nil Org computes the
3004 priority from the priority cookie like [#A] in the headline. It returns
3005 an integer, increasing by 1000 for each priority level.
3006 The user can set a different function here, which should take a string
3007 as an argument and return the numeric priority."
3008 :group
'org-priorities
3014 (defgroup org-time nil
3015 "Options concerning time stamps and deadlines in Org-mode."
3019 (defcustom org-insert-labeled-timestamps-at-point nil
3020 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
3021 When nil, these labeled time stamps are forces into the second line of an
3022 entry, just after the headline. When scheduling from the global TODO list,
3023 the time stamp will always be forced into the second line."
3027 (defcustom org-time-stamp-rounding-minutes
'(0 5)
3028 "Number of minutes to round time stamps to.
3029 These are two values, the first applies when first creating a time stamp.
3030 The second applies when changing it with the commands `S-up' and `S-down'.
3031 When changing the time stamp, this means that it will change in steps
3032 of N minutes, as given by the second value.
3034 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3035 numbers should be factors of 60, so for example 5, 10, 15.
3037 When this is larger than 1, you can still force an exact time stamp by using
3038 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3039 and by using a prefix arg to `S-up/down' to specify the exact number
3040 of minutes to shift."
3042 :get
(lambda (var) ; Make sure both elements are there
3043 (if (integerp (default-value var
))
3044 (list (default-value var
) 5)
3045 (default-value var
)))
3047 (integer :tag
"when inserting times")
3048 (integer :tag
"when modifying times")))
3050 ;; Normalize old customizations of this variable.
3051 (when (integerp org-time-stamp-rounding-minutes
)
3052 (setq org-time-stamp-rounding-minutes
3053 (list org-time-stamp-rounding-minutes
3054 org-time-stamp-rounding-minutes
)))
3056 (defcustom org-display-custom-times nil
3057 "Non-nil means overlay custom formats over all time stamps.
3058 The formats are defined through the variable `org-time-stamp-custom-formats'.
3059 To turn this on on a per-file basis, insert anywhere in the file:
3060 #+STARTUP: customtime"
3064 (make-variable-buffer-local 'org-display-custom-times
)
3066 (defcustom org-time-stamp-custom-formats
3067 '("<%m/%d/%y %a>" .
"<%m/%d/%y %a %H:%M>") ; american
3068 "Custom formats for time stamps. See `format-time-string' for the syntax.
3069 These are overlaid over the default ISO format if the variable
3070 `org-display-custom-times' is set. Time like %H:%M should be at the
3071 end of the second format. The custom formats are also honored by export
3072 commands, if custom time display is turned on at the time of export."
3076 (defun org-time-stamp-format (&optional long inactive
)
3077 "Get the right format for a time string."
3078 (let ((f (if long
(cdr org-time-stamp-formats
)
3079 (car org-time-stamp-formats
))))
3081 (concat "[" (substring f
1 -
1) "]")
3084 (defcustom org-time-clocksum-format
3085 '(:days
"%dd " :hours
"%d" :require-hours t
:minutes
":%02d" :require-minutes t
)
3086 "The format string used when creating CLOCKSUM lines.
3087 This is also used when Org mode generates a time duration.
3089 The value can be a single format string containing two
3090 %-sequences, which will be filled with the number of hours and
3091 minutes in that order.
3093 Alternatively, the value can be a plist associating any of the
3094 keys :years, :months, :weeks, :days, :hours or :minutes with
3095 format strings. The time duration is formatted using only the
3096 time components that are needed and concatenating the results.
3097 If a time unit in absent, it falls back to the next smallest
3100 The keys :require-years, :require-months, :require-days,
3101 :require-weeks, :require-hours, :require-minutes are also
3102 meaningful. A non-nil value for these keys indicates that the
3103 corresponding time component should always be included, even if
3109 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3112 means durations longer than a day will be expressed in days,
3113 hours and minutes, and durations less than a day will always be
3114 expressed in hours and minutes (even for durations less than an
3119 \(:days \"%dd\" :minutes \"%dm\")
3121 means durations longer than a day will be expressed in days and
3122 minutes, and durations less than a day will be expressed entirely
3123 in minutes (even for durations longer than an hour)."
3127 :package-version
'(Org .
"8.0")
3128 :type
'(choice (string :tag
"Format string")
3130 (group :inline t
(const :tag
"Years" :years
)
3131 (string :tag
"Format string"))
3133 (const :tag
"Always show years" :require-years
)
3135 (group :inline t
(const :tag
"Months" :months
)
3136 (string :tag
"Format string"))
3138 (const :tag
"Always show months" :require-months
)
3140 (group :inline t
(const :tag
"Weeks" :weeks
)
3141 (string :tag
"Format string"))
3143 (const :tag
"Always show weeks" :require-weeks
)
3145 (group :inline t
(const :tag
"Days" :days
)
3146 (string :tag
"Format string"))
3148 (const :tag
"Always show days" :require-days
)
3150 (group :inline t
(const :tag
"Hours" :hours
)
3151 (string :tag
"Format string"))
3153 (const :tag
"Always show hours" :require-hours
)
3155 (group :inline t
(const :tag
"Minutes" :minutes
)
3156 (string :tag
"Format string"))
3158 (const :tag
"Always show minutes" :require-minutes
)
3161 (defcustom org-time-clocksum-use-fractional nil
3162 "When non-nil, \\[org-clock-display] uses fractional times.
3163 See `org-time-clocksum-format' for more on time clock formats."
3169 (defcustom org-time-clocksum-use-effort-durations nil
3170 "When non-nil, \\[org-clock-display] uses effort durations.
3171 E.g. by default, one day is considered to be a 8 hours effort,
3172 so a task that has been clocked for 16 hours will be displayed
3173 as during 2 days in the clock display or in the clocktable.
3175 See `org-effort-durations' on how to set effort durations
3176 and `org-time-clocksum-format' for more on time clock formats."
3180 :package-version
'(Org .
"8.0")
3183 (defcustom org-time-clocksum-fractional-format
"%.2f"
3184 "The format string used when creating CLOCKSUM lines,
3185 or when Org mode generates a time duration, if
3186 `org-time-clocksum-use-fractional' is enabled.
3188 The value can be a single format string containing one
3189 %-sequence, which will be filled with the number of hours as
3192 Alternatively, the value can be a plist associating any of the
3193 keys :years, :months, :weeks, :days, :hours or :minutes with
3194 a format string. The time duration is formatted using the
3195 largest time unit which gives a non-zero integer part. If all
3196 specified formats have zero integer part, the smallest time unit
3199 :type
'(choice (string :tag
"Format string")
3200 (set (group :inline t
(const :tag
"Years" :years
)
3201 (string :tag
"Format string"))
3202 (group :inline t
(const :tag
"Months" :months
)
3203 (string :tag
"Format string"))
3204 (group :inline t
(const :tag
"Weeks" :weeks
)
3205 (string :tag
"Format string"))
3206 (group :inline t
(const :tag
"Days" :days
)
3207 (string :tag
"Format string"))
3208 (group :inline t
(const :tag
"Hours" :hours
)
3209 (string :tag
"Format string"))
3210 (group :inline t
(const :tag
"Minutes" :minutes
)
3211 (string :tag
"Format string")))))
3213 (defcustom org-deadline-warning-days
14
3214 "Number of days before expiration during which a deadline becomes active.
3215 This variable governs the display in sparse trees and in the agenda.
3216 When 0 or negative, it means use this number (the absolute value of it)
3217 even if a deadline has a different individual lead time specified.
3219 Custom commands can set this variable in the options section."
3221 :group
'org-agenda-daily
/weekly
3224 (defcustom org-scheduled-delay-days
0
3225 "Number of days before a scheduled item becomes active.
3226 This variable governs the display in sparse trees and in the agenda.
3227 The default value (i.e. 0) means: don't delay scheduled item.
3228 When negative, it means use this number (the absolute value of it)
3229 even if a scheduled item has a different individual delay time
3232 Custom commands can set this variable in the options section."
3234 :group
'org-agenda-daily
/weekly
3236 :package-version
'(Org .
"8.0")
3239 (defcustom org-read-date-prefer-future t
3240 "Non-nil means assume future for incomplete date input from user.
3241 This affects the following situations:
3242 1. The user gives a month but not a year.
3243 For example, if it is April and you enter \"feb 2\", this will be read
3244 as Feb 2, *next* year. \"May 5\", however, will be this year.
3245 2. The user gives a day, but no month.
3246 For example, if today is the 15th, and you enter \"3\", Org-mode will
3247 read this as the third of *next* month. However, if you enter \"17\",
3248 it will be considered as *this* month.
3250 If you set this variable to the symbol `time', then also the following
3253 3. If the user gives a time.
3254 If the time is before now, it will be interpreted as tomorrow.
3256 Currently none of this works for ISO week specifications.
3258 When this option is nil, the current day, month and year will always be
3261 See also `org-agenda-jump-prefer-future'."
3264 (const :tag
"Never" nil
)
3265 (const :tag
"Check month and day" t
)
3266 (const :tag
"Check month, day, and time" time
)))
3268 (defcustom org-agenda-jump-prefer-future
'org-read-date-prefer-future
3269 "Should the agenda jump command prefer the future for incomplete dates?
3270 The default is to do the same as configured in `org-read-date-prefer-future'.
3271 But you can also set a deviating value here.
3272 This may t or nil, or the symbol `org-read-date-prefer-future'."
3277 (const :tag
"Use org-read-date-prefer-future"
3278 org-read-date-prefer-future
)
3279 (const :tag
"Never" nil
)
3280 (const :tag
"Always" t
)))
3282 (defcustom org-read-date-force-compatible-dates t
3283 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3285 Depending on the system Emacs is running on, certain dates cannot
3286 be represented with the type used internally to represent time.
3287 Dates between 1970-1-1 and 2038-1-1 can always be represented
3288 correctly. Some systems allow for earlier dates, some for later,
3289 some for both. One way to find out it to insert any date into an
3290 Org buffer, putting the cursor on the year and hitting S-up and
3291 S-down to test the range.
3293 When this variable is set to t, the date/time prompt will not let
3294 you specify dates outside the 1970-2037 range, so it is certain that
3295 these dates will work in whatever version of Emacs you are
3296 running, and also that you can move a file from one Emacs implementation
3297 to another. WHenever Org is forcing the year for you, it will display
3300 When this variable is nil, Org will check if the date is
3301 representable in the specific Emacs implementation you are using.
3302 If not, it will force a year, usually the current year, and beep
3303 to remind you. Currently this setting is not recommended because
3304 the likelihood that you will open your Org files in an Emacs that
3305 has limited date range is not negligible.
3307 A workaround for this problem is to use diary sexp dates for time
3308 stamps outside of this range."
3313 (defcustom org-read-date-display-live t
3314 "Non-nil means display current interpretation of date prompt live.
3315 This display will be in an overlay, in the minibuffer."
3319 (defcustom org-read-date-popup-calendar t
3320 "Non-nil means pop up a calendar when prompting for a date.
3321 In the calendar, the date can be selected with mouse-1. However, the
3322 minibuffer will also be active, and you can simply enter the date as well.
3323 When nil, only the minibuffer will be available."
3326 (org-defvaralias 'org-popup-calendar-for-date-prompt
3327 'org-read-date-popup-calendar
)
3329 (make-obsolete-variable
3330 'org-read-date-minibuffer-setup-hook
3331 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3332 (defcustom org-read-date-minibuffer-setup-hook nil
3333 "Hook to be used to set up keys for the date/time interface.
3334 Add key definitions to `minibuffer-local-map', which will be a
3337 WARNING: This option is obsolete, you should use
3338 `org-read-date-minibuffer-local-map' to set up keys."
3342 (defcustom org-extend-today-until
0
3343 "The hour when your day really ends. Must be an integer.
3344 This has influence for the following applications:
3345 - When switching the agenda to \"today\". It it is still earlier than
3346 the time given here, the day recognized as TODAY is actually yesterday.
3347 - When a date is read from the user and it is still before the time given
3348 here, the current date and time will be assumed to be yesterday, 23:59.
3349 Also, timestamps inserted in capture templates follow this rule.
3351 IMPORTANT: This is a feature whose implementation is and likely will
3352 remain incomplete. Really, it is only here because past midnight seems to
3353 be the favorite working time of John Wiegley :-)"
3357 (defcustom org-use-effective-time nil
3358 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3359 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3360 \"effective time\" of any timestamps between midnight and 8am will be
3361 23:59 of the previous day."
3366 (defcustom org-use-last-clock-out-time-as-effective-time nil
3367 "When non-nil, use the last clock out time for `org-todo'.
3368 Note that this option has precedence over the combined use of
3369 `org-use-effective-time' and `org-extend-today-until'."
3372 :package-version
'(Org .
"8.0")
3375 (defcustom org-edit-timestamp-down-means-later nil
3376 "Non-nil means S-down will increase the time in a time stamp.
3377 When nil, S-up will increase."
3381 (defcustom org-calendar-follow-timestamp-change t
3382 "Non-nil means make the calendar window follow timestamp changes.
3383 When a timestamp is modified and the calendar window is visible, it will be
3384 moved to the new date."
3388 (defgroup org-tags nil
3389 "Options concerning tags in Org-mode."
3393 (defcustom org-tag-alist nil
3394 "List of tags allowed in Org-mode files.
3395 When this list is nil, Org-mode will base TAG input on what is already in the
3397 The value of this variable is an alist, the car of each entry must be a
3398 keyword as a string, the cdr may be a character that is used to select
3399 that tag through the fast-tag-selection interface.
3400 See the manual for details."
3404 (cons (string :tag
"Tag name")
3405 (character :tag
"Access char"))
3406 (list :tag
"Start radio group"
3408 (option (string :tag
"Group description")))
3409 (list :tag
"Group tags delimiter"
3411 (list :tag
"End radio group"
3413 (option (string :tag
"Group description")))
3414 (const :tag
"New line" (:newline
)))))
3416 (defcustom org-tag-persistent-alist nil
3417 "List of tags that will always appear in all Org-mode files.
3418 This is in addition to any in buffer settings or customizations
3420 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3421 The value of this variable is an alist, the car of each entry must be a
3422 keyword as a string, the cdr may be a character that is used to select
3423 that tag through the fast-tag-selection interface.
3424 See the manual for details.
3425 To disable these tags on a per-file basis, insert anywhere in the file:
3430 (cons (string :tag
"Tag name")
3431 (character :tag
"Access char"))
3432 (const :tag
"Start radio group" (:startgroup
))
3433 (const :tag
"Group tags delimiter" (:grouptags
))
3434 (const :tag
"End radio group" (:endgroup
))
3435 (const :tag
"New line" (:newline
)))))
3437 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3438 "If non-nil, always offer completion for all tags of all agenda files.
3439 Instead of customizing this variable directly, you might want to
3440 set it locally for capture buffers, because there no list of
3441 tags in that file can be created dynamically (there are none).
3443 (add-hook 'org-capture-mode-hook
3445 (set (make-local-variable
3446 'org-complete-tags-always-offer-all-agenda-tags)
3452 (defvar org-file-tags nil
3453 "List of tags that can be inherited by all entries in the file.
3454 The tags will be inherited if the variable `org-use-tag-inheritance'
3455 says they should be.
3456 This variable is populated from #+FILETAGS lines.")
3458 (defcustom org-use-fast-tag-selection
'auto
3459 "Non-nil means use fast tag selection scheme.
3460 This is a special interface to select and deselect tags with single keys.
3461 When nil, fast selection is never used.
3462 When the symbol `auto', fast selection is used if and only if selection
3463 characters for tags have been configured, either through the variable
3464 `org-tag-alist' or through a #+TAGS line in the buffer.
3465 When t, fast selection is always used and selection keys are assigned
3466 automatically if necessary."
3469 (const :tag
"Always" t
)
3470 (const :tag
"Never" nil
)
3471 (const :tag
"When selection characters are configured" auto
)))
3473 (defcustom org-fast-tag-selection-single-key nil
3474 "Non-nil means fast tag selection exits after first change.
3475 When nil, you have to press RET to exit it.
3476 During fast tag selection, you can toggle this flag with `C-c'.
3477 This variable can also have the value `expert'. In this case, the window
3478 displaying the tags menu is not even shown, until you press C-c again."
3481 (const :tag
"No" nil
)
3482 (const :tag
"Yes" t
)
3483 (const :tag
"Expert" expert
)))
3485 (defvar org-fast-tag-selection-include-todo nil
3486 "Non-nil means fast tags selection interface will also offer TODO states.
3487 This is an undocumented feature, you should not rely on it.")
3489 (defcustom org-tags-column
(if (featurep 'xemacs
) -
76 -
77)
3490 "The column to which tags should be indented in a headline.
3491 If this number is positive, it specifies the column. If it is negative,
3492 it means that the tags should be flushright to that column. For example,
3493 -80 works well for a normal 80 character screen.
3494 When 0, place tags directly after headline text, with only one space in
3499 (defcustom org-auto-align-tags t
3500 "Non-nil keeps tags aligned when modifying headlines.
3501 Some operations (i.e. demoting) change the length of a headline and
3502 therefore shift the tags around. With this option turned on, after
3503 each such operation the tags are again aligned to `org-tags-column'."
3507 (defcustom org-use-tag-inheritance t
3508 "Non-nil means tags in levels apply also for sublevels.
3509 When nil, only the tags directly given in a specific line apply there.
3510 This may also be a list of tags that should be inherited, or a regexp that
3511 matches tags that should be inherited. Additional control is possible
3512 with the variable `org-tags-exclude-from-inheritance' which gives an
3513 explicit list of tags to be excluded from inheritance, even if the value of
3514 `org-use-tag-inheritance' would select it for inheritance.
3516 If this option is t, a match early-on in a tree can lead to a large
3517 number of matches in the subtree when constructing the agenda or creating
3518 a sparse tree. If you only want to see the first match in a tree during
3519 a search, check out the variable `org-tags-match-list-sublevels'."
3522 (const :tag
"Not" nil
)
3523 (const :tag
"Always" t
)
3524 (repeat :tag
"Specific tags" (string :tag
"Tag"))
3525 (regexp :tag
"Tags matched by regexp")))
3527 (defcustom org-tags-exclude-from-inheritance nil
3528 "List of tags that should never be inherited.
3529 This is a way to exclude a few tags from inheritance. For way to do
3530 the opposite, to actively allow inheritance for selected tags,
3531 see the variable `org-use-tag-inheritance'."
3533 :type
'(repeat (string :tag
"Tag")))
3535 (defun org-tag-inherit-p (tag)
3536 "Check if TAG is one that should be inherited."
3538 ((member tag org-tags-exclude-from-inheritance
) nil
)
3539 ((eq org-use-tag-inheritance t
) t
)
3540 ((not org-use-tag-inheritance
) nil
)
3541 ((stringp org-use-tag-inheritance
)
3542 (string-match org-use-tag-inheritance tag
))
3543 ((listp org-use-tag-inheritance
)
3544 (member tag org-use-tag-inheritance
))
3545 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3547 (defcustom org-tags-match-list-sublevels t
3548 "Non-nil means list also sublevels of headlines matching a search.
3549 This variable applies to tags/property searches, and also to stuck
3550 projects because this search is based on a tags match as well.
3552 When set to the symbol `indented', sublevels are indented with
3555 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3556 the sublevels of a headline matching a tag search often also match
3557 the same search. Listing all of them can create very long lists.
3558 Setting this variable to nil causes subtrees of a match to be skipped.
3560 This variable is semi-obsolete and probably should always be true. It
3561 is better to limit inheritance to certain tags using the variables
3562 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3565 (const :tag
"No, don't list them" nil
)
3566 (const :tag
"Yes, do list them" t
)
3567 (const :tag
"List them, indented with leading dots" indented
)))
3569 (defcustom org-tags-sort-function nil
3570 "When set, tags are sorted using this function as a comparator."
3573 (const :tag
"No sorting" nil
)
3574 (const :tag
"Alphabetical" string
<)
3575 (const :tag
"Reverse alphabetical" string
>)
3576 (function :tag
"Custom function" nil
)))
3578 (defvar org-tags-history nil
3579 "History of minibuffer reads for tags.")
3580 (defvar org-last-tags-completion-table nil
3581 "The last used completion table for tags.")
3582 (defvar org-after-tags-change-hook nil
3583 "Hook that is run after the tags in a line have changed.")
3585 (defgroup org-properties nil
3586 "Options concerning properties in Org-mode."
3587 :tag
"Org Properties"
3590 (defcustom org-property-format
"%-10s %s"
3591 "How property key/value pairs should be formatted by `indent-line'.
3592 When `indent-line' hits a property definition, it will format the line
3593 according to this format, mainly to make sure that the values are
3594 lined-up with respect to each other."
3595 :group
'org-properties
3598 (defcustom org-properties-postprocess-alist nil
3599 "Alist of properties and functions to adjust inserted values.
3600 Elements of this alist must be of the form
3602 ([string] [function])
3604 where [string] must be a property name and [function] must be a
3605 lambda expression: this lambda expression must take one argument,
3606 the value to adjust, and return the new value as a string.
3608 For example, this element will allow the property \"Remaining\"
3609 to be updated wrt the relation between the \"Effort\" property
3610 and the clock summary:
3612 ((\"Remaining\" (lambda(value)
3613 (let ((clocksum (org-clock-sum-current-item))
3614 (effort (org-duration-string-to-minutes
3615 (org-entry-get (point) \"Effort\"))))
3616 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3617 :group
'org-properties
3619 :type
'(alist :key-type
(string :tag
"Property")
3620 :value-type
(function :tag
"Function")))
3622 (defcustom org-use-property-inheritance nil
3623 "Non-nil means properties apply also for sublevels.
3625 This setting is chiefly used during property searches. Turning it on can
3626 cause significant overhead when doing a search, which is why it is not
3629 When nil, only the properties directly given in the current entry count.
3630 When t, every property is inherited. The value may also be a list of
3631 properties that should have inheritance, or a regular expression matching
3632 properties that should be inherited.
3634 However, note that some special properties use inheritance under special
3635 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3636 and the properties ending in \"_ALL\" when they are used as descriptor
3637 for valid values of a property.
3639 Note for programmers:
3640 When querying an entry with `org-entry-get', you can control if inheritance
3641 should be used. By default, `org-entry-get' looks only at the local
3642 properties. You can request inheritance by setting the inherit argument
3643 to t (to force inheritance) or to `selective' (to respect the setting
3645 :group
'org-properties
3647 (const :tag
"Not" nil
)
3648 (const :tag
"Always" t
)
3649 (repeat :tag
"Specific properties" (string :tag
"Property"))
3650 (regexp :tag
"Properties matched by regexp")))
3652 (defun org-property-inherit-p (property)
3653 "Check if PROPERTY is one that should be inherited."
3655 ((eq org-use-property-inheritance t
) t
)
3656 ((not org-use-property-inheritance
) nil
)
3657 ((stringp org-use-property-inheritance
)
3658 (string-match org-use-property-inheritance property
))
3659 ((listp org-use-property-inheritance
)
3660 (member property org-use-property-inheritance
))
3661 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3663 (defcustom org-columns-default-format
"%25ITEM %TODO %3PRIORITY %TAGS"
3664 "The default column format, if no other format has been defined.
3665 This variable can be set on the per-file basis by inserting a line
3667 #+COLUMNS: %25ITEM ....."
3668 :group
'org-properties
3671 (defcustom org-columns-ellipses
".."
3672 "The ellipses to be used when a field in column view is truncated.
3673 When this is the empty string, as many characters as possible are shown,
3674 but then there will be no visual indication that the field has been truncated.
3675 When this is a string of length N, the last N characters of a truncated
3676 field are replaced by this string. If the column is narrower than the
3677 ellipses string, only part of the ellipses string will be shown."
3678 :group
'org-properties
3681 (defcustom org-columns-modify-value-for-display-function nil
3682 "Function that modifies values for display in column view.
3683 For example, it can be used to cut out a certain part from a time stamp.
3684 The function must take 2 arguments:
3686 column-title The title of the column (*not* the property name)
3687 value The value that should be modified.
3689 The function should return the value that should be displayed,
3690 or nil if the normal value should be used."
3691 :group
'org-properties
3692 :type
'(choice (const nil
) (function)))
3694 (defconst org-global-properties-fixed
3695 '(("VISIBILITY_ALL" .
"folded children content all")
3696 ("CLOCK_MODELINE_TOTAL_ALL" .
"current today repeat all auto"))
3697 "List of property/value pairs that can be inherited by any entry.
3699 These are fixed values, for the preset properties. The user variable
3700 that can be used to add to this list is `org-global-properties'.
3702 The entries in this list are cons cells where the car is a property
3703 name and cdr is a string with the value. If the value represents
3704 multiple items like an \"_ALL\" property, separate the items by
3707 (defcustom org-global-properties nil
3708 "List of property/value pairs that can be inherited by any entry.
3710 This list will be combined with the constant `org-global-properties-fixed'.
3712 The entries in this list are cons cells where the car is a property
3713 name and cdr is a string with the value.
3715 You can set buffer-local values for the same purpose in the variable
3716 `org-file-properties' this by adding lines like
3718 #+PROPERTY: NAME VALUE"
3719 :group
'org-properties
3721 (cons (string :tag
"Property")
3722 (string :tag
"Value"))))
3724 (defvar org-file-properties nil
3725 "List of property/value pairs that can be inherited by any entry.
3726 Valid for the current buffer.
3727 This variable is populated from #+PROPERTY lines.")
3728 (make-variable-buffer-local 'org-file-properties
)
3730 (defgroup org-agenda nil
3731 "Options concerning agenda views in Org-mode."
3735 (defvar org-category nil
3736 "Variable used by org files to set a category for agenda display.
3737 Such files should use a file variable to set it, for example
3739 # -*- mode: org; org-category: \"ELisp\"
3741 or contain a special line
3745 If the file does not specify a category, then file's base name
3747 (make-variable-buffer-local 'org-category
)
3748 (put 'org-category
'safe-local-variable
(lambda (x) (or (symbolp x
) (stringp x
))))
3750 (defcustom org-agenda-files nil
3751 "The files to be used for agenda display.
3752 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3753 \\[org-remove-file]. You can also use customize to edit the list.
3755 If an entry is a directory, all files in that directory that are matched by
3756 `org-agenda-file-regexp' will be part of the file list.
3758 If the value of the variable is not a list but a single file name, then
3759 the list of agenda files is actually stored and maintained in that file, one
3760 agenda file per line. In this file paths can be given relative to
3761 `org-directory'. Tilde expansion and environment variable substitution
3765 (repeat :tag
"List of files and directories" file
)
3766 (file :tag
"Store list in a file\n" :value
"~/.agenda_files")))
3768 (defcustom org-agenda-file-regexp
"\\`[^.].*\\.org\\'"
3769 "Regular expression to match files for `org-agenda-files'.
3770 If any element in the list in that variable contains a directory instead
3771 of a normal file, all files in that directory that are matched by this
3772 regular expression will be included."
3776 (defcustom org-agenda-text-search-extra-files nil
3777 "List of extra files to be searched by text search commands.
3778 These files will be searched in addition to the agenda files by the
3779 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3780 Note that these files will only be searched for text search commands,
3781 not for the other agenda views like todo lists, tag searches or the weekly
3782 agenda. This variable is intended to list notes and possibly archive files
3783 that should also be searched by these two commands.
3784 In fact, if the first element in the list is the symbol `agenda-archives',
3785 then all archive files of all agenda files will be added to the search
3788 :type
'(set :greedy t
3789 (const :tag
"Agenda Archives" agenda-archives
)
3790 (repeat :inline t
(file))))
3792 (org-defvaralias 'org-agenda-multi-occur-extra-files
3793 'org-agenda-text-search-extra-files
)
3795 (defcustom org-agenda-skip-unavailable-files nil
3796 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3797 A nil value means to remove them, after a query, from the list."
3801 (defcustom org-calendar-to-agenda-key
[?c
]
3802 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3803 The command `org-calendar-goto-agenda' will be bound to this key. The
3804 default is the character `c' because then `c' can be used to switch back and
3805 forth between agenda and calendar."
3809 (defcustom org-calendar-insert-diary-entry-key
[?i
]
3810 "The key to be installed in `calendar-mode-map' for adding diary entries.
3811 This option is irrelevant until `org-agenda-diary-file' has been configured
3812 to point to an Org-mode file. When that is the case, the command
3813 `org-agenda-diary-entry' will be bound to the key given here, by default
3814 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3815 if you want to continue doing this, you need to change this to a different
3820 (defcustom org-agenda-diary-file
'diary-file
3821 "File to which to add new entries with the `i' key in agenda and calendar.
3822 When this is the symbol `diary-file', the functionality in the Emacs
3823 calendar will be used to add entries to the `diary-file'. But when this
3824 points to a file, `org-agenda-diary-entry' will be used instead."
3827 (const :tag
"The standard Emacs diary file" diary-file
)
3828 (file :tag
"Special Org file diary entries")))
3830 (eval-after-load "calendar"
3832 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3833 'org-calendar-goto-agenda
)
3834 (add-hook 'calendar-mode-hook
3836 (unless (eq org-agenda-diary-file
'diary-file
)
3837 (define-key calendar-mode-map
3838 org-calendar-insert-diary-entry-key
3839 'org-agenda-diary-entry
))))))
3841 (defgroup org-latex nil
3842 "Options for embedding LaTeX code into Org-mode."
3846 (defcustom org-format-latex-options
3847 '(:foreground default
:background default
:scale
1.0
3848 :html-foreground
"Black" :html-background
"Transparent"
3849 :html-scale
1.0 :matchers
("begin" "$1" "$" "$$" "\\(" "\\["))
3850 "Options for creating images from LaTeX fragments.
3851 This is a property list with the following properties:
3852 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3853 `default' means use the foreground of the default face.
3854 `auto' means use the foreground from the text face.
3855 :background the background color, or \"Transparent\".
3856 `default' means use the background of the default face.
3857 `auto' means use the background from the text face.
3858 :scale a scaling factor for the size of the images, to get more pixels
3859 :html-foreground, :html-background, :html-scale
3860 the same numbers for HTML export.
3861 :matchers a list indicating which matchers should be used to
3862 find LaTeX fragments. Valid members of this list are:
3863 \"begin\" find environments
3864 \"$1\" find single characters surrounded by $.$
3865 \"$\" find math expressions surrounded by $...$
3866 \"$$\" find math expressions surrounded by $$....$$
3867 \"\\(\" find math expressions surrounded by \\(...\\)
3868 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3872 (defcustom org-format-latex-signal-error t
3873 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3874 When nil, just push out a message."
3879 (defcustom org-latex-to-mathml-jar-file nil
3880 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3881 Use this to specify additional executable file say a jar file.
3883 When using MathToWeb as the converter, specify the full-path to
3884 your mathtoweb.jar file."
3888 (const :tag
"None" nil
)
3889 (file :tag
"JAR file" :must-match t
)))
3891 (defcustom org-latex-to-mathml-convert-command nil
3892 "Command to convert LaTeX fragments to MathML.
3893 Replace format-specifiers in the command as noted below and use
3894 `shell-command' to convert LaTeX to MathML.
3895 %j: Executable file in fully expanded form as specified by
3896 `org-latex-to-mathml-jar-file'.
3897 %I: Input LaTeX file in fully expanded form
3898 %o: Output MathML file
3899 This command is used by `org-create-math-formula'.
3901 When using MathToWeb as the converter, set this to
3902 \"java -jar %j -unicode -force -df %o %I\"."
3906 (const :tag
"None" nil
)
3907 (string :tag
"\nShell command")))
3909 (defcustom org-latex-create-formula-image-program
'dvipng
3910 "Program to convert LaTeX fragments with.
3912 dvipng Process the LaTeX fragments to dvi file, then convert
3913 dvi files to png files using dvipng.
3914 This will also include processing of non-math environments.
3915 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3916 to convert pdf files to png files"
3920 (const :tag
"dvipng" dvipng
)
3921 (const :tag
"imagemagick" imagemagick
)))
3923 (defcustom org-latex-preview-ltxpng-directory
"ltxpng/"
3924 "Path to store latex preview images.
3925 A relative path here creates many directories relative to the
3926 processed org files paths. An absolute path puts all preview
3927 images at the same place."
3932 (defun org-format-latex-mathml-available-p ()
3933 "Return t if `org-latex-to-mathml-convert-command' is usable."
3935 (when (and (boundp 'org-latex-to-mathml-convert-command
)
3936 org-latex-to-mathml-convert-command
)
3937 (let ((executable (car (split-string
3938 org-latex-to-mathml-convert-command
))))
3939 (when (executable-find executable
)
3941 "%j" org-latex-to-mathml-convert-command
)
3942 (file-readable-p org-latex-to-mathml-jar-file
)
3945 (defcustom org-format-latex-header
"\\documentclass{article}
3946 \\usepackage[usenames]{color}
3949 \\pagestyle{empty} % do not remove
3950 % The settings below are copied from fullpage.sty
3951 \\setlength{\\textwidth}{\\paperwidth}
3952 \\addtolength{\\textwidth}{-3cm}
3953 \\setlength{\\oddsidemargin}{1.5cm}
3954 \\addtolength{\\oddsidemargin}{-2.54cm}
3955 \\setlength{\\evensidemargin}{\\oddsidemargin}
3956 \\setlength{\\textheight}{\\paperheight}
3957 \\addtolength{\\textheight}{-\\headheight}
3958 \\addtolength{\\textheight}{-\\headsep}
3959 \\addtolength{\\textheight}{-\\footskip}
3960 \\addtolength{\\textheight}{-3cm}
3961 \\setlength{\\topmargin}{1.5cm}
3962 \\addtolength{\\topmargin}{-2.54cm}"
3963 "The document header used for processing LaTeX fragments.
3964 It is imperative that this header make sure that no page number
3965 appears on the page. The package defined in the variables
3966 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3967 will either replace the placeholder \"[PACKAGES]\" in this
3968 header, or they will be appended."
3972 (defun org-set-packages-alist (var val
)
3973 "Set the packages alist and make sure it has 3 elements per entry."
3974 (set var
(mapcar (lambda (x)
3975 (if (and (consp x
) (= (length x
) 2))
3976 (list (car x
) (nth 1 x
) t
)
3980 (defun org-get-packages-alist (var)
3981 "Get the packages alist and make sure it has 3 elements per entry."
3983 (if (and (consp x
) (= (length x
) 2))
3984 (list (car x
) (nth 1 x
) t
)
3986 (default-value var
)))
3988 (defcustom org-latex-default-packages-alist
3989 '(("AUTO" "inputenc" t
)
3993 ("" "longtable" nil
)
3997 ("normalem" "ulem" t
)
4005 "Alist of default packages to be inserted in the header.
4007 Change this only if one of the packages here causes an
4008 incompatibility with another package you are using.
4010 The packages in this list are needed by one part or another of
4011 Org mode to function properly:
4013 - inputenc, fontenc: for basic font and character selection
4014 - fixltx2e: Important patches of LaTeX itself
4015 - graphicx: for including images
4016 - longtable: For multipage tables
4017 - float, wrapfig: for figure placement
4018 - rotating: for sideways figures and tables
4019 - ulem: for underline and strike-through
4020 - amsmath: for subscript and superscript and math environments
4021 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4022 for interpreting the entities in `org-entities'. You can skip
4023 some of these packages if you don't use any of their symbols.
4024 - hyperref: for cross references
4026 Therefore you should not modify this variable unless you know
4027 what you are doing. The one reason to change it anyway is that
4028 you might be loading some other package that conflicts with one
4029 of the default packages. Each element is either a cell or
4032 A cell is of the format:
4034 \( \"options\" \"package\" SNIPPET-FLAG).
4036 If SNIPPET-FLAG is non-nil, the package also needs to be included
4037 when compiling LaTeX snippets into images for inclusion into
4040 A string will be inserted as-is in the header of the document."
4042 :group
'org-export-latex
4043 :set
'org-set-packages-alist
4044 :get
'org-get-packages-alist
4048 (list :tag
"options/package pair"
4049 (string :tag
"options")
4050 (string :tag
"package")
4051 (boolean :tag
"Snippet"))
4052 (string :tag
"A line of LaTeX"))))
4054 (defcustom org-latex-packages-alist nil
4055 "Alist of packages to be inserted in every LaTeX header.
4057 These will be inserted after `org-latex-default-packages-alist'.
4058 Each element is either a cell or a string.
4060 A cell is of the format:
4062 \(\"options\" \"package\" SNIPPET-FLAG)
4064 SNIPPET-FLAG, when non-nil, indicates that this package is also
4065 needed when turning LaTeX snippets into images for inclusion into
4068 A string will be inserted as-is in the header of the document.
4070 Make sure that you only list packages here which:
4072 - you want in every file;
4073 - do not conflict with the setup in `org-format-latex-header';
4074 - do not conflict with the default packages in
4075 `org-latex-default-packages-alist'."
4077 :group
'org-export-latex
4078 :set
'org-set-packages-alist
4079 :get
'org-get-packages-alist
4082 (list :tag
"options/package pair"
4083 (string :tag
"options")
4084 (string :tag
"package")
4085 (boolean :tag
"Snippet"))
4086 (string :tag
"A line of LaTeX"))))
4088 (defgroup org-appearance nil
4089 "Settings for Org-mode appearance."
4090 :tag
"Org Appearance"
4093 (defcustom org-level-color-stars-only nil
4094 "Non-nil means fontify only the stars in each headline.
4095 When nil, the entire headline is fontified.
4096 Changing it requires restart of `font-lock-mode' to become effective
4097 also in regions already fontified."
4098 :group
'org-appearance
4101 (defcustom org-hide-leading-stars nil
4102 "Non-nil means hide the first N-1 stars in a headline.
4103 This works by using the face `org-hide' for these stars. This
4104 face is white for a light background, and black for a dark
4105 background. You may have to customize the face `org-hide' to
4107 Changing it requires restart of `font-lock-mode' to become effective
4108 also in regions already fontified.
4109 You may also set this on a per-file basis by adding one of the following
4110 lines to the buffer:
4112 #+STARTUP: hidestars
4113 #+STARTUP: showstars"
4114 :group
'org-appearance
4117 (defcustom org-hidden-keywords nil
4118 "List of symbols corresponding to keywords to be hidden the org buffer.
4119 For example, a value '(title) for this list will make the document's title
4120 appear in the buffer without the initial #+TITLE: keyword."
4121 :group
'org-appearance
4123 :type
'(set (const :tag
"#+AUTHOR" author
)
4124 (const :tag
"#+DATE" date
)
4125 (const :tag
"#+EMAIL" email
)
4126 (const :tag
"#+TITLE" title
)))
4128 (defcustom org-custom-properties nil
4129 "List of properties (as strings) with a special meaning.
4130 The default use of these custom properties is to let the user
4131 hide them with `org-toggle-custom-properties-visibility'."
4132 :group
'org-properties
4133 :group
'org-appearance
4135 :type
'(repeat (string :tag
"Property Name")))
4137 (defcustom org-fontify-done-headline nil
4138 "Non-nil means change the face of a headline if it is marked DONE.
4139 Normally, only the TODO/DONE keyword indicates the state of a headline.
4140 When this is non-nil, the headline after the keyword is set to the
4141 `org-headline-done' as an additional indication."
4142 :group
'org-appearance
4145 (defcustom org-fontify-emphasized-text t
4146 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4147 Changing this variable requires a restart of Emacs to take effect."
4148 :group
'org-appearance
4151 (defcustom org-fontify-whole-heading-line nil
4152 "Non-nil means fontify the whole line for headings.
4153 This is useful when setting a background color for the
4155 :group
'org-appearance
4158 (defcustom org-highlight-latex-and-related nil
4159 "Non-nil means highlight LaTeX related syntax in the buffer.
4160 When non nil, the value should be a list containing any of the
4162 `latex' Highlight LaTeX snippets and environments.
4163 `script' Highlight subscript and superscript.
4164 `entities' Highlight entities."
4165 :group
'org-appearance
4167 :package-version
'(Org .
"8.0")
4169 (const :tag
"No highlighting" nil
)
4170 (set :greedy t
:tag
"Highlight"
4171 (const :tag
"LaTeX snippets and environments" latex
)
4172 (const :tag
"Subscript and superscript" script
)
4173 (const :tag
"Entities" entities
))))
4175 (defcustom org-hide-emphasis-markers nil
4176 "Non-nil mean font-lock should hide the emphasis marker characters."
4177 :group
'org-appearance
4180 (defcustom org-hide-macro-markers nil
4181 "Non-nil mean font-lock should hide the brackets marking macro calls."
4182 :group
'org-appearance
4185 (defcustom org-pretty-entities nil
4186 "Non-nil means show entities as UTF8 characters.
4187 When nil, the \\name form remains in the buffer."
4188 :group
'org-appearance
4192 (defcustom org-pretty-entities-include-sub-superscripts t
4193 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4194 :group
'org-appearance
4198 (defvar org-emph-re nil
4199 "Regular expression for matching emphasis.
4200 After a match, the match groups contain these elements:
4201 0 The match of the full regular expression, including the characters
4202 before and after the proper match
4203 1 The character before the proper match, or empty at beginning of line
4204 2 The proper match, including the leading and trailing markers
4205 3 The leading marker like * or /, indicating the type of highlighting
4206 4 The text between the emphasis markers, not including the markers
4207 5 The character after the match, empty at the end of a line")
4208 (defvar org-verbatim-re nil
4209 "Regular expression for matching verbatim text.")
4210 (defvar org-emphasis-regexp-components
) ; defined just below
4211 (defvar org-emphasis-alist
) ; defined just below
4212 (defun org-set-emph-re (var val
)
4213 "Set variable and compute the emphasis regular expression."
4215 (when (and (boundp 'org-emphasis-alist
)
4216 (boundp 'org-emphasis-regexp-components
)
4217 org-emphasis-alist org-emphasis-regexp-components
)
4218 (let* ((e org-emphasis-regexp-components
)
4224 (body1 (concat body
"*?"))
4225 (markers (mapconcat 'car org-emphasis-alist
""))
4226 (vmarkers (mapconcat
4227 (lambda (x) (if (eq (nth 2 x
) 'verbatim
) (car x
) ""))
4228 org-emphasis-alist
"")))
4229 ;; make sure special characters appear at the right position in the class
4230 (if (string-match "\\^" markers
)
4231 (setq markers
(concat (replace-match "" t t markers
) "^")))
4232 (if (string-match "-" markers
)
4233 (setq markers
(concat (replace-match "" t t markers
) "-")))
4234 (if (string-match "\\^" vmarkers
)
4235 (setq vmarkers
(concat (replace-match "" t t vmarkers
) "^")))
4236 (if (string-match "-" vmarkers
)
4237 (setq vmarkers
(concat (replace-match "" t t vmarkers
) "-")))
4239 (setq body1
(concat body1
"\\(?:\n" body
"*?\\)\\{0,"
4240 (int-to-string nl
) "\\}")))
4243 (concat "\\([" pre
"]\\|^\\)"
4245 "\\([" markers
"]\\)"
4253 "\\([" post
"]\\|$\\)"))
4254 (setq org-verbatim-re
4255 (concat "\\([" pre
"]\\|^\\)"
4257 "\\([" vmarkers
"]\\)"
4265 "\\([" post
"]\\|$\\)")))))
4267 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4268 ;; set this option proved cumbersome. See this message/thread:
4269 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4270 (defvar org-emphasis-regexp-components
4271 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n,\"'" "." 1)
4272 "Components used to build the regular expression for emphasis.
4273 This is a list with five entries. Terminology: In an emphasis string
4274 like \" *strong word* \", we call the initial space PREMATCH, the final
4275 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4276 and \"trong wor\" is the body. The different components in this variable
4277 specify what is allowed/forbidden in each part:
4279 pre Chars allowed as prematch. Beginning of line will be allowed too.
4280 post Chars allowed as postmatch. End of line will be allowed too.
4281 border The chars *forbidden* as border characters.
4282 body-regexp A regexp like \".\" to match a body character. Don't use
4283 non-shy groups here, and don't allow newline here.
4284 newline The maximum number of newlines allowed in an emphasis exp.
4286 You need to reload Org or to restart Emacs after customizing this.")
4288 (defcustom org-emphasis-alist
4292 ("=" org-verbatim verbatim
)
4293 ("~" org-code verbatim
)
4294 ("+" ,(if (featurep 'xemacs
) 'org-table
'(:strike-through t
))))
4295 "Alist of characters and faces to emphasize text.
4296 Text starting and ending with a special character will be emphasized,
4297 for example *bold*, _underlined_ and /italic/. This variable sets the
4298 marker characters and the face to be used by font-lock for highlighting
4299 in Org-mode Emacs buffers.
4301 You need to reload Org or to restart Emacs after customizing this."
4302 :group
'org-appearance
4303 :set
'org-set-emph-re
4305 :package-version
'(Org .
"8.0")
4308 (string :tag
"Marker character")
4310 (face :tag
"Font-lock-face")
4311 (plist :tag
"Face property list"))
4312 (option (const verbatim
)))))
4314 (defvar org-protecting-blocks
4315 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4316 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4317 This is needed for font-lock setup.")
4319 ;;; Miscellaneous options
4321 (defgroup org-completion nil
4322 "Completion in Org-mode."
4323 :tag
"Org Completion"
4326 (defcustom org-completion-use-ido nil
4327 "Non-nil means use ido completion wherever possible.
4328 Note that `ido-mode' must be active for this variable to be relevant.
4329 If you decide to turn this variable on, you might well want to turn off
4330 `org-outline-path-complete-in-steps'.
4331 See also `org-completion-use-iswitchb'."
4332 :group
'org-completion
4335 (defcustom org-completion-use-iswitchb nil
4336 "Non-nil means use iswitchb completion wherever possible.
4337 Note that `iswitchb-mode' must be active for this variable to be relevant.
4338 If you decide to turn this variable on, you might well want to turn off
4339 `org-outline-path-complete-in-steps'.
4340 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4341 :group
'org-completion
4344 (defcustom org-completion-fallback-command
'hippie-expand
4345 "The expansion command called by \\[pcomplete] in normal context.
4346 Normal means, no org-mode-specific context."
4347 :group
'org-completion
4350 ;;; Functions and variables from their packages
4351 ;; Declared here to avoid compiler warnings
4354 (defvar outline-mode-menu-heading
)
4355 (defvar outline-mode-menu-show
)
4356 (defvar outline-mode-menu-hide
)
4357 (defvar zmacs-regions
) ; XEmacs regions
4360 (defvar mark-active
)
4363 (declare-function calendar-absolute-from-iso
"cal-iso" (date))
4364 (declare-function calendar-forward-day
"cal-move" (arg))
4365 (declare-function calendar-goto-date
"cal-move" (date))
4366 (declare-function calendar-goto-today
"cal-move" ())
4367 (declare-function calendar-iso-from-absolute
"cal-iso" (date))
4368 (defvar calc-embedded-close-formula
)
4369 (defvar calc-embedded-open-formula
)
4370 (declare-function cdlatex-tab
"ext:cdlatex" ())
4371 (declare-function cdlatex-compute-tables
"ext:cdlatex" ())
4372 (declare-function dired-get-filename
"dired" (&optional localp no-error-if-not-filep
))
4373 (defvar font-lock-unfontify-region-function
)
4374 (declare-function iswitchb-read-buffer
"iswitchb"
4375 (prompt &optional default require-match start matches-set
))
4376 (defvar iswitchb-temp-buflist
)
4377 (declare-function org-gnus-follow-link
"org-gnus" (&optional group article
))
4378 (defvar org-agenda-tags-todo-honor-ignore-options
)
4379 (declare-function org-agenda-skip
"org-agenda" ())
4381 org-agenda-format-item
"org-agenda"
4382 (extra txt
&optional level category tags dotime noprefix remove-re habitp
))
4383 (declare-function org-agenda-new-marker
"org-agenda" (&optional pos
))
4384 (declare-function org-agenda-change-all-lines
"org-agenda"
4385 (newhead hdmarker
&optional fixface just-this
))
4386 (declare-function org-agenda-set-restriction-lock
"org-agenda" (&optional type
))
4387 (declare-function org-agenda-maybe-redo
"org-agenda" ())
4388 (declare-function org-agenda-save-markers-for-cut-and-paste
"org-agenda"
4390 (declare-function org-agenda-copy-local-variable
"org-agenda" (var))
4391 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4392 "org-agenda" (&optional end
))
4393 (declare-function org-inlinetask-remove-END-maybe
"org-inlinetask" ())
4394 (declare-function org-inlinetask-in-task-p
"org-inlinetask" ())
4395 (declare-function org-inlinetask-goto-beginning
"org-inlinetask" ())
4396 (declare-function org-inlinetask-goto-end
"org-inlinetask" ())
4397 (declare-function org-indent-mode
"org-indent" (&optional arg
))
4398 (declare-function parse-time-string
"parse-time" (string))
4399 (declare-function org-attach-reveal
"org-attach" (&optional if-exists
))
4400 (declare-function orgtbl-send-table
"org-table" (&optional maybe
))
4401 (defvar remember-data-file
)
4402 (defvar texmathp-why
)
4403 (declare-function speedbar-line-directory
"speedbar" (&optional depth
))
4404 (declare-function table--at-cell-p
"table" (position &optional object at-column
))
4405 (declare-function calc-eval
"calc" (str &optional separator
&rest args
))
4408 (defun turn-on-orgtbl ()
4409 "Unconditionally turn on `orgtbl-mode'."
4410 (require 'org-table
)
4413 (defun org-at-table-p (&optional table-type
)
4414 "Return t if the cursor is inside an org-type table.
4415 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4416 (if org-enable-table-editor
4418 (beginning-of-line 1)
4419 (looking-at (if table-type org-table-any-line-regexp
4420 org-table-line-regexp
)))
4422 (defsubst org-table-p
() (org-at-table-p))
4424 (defun org-at-table.el-p
()
4425 "Return t if and only if we are at a table.el table."
4426 (and (org-at-table-p 'any
)
4428 (goto-char (org-table-begin 'any
))
4429 (looking-at org-table1-hline-regexp
))))
4431 (defun org-table-recognize-table.el
()
4432 "If there is a table.el table nearby, recognize it and move into it."
4433 (if org-table-tab-recognizes-table.el
4434 (if (org-at-table.el-p
)
4436 (beginning-of-line 1)
4437 (if (looking-at org-table-dataline-regexp
)
4439 (if (looking-at org-table1-hline-regexp
)
4441 (beginning-of-line 2)
4442 (if (looking-at org-table-any-border-regexp
)
4443 (beginning-of-line -
1)))))
4444 (if (re-search-forward "|" (org-table-end t
) t
)
4447 (if (table--at-cell-p (point))
4449 (message "recognizing table.el table...")
4450 (table-recognize-table)
4451 (message "recognizing table.el table...done")))
4452 (error "This should not happen"))
4457 (defun org-at-table-hline-p ()
4458 "Return t if the cursor is inside a hline in a table."
4459 (if org-enable-table-editor
4461 (beginning-of-line 1)
4462 (looking-at org-table-hline-regexp
))
4465 (defun org-table-map-tables (function &optional quietly
)
4466 "Apply FUNCTION to the start of all tables in the buffer."
4470 (goto-char (point-min))
4471 (while (re-search-forward org-table-any-line-regexp nil t
)
4473 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4474 (beginning-of-line 1)
4475 (when (and (looking-at org-table-line-regexp
)
4476 ;; Exclude tables in src/example/verbatim/clocktable blocks
4477 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4478 (save-excursion (funcall function
))
4479 (or (looking-at org-table-line-regexp
)
4481 (re-search-forward org-table-any-border-regexp nil
1))))
4482 (unless quietly
(message "Mapping tables: done")))
4484 (declare-function org-clock-save-markers-for-cut-and-paste
"org-clock" (beg end
))
4485 (declare-function org-clock-update-mode-line
"org-clock" ())
4486 (declare-function org-resolve-clocks
"org-clock"
4487 (&optional also-non-dangling-p prompt last-valid
))
4489 (defun org-at-TBLFM-p (&optional pos
)
4490 "Return t when point (or POS) is in #+TBLFM line."
4493 (goto-char (or pos
(point)))
4494 (beginning-of-line 1)
4495 (looking-at org-TBLFM-regexp
)))
4497 (defvar org-clock-start-time
)
4498 (defvar org-clock-marker
(make-marker)
4499 "Marker recording the last clock-in.")
4500 (defvar org-clock-hd-marker
(make-marker)
4501 "Marker recording the last clock-in, but the headline position.")
4502 (defvar org-clock-heading
""
4503 "The heading of the current clock entry.")
4504 (defun org-clock-is-active ()
4505 "Return the buffer where the clock is currently running.
4506 Return nil if no clock is running."
4507 (marker-buffer org-clock-marker
))
4509 (defun org-check-running-clock ()
4510 "Check if the current buffer contains the running clock.
4511 If yes, offer to stop it and to save the buffer with the changes."
4512 (when (and (equal (marker-buffer org-clock-marker
) (current-buffer))
4513 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4516 (when (y-or-n-p "Save changed buffer?")
4519 (defun org-clocktable-try-shift (dir n
)
4520 "Check if this line starts a clock table, if yes, shift the time block."
4521 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4522 (org-clocktable-shift dir n
)))
4525 (defun org-clock-persistence-insinuate ()
4526 "Set up hooks for clock persistence."
4527 (require 'org-clock
)
4528 (add-hook 'org-mode-hook
'org-clock-load
)
4529 (add-hook 'kill-emacs-hook
'org-clock-save
))
4531 (defgroup org-archive nil
4532 "Options concerning archiving in Org-mode."
4534 :group
'org-structure
)
4536 (defcustom org-archive-location
"%s_archive::"
4537 "The location where subtrees should be archived.
4539 The value of this variable is a string, consisting of two parts,
4540 separated by a double-colon. The first part is a filename and
4541 the second part is a headline.
4543 When the filename is omitted, archiving happens in the same file.
4544 %s in the filename will be replaced by the current file
4545 name (without the directory part). Archiving to a different file
4546 is useful to keep archived entries from contributing to the
4549 The archived entries will be filed as subtrees of the specified
4550 headline. When the headline is omitted, the subtrees are simply
4551 filed away at the end of the file, as top-level entries. Also in
4552 the heading you can use %s to represent the file name, this can be
4553 useful when using the same archive for a number of different files.
4555 Here are a few examples:
4557 If the current file is Projects.org, archive in file
4558 Projects.org_archive, as top-level trees. This is the default.
4560 \"::* Archived Tasks\"
4561 Archive in the current file, under the top-level headline
4562 \"* Archived Tasks\".
4564 \"~/org/archive.org::\"
4565 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4567 \"~/org/archive.org::* From %s\"
4568 Archive in file ~/org/archive.org (absolute path), under headlines
4569 \"From FILENAME\" where file name is the current file name.
4571 \"~/org/datetree.org::datetree/* Finished Tasks\"
4572 The \"datetree/\" string is special, signifying to archive
4573 items to the datetree. Items are placed in either the CLOSED
4574 date of the item, or the current date if there is no CLOSED date.
4575 The heading will be a subentry to the current date. There doesn't
4576 need to be a heading, but there always needs to be a slash after
4577 datetree. For example, to store archived items directly in the
4578 datetree, use \"~/org/datetree.org::datetree/\".
4580 \"basement::** Finished Tasks\"
4581 Archive in file ./basement (relative path), as level 3 trees
4582 below the level 2 heading \"** Finished Tasks\".
4584 You may set this option on a per-file basis by adding to the buffer a
4587 #+ARCHIVE: basement::** Finished Tasks
4589 You may also define it locally for a subtree by setting an ARCHIVE property
4590 in the entry. If such a property is found in an entry, or anywhere up
4591 the hierarchy, it will be used."
4595 (defcustom org-agenda-skip-archived-trees t
4596 "Non-nil means the agenda will skip any items located in archived trees.
4597 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4598 variable is no longer recommended, you should leave it at the value t.
4599 Instead, use the key `v' to cycle the archives-mode in the agenda."
4601 :group
'org-agenda-skip
4604 (defcustom org-columns-skip-archived-trees t
4605 "Non-nil means ignore archived trees when creating column view."
4607 :group
'org-properties
4610 (defcustom org-cycle-open-archived-trees nil
4611 "Non-nil means `org-cycle' will open archived trees.
4612 An archived tree is a tree marked with the tag ARCHIVE.
4613 When nil, archived trees will stay folded. You can still open them with
4614 normal outline commands like `show-all', but not with the cycling commands."
4619 (defcustom org-sparse-tree-open-archived-trees nil
4620 "Non-nil means sparse tree construction shows matches in archived trees.
4621 When nil, matches in these trees are highlighted, but the trees are kept in
4624 :group
'org-sparse-trees
4627 (defcustom org-sparse-tree-default-date-type
'scheduled-or-deadline
4628 "The default date type when building a sparse tree.
4629 When this is nil, a date is a scheduled or a deadline timestamp.
4630 Otherwise, these types are allowed:
4633 active: only active timestamps (<...>)
4634 inactive: only inactive timestamps (<...)
4635 scheduled: only scheduled timestamps
4636 deadline: only deadline timestamps"
4637 :type
'(choice (const :tag
"Scheduled or deadline" scheduled-or-deadline
)
4638 (const :tag
"All timestamps" all
)
4639 (const :tag
"Only active timestamps" active
)
4640 (const :tag
"Only inactive timestamps" inactive
)
4641 (const :tag
"Only scheduled timestamps" scheduled
)
4642 (const :tag
"Only deadline timestamps" deadline
)
4643 (const :tag
"Only closed timestamps" closed
))
4645 :group
'org-sparse-trees
)
4647 (defun org-cycle-hide-archived-subtrees (state)
4648 "Re-hide all archived subtrees after a visibility state change."
4649 (when (and (not org-cycle-open-archived-trees
)
4650 (not (memq state
'(overview folded
))))
4652 (let* ((globalp (memq state
'(contents all
)))
4653 (beg (if globalp
(point-min) (point)))
4654 (end (if globalp
(point-max) (org-end-of-subtree t
))))
4655 (org-hide-archived-subtrees beg end
)
4657 (if (looking-at (concat ".*:" org-archive-tag
":"))
4658 (message "%s" (substitute-command-keys
4659 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4661 (defun org-force-cycle-archived ()
4662 "Cycle subtree even if it is archived."
4664 (setq this-command
'org-cycle
)
4665 (let ((org-cycle-open-archived-trees t
))
4666 (call-interactively 'org-cycle
)))
4668 (defun org-hide-archived-subtrees (beg end
)
4669 "Re-hide all archived subtrees after a visibility state change."
4671 (let* ((re (concat ":" org-archive-tag
":")))
4673 (while (re-search-forward re end t
)
4674 (when (org-at-heading-p)
4675 (org-flag-subtree t
)
4676 (org-end-of-subtree t
))))))
4678 (declare-function outline-end-of-heading
"outline" ())
4679 (declare-function outline-flag-region
"outline" (from to flag
))
4680 (defun org-flag-subtree (flag)
4682 (org-back-to-heading t
)
4683 (outline-end-of-heading)
4684 (outline-flag-region (point)
4685 (progn (org-end-of-subtree t
) (point))
4688 (defalias 'org-advertized-archive-subtree
'org-archive-subtree
)
4690 ;; Declare Column View Code
4692 (declare-function org-columns-number-to-string
"org-colview" (n fmt
&optional printf
))
4693 (declare-function org-columns-get-format-and-top-level
"org-colview" ())
4694 (declare-function org-columns-compute
"org-colview" (property))
4698 (declare-function org-id-store-link
"org-id")
4699 (declare-function org-id-locations-load
"org-id")
4700 (declare-function org-id-locations-save
"org-id")
4701 (defvar org-id-track-globally
)
4703 ;;; Variables for pre-computed regular expressions, all buffer local
4705 (defvar org-todo-regexp nil
4706 "Matches any of the TODO state keywords.")
4707 (make-variable-buffer-local 'org-todo-regexp
)
4708 (defvar org-not-done-regexp nil
4709 "Matches any of the TODO state keywords except the last one.")
4710 (make-variable-buffer-local 'org-not-done-regexp
)
4711 (defvar org-not-done-heading-regexp nil
4712 "Matches a TODO headline that is not done.")
4713 (make-variable-buffer-local 'org-not-done-regexp
)
4714 (defvar org-todo-line-regexp nil
4715 "Matches a headline and puts TODO state into group 2 if present.")
4716 (make-variable-buffer-local 'org-todo-line-regexp
)
4717 (defvar org-complex-heading-regexp nil
4718 "Matches a headline and puts everything into groups:
4720 group 2: The todo keyword, maybe
4721 group 3: Priority cookie
4722 group 4: True headline
4724 (make-variable-buffer-local 'org-complex-heading-regexp
)
4725 (defvar org-complex-heading-regexp-format nil
4726 "Printf format to make regexp to match an exact headline.
4727 This regexp will match the headline of any node which has the
4728 exact headline text that is put into the format, but may have any
4729 TODO state, priority and tags.")
4730 (make-variable-buffer-local 'org-complex-heading-regexp-format
)
4731 (defvar org-todo-line-tags-regexp nil
4732 "Matches a headline and puts TODO state into group 2 if present.
4733 Also put tags into group 4 if tags are present.")
4734 (make-variable-buffer-local 'org-todo-line-tags-regexp
)
4735 (defvar org-ds-keyword-length
12
4736 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4737 (make-variable-buffer-local 'org-ds-keyword-length
)
4738 (defvar org-deadline-regexp nil
4739 "Matches the DEADLINE keyword.")
4740 (make-variable-buffer-local 'org-deadline-regexp
)
4741 (defvar org-deadline-time-regexp nil
4742 "Matches the DEADLINE keyword together with a time stamp.")
4743 (make-variable-buffer-local 'org-deadline-time-regexp
)
4744 (defvar org-deadline-time-hour-regexp nil
4745 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4746 (make-variable-buffer-local 'org-deadline-time-hour-regexp
)
4747 (defvar org-deadline-line-regexp nil
4748 "Matches the DEADLINE keyword and the rest of the line.")
4749 (make-variable-buffer-local 'org-deadline-line-regexp
)
4750 (defvar org-scheduled-regexp nil
4751 "Matches the SCHEDULED keyword.")
4752 (make-variable-buffer-local 'org-scheduled-regexp
)
4753 (defvar org-scheduled-time-regexp nil
4754 "Matches the SCHEDULED keyword together with a time stamp.")
4755 (make-variable-buffer-local 'org-scheduled-time-regexp
)
4756 (defvar org-scheduled-time-hour-regexp nil
4757 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4758 (make-variable-buffer-local 'org-scheduled-time-hour-regexp
)
4759 (defvar org-closed-time-regexp nil
4760 "Matches the CLOSED keyword together with a time stamp.")
4761 (make-variable-buffer-local 'org-closed-time-regexp
)
4763 (defvar org-keyword-time-regexp nil
4764 "Matches any of the 4 keywords, together with the time stamp.")
4765 (make-variable-buffer-local 'org-keyword-time-regexp
)
4766 (defvar org-keyword-time-not-clock-regexp nil
4767 "Matches any of the 3 keywords, together with the time stamp.")
4768 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp
)
4769 (defvar org-maybe-keyword-time-regexp nil
4770 "Matches a timestamp, possibly preceded by a keyword.")
4771 (make-variable-buffer-local 'org-maybe-keyword-time-regexp
)
4772 (defvar org-all-time-keywords nil
4773 "List of time keywords.")
4774 (make-variable-buffer-local 'org-all-time-keywords
)
4776 (defconst org-plain-time-of-day-regexp
4779 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4782 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4784 "Regular expression to match a plain time or time range.
4785 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4786 groups carry important information:
4788 1 the first time, range or not
4789 8 the second time, if it is a range.")
4791 (defconst org-plain-time-extension-regexp
4794 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4795 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4796 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4797 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4798 groups carry important information:
4801 9 minutes of duration")
4803 (defconst org-stamp-time-of-day-regexp
4805 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4806 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4808 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4809 "Regular expression to match a timestamp time or time range.
4810 After a match, the following groups carry important information:
4812 1 date plus weekday, for back referencing to make sure both times are on the same day
4813 2 the first time, range or not
4814 4 the second time, if it is a range.")
4816 (defconst org-startup-options
4817 '(("fold" org-startup-folded t
)
4818 ("overview" org-startup-folded t
)
4819 ("nofold" org-startup-folded nil
)
4820 ("showall" org-startup-folded nil
)
4821 ("showeverything" org-startup-folded showeverything
)
4822 ("content" org-startup-folded content
)
4823 ("indent" org-startup-indented t
)
4824 ("noindent" org-startup-indented nil
)
4825 ("hidestars" org-hide-leading-stars t
)
4826 ("showstars" org-hide-leading-stars nil
)
4827 ("odd" org-odd-levels-only t
)
4828 ("oddeven" org-odd-levels-only nil
)
4829 ("align" org-startup-align-all-tables t
)
4830 ("noalign" org-startup-align-all-tables nil
)
4831 ("inlineimages" org-startup-with-inline-images t
)
4832 ("noinlineimages" org-startup-with-inline-images nil
)
4833 ("latexpreview" org-startup-with-latex-preview t
)
4834 ("nolatexpreview" org-startup-with-latex-preview nil
)
4835 ("customtime" org-display-custom-times t
)
4836 ("logdone" org-log-done time
)
4837 ("lognotedone" org-log-done note
)
4838 ("nologdone" org-log-done nil
)
4839 ("lognoteclock-out" org-log-note-clock-out t
)
4840 ("nolognoteclock-out" org-log-note-clock-out nil
)
4841 ("logrepeat" org-log-repeat state
)
4842 ("lognoterepeat" org-log-repeat note
)
4843 ("logdrawer" org-log-into-drawer t
)
4844 ("nologdrawer" org-log-into-drawer nil
)
4845 ("logstatesreversed" org-log-states-order-reversed t
)
4846 ("nologstatesreversed" org-log-states-order-reversed nil
)
4847 ("nologrepeat" org-log-repeat nil
)
4848 ("logreschedule" org-log-reschedule time
)
4849 ("lognotereschedule" org-log-reschedule note
)
4850 ("nologreschedule" org-log-reschedule nil
)
4851 ("logredeadline" org-log-redeadline time
)
4852 ("lognoteredeadline" org-log-redeadline note
)
4853 ("nologredeadline" org-log-redeadline nil
)
4854 ("logrefile" org-log-refile time
)
4855 ("lognoterefile" org-log-refile note
)
4856 ("nologrefile" org-log-refile nil
)
4857 ("fninline" org-footnote-define-inline t
)
4858 ("nofninline" org-footnote-define-inline nil
)
4859 ("fnlocal" org-footnote-section nil
)
4860 ("fnauto" org-footnote-auto-label t
)
4861 ("fnprompt" org-footnote-auto-label nil
)
4862 ("fnconfirm" org-footnote-auto-label confirm
)
4863 ("fnplain" org-footnote-auto-label plain
)
4864 ("fnadjust" org-footnote-auto-adjust t
)
4865 ("nofnadjust" org-footnote-auto-adjust nil
)
4866 ("constcgs" constants-unit-system cgs
)
4867 ("constSI" constants-unit-system SI
)
4868 ("noptag" org-tag-persistent-alist nil
)
4869 ("hideblocks" org-hide-block-startup t
)
4870 ("nohideblocks" org-hide-block-startup nil
)
4871 ("beamer" org-startup-with-beamer-mode t
)
4872 ("entitiespretty" org-pretty-entities t
)
4873 ("entitiesplain" org-pretty-entities nil
))
4874 "Variable associated with STARTUP options for org-mode.
4875 Each element is a list of three items: the startup options (as written
4876 in the #+STARTUP line), the corresponding variable, and the value to set
4877 this variable to if the option is found. An optional forth element PUSH
4878 means to push this value onto the list in the variable.")
4880 (defun org-update-property-plist (key val props
)
4881 "Update PROPS with KEY and VAL."
4882 (let* ((appending (string= "+" (substring key
(- (length key
) 1))))
4883 (key (if appending
(substring key
0 (- (length key
) 1)) key
))
4884 (remainder (org-remove-if (lambda (p) (string= (car p
) key
)) props
))
4885 (previous (cdr (assoc key props
))))
4887 (cons (cons key
(if previous
(concat previous
" " val
) val
)) remainder
)
4888 (cons (cons key val
) remainder
))))
4890 (defcustom org-group-tags t
4891 "When non-nil (the default), use group tags.
4892 This can be turned on/off through `org-toggle-tags-groups'."
4897 (defvar org-inhibit-startup nil
) ; Dynamically-scoped param.
4899 (defun org-toggle-tags-groups ()
4900 "Toggle support for group tags.
4901 Support for group tags is controlled by the option
4902 `org-group-tags', which is non-nil by default."
4904 (setq org-group-tags
(not org-group-tags
))
4905 (cond ((and (derived-mode-p 'org-agenda-mode
)
4908 ((derived-mode-p 'org-mode
)
4909 (let ((org-inhibit-startup t
)) (org-mode))))
4910 (message "Groups tags support has been turned %s"
4911 (if org-group-tags
"on" "off")))
4913 (defun org-set-regexps-and-options-for-tags ()
4914 "Precompute variables used for tags."
4915 (when (derived-mode-p 'org-mode
)
4916 (org-set-local 'org-file-tags nil
)
4917 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4920 tags ftags key value
)
4924 (goto-char (point-min))
4925 (while (re-search-forward re nil t
)
4926 (setq key
(upcase (org-match-string-no-properties 1))
4927 value
(org-match-string-no-properties 2))
4928 (if (stringp value
) (setq value
(org-trim value
)))
4931 (setq tags
(append tags
(if tags
'("\\n") nil
)
4932 (org-split-string value splitre
))))
4933 ((equal key
"FILETAGS")
4934 (when (string-match "\\S-" value
)
4939 (mapcar (lambda (x) (org-split-string x
":"))
4940 (org-split-string value
)))))))))))
4941 ;; Process the file tags.
4942 (and ftags
(org-set-local 'org-file-tags
4943 (mapcar 'org-add-prop-inherited ftags
)))
4944 (org-set-local 'org-tag-groups-alist nil
)
4945 ;; Process the tags.
4946 (when (and (not tags
) org-tag-alist
)
4949 (lambda (tg) (cond ((eq (car tg
) :startgroup
) "{")
4950 ((eq (car tg
) :endgroup
) "}")
4951 ((eq (car tg
) :grouptags
) ":")
4952 ((eq (car tg
) :newline
) "\n")
4954 (if (characterp (cdr tg
))
4955 (format "(%s)" (char-to-string (cdr tg
))) "")))))
4958 (while (setq e
(pop tags
))
4961 (progn (push '(:startgroup
) tgs
)
4962 (when (equal (nth 1 tags
) ":")
4963 (push (list (replace-regexp-in-string
4964 "(.+)$" "" (nth 0 tags
)))
4965 org-tag-groups-alist
)
4967 ((equal e
":") (push '(:grouptags
) tgs
))
4968 ((equal e
"}") (push '(:endgroup
) tgs
) (if g
(setq g nil
)))
4969 ((equal e
"\\n") (push '(:newline
) tgs
))
4970 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e
)
4971 (push (cons (match-string 1 e
)
4972 (string-to-char (match-string 2 e
))) tgs
)
4974 (setcar org-tag-groups-alist
4975 (append (car org-tag-groups-alist
)
4976 (list (match-string 1 e
)))))
4977 (if g
(setq g
(1+ g
))))
4978 (t (push (list e
) tgs
)
4980 (setcar org-tag-groups-alist
4981 (append (car org-tag-groups-alist
) (list e
))))
4982 (if g
(setq g
(1+ g
))))))
4983 (org-set-local 'org-tag-alist nil
)
4984 (while (setq e
(pop tgs
))
4985 (or (and (stringp (car e
))
4986 (assoc (car e
) org-tag-alist
))
4987 (push e org-tag-alist
)))
4988 ;; Return a list with tag variables
4989 (list org-file-tags org-tag-alist org-tag-groups-alist
)))))
4991 (defvar org-ota nil
)
4992 (defun org-set-regexps-and-options ()
4993 "Precompute regular expressions used in the current buffer."
4994 (when (derived-mode-p 'org-mode
)
4995 (org-set-local 'org-todo-kwd-alist nil
)
4996 (org-set-local 'org-todo-key-alist nil
)
4997 (org-set-local 'org-todo-key-trigger nil
)
4998 (org-set-local 'org-todo-keywords-1 nil
)
4999 (org-set-local 'org-done-keywords nil
)
5000 (org-set-local 'org-todo-heads nil
)
5001 (org-set-local 'org-todo-sets nil
)
5002 (org-set-local 'org-todo-log-states nil
)
5003 (org-set-local 'org-file-properties nil
)
5004 (let ((re (org-make-options-regexp
5005 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
5006 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
5007 "SETUPFILE" "OPTIONS")
5008 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
5010 (scripts org-use-sub-superscripts
)
5011 kwds kws0 kwsa key log value cat arch const links hw dws
5012 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
5017 (goto-char (point-min))
5024 (insert ext-setup-or-nil
)
5025 (let ((major-mode 'org-mode
) org-ota
)
5026 (setq ret
(save-match-data
5027 (org-set-regexps-and-options-for-tags)))))
5028 ;; Append setupfile tags to existing tags
5031 (delq nil
(append org-file-tags
(nth 0 ret
)))
5033 (delq nil
(append org-tag-alist
(nth 1 ret
)))
5034 org-tag-groups-alist
5035 (delq nil
(append org-tag-groups-alist
(nth 2 ret
))))))
5036 (and ext-setup-or-nil
5037 (string-match re ext-setup-or-nil start
)
5038 (setq start
(match-end 0)))
5039 (and (setq ext-setup-or-nil nil start
0)
5040 (re-search-forward re nil t
)))
5041 (setq key
(upcase (match-string 1 ext-setup-or-nil
))
5042 value
(org-match-string-no-properties 2 ext-setup-or-nil
))
5043 (if (stringp value
) (setq value
(org-trim value
)))
5045 ((equal key
"CATEGORY")
5047 ((member key
'("SEQ_TODO" "TODO"))
5048 (push (cons 'sequence
(org-split-string value splitre
)) kwds
))
5049 ((equal key
"TYP_TODO")
5050 (push (cons 'type
(org-split-string value splitre
)) kwds
))
5051 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key
)
5052 ;; general TODO-like setup
5053 (push (cons (intern (downcase (match-string 1 key
)))
5054 (org-split-string value splitre
)) kwds
))
5055 ((equal key
"COLUMNS")
5056 (org-set-local 'org-columns-default-format value
))
5058 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value
)
5059 (push (cons (match-string 1 value
)
5060 (org-trim (match-string 2 value
)))
5062 ((equal key
"PRIORITIES")
5063 (setq prio
(org-split-string value
" +")))
5064 ((equal key
"PROPERTY")
5065 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value
)
5066 (setq props
(org-update-property-plist (match-string 1 value
)
5067 (match-string 2 value
)
5069 ((equal key
"CONSTANTS")
5070 (org-table-set-constants))
5071 ((equal key
"STARTUP")
5072 (let ((opts (org-split-string value splitre
))
5074 (while (setq l
(pop opts
))
5075 (when (setq l
(assoc l org-startup-options
))
5076 (setq var
(nth 1 l
) val
(nth 2 l
))
5078 (set (make-local-variable var
) val
)
5079 (if (not (listp (symbol-value var
)))
5080 (set (make-local-variable var
) nil
))
5081 (set (make-local-variable var
) (symbol-value var
))
5082 (add-to-list var val
))))))
5083 ((equal key
"ARCHIVE")
5085 (remove-text-properties 0 (length arch
)
5086 '(face t fontified t
) arch
))
5087 ((equal key
"OPTIONS")
5088 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value
)
5089 (setq scripts
(read (match-string 2 value
)))))
5090 ((and (equal key
"SETUPFILE")
5091 ;; Prevent checking in Gnus messages
5092 (not buffer-read-only
))
5093 (setq setup-contents
(org-file-contents
5095 (org-remove-double-quotes value
))
5097 (if (not ext-setup-or-nil
)
5098 (setq ext-setup-or-nil setup-contents start
0)
5099 (setq ext-setup-or-nil
5100 (concat (substring ext-setup-or-nil
0 start
)
5101 "\n" setup-contents
"\n"
5102 (substring ext-setup-or-nil start
)))))))
5103 ;; search for property blocks
5104 (goto-char (point-min))
5105 (while (re-search-forward org-block-regexp nil t
)
5106 (when (equal "PROPERTY" (upcase (match-string 1)))
5107 (setq value
(replace-regexp-in-string
5108 "[\n\r]" " " (match-string 4)))
5109 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value
)
5110 (setq props
(org-update-property-plist (match-string 1 value
)
5111 (match-string 2 value
)
5113 (org-set-local 'org-use-sub-superscripts scripts
)
5115 (org-set-local 'org-category
(intern cat
))
5116 (push (cons "CATEGORY" cat
) props
))
5118 (if (< (length prio
) 3) (setq prio
'("A" "C" "B")))
5119 (setq prio
(mapcar 'string-to-char prio
))
5120 (org-set-local 'org-highest-priority
(nth 0 prio
))
5121 (org-set-local 'org-lowest-priority
(nth 1 prio
))
5122 (org-set-local 'org-default-priority
(nth 2 prio
)))
5123 (and props
(org-set-local 'org-file-properties
(nreverse props
)))
5124 (and arch
(org-set-local 'org-archive-location arch
))
5125 (and links
(setq org-link-abbrev-alist-local
(nreverse links
)))
5126 ;; Process the TODO keywords
5128 ;; Use the global values as if they had been given locally.
5129 (setq kwds
(default-value 'org-todo-keywords
))
5130 (if (stringp (car kwds
))
5131 (setq kwds
(list (cons org-todo-interpretation
5132 (default-value 'org-todo-keywords
)))))
5133 (setq kwds
(reverse kwds
)))
5134 (setq kwds
(nreverse kwds
))
5136 (while (setq kws
(pop kwds
))
5138 (run-hook-with-args-until-success
5139 'org-todo-setup-filter-hook kws
)
5141 (setq inter
(pop kws
) sep
(member "|" kws
)
5142 kws0
(delete "|" (copy-sequence kws
))
5147 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x
)
5149 (setq kw
(match-string 1 x
)
5150 key
(and (match-end 2) (match-string 2 x
))
5151 log
(org-extract-log-state-settings x
))
5152 (push (cons kw
(and key
(string-to-char key
))) kwsa
)
5153 (and log
(push log org-todo-log-states
))
5155 (error "Invalid TODO keyword %s" x
)))
5157 kwsa
(if kwsa
(append '((:startgroup
))
5161 dws
(if sep
(org-remove-keyword-keys (cdr sep
)) (last kws1
))
5162 tail
(list inter hw
(car dws
) (org-last dws
))))
5163 (add-to-list 'org-todo-heads hw
'append
)
5164 (push kws1 org-todo-sets
)
5165 (setq org-done-keywords
(append org-done-keywords dws nil
))
5166 (setq org-todo-key-alist
(append org-todo-key-alist kwsa
))
5167 (mapc (lambda (x) (push (cons x tail
) org-todo-kwd-alist
)) kws1
)
5168 (setq org-todo-keywords-1
(append org-todo-keywords-1 kws1 nil
)))
5169 (setq org-todo-sets
(nreverse org-todo-sets
)
5170 org-todo-kwd-alist
(nreverse org-todo-kwd-alist
)
5171 org-todo-key-trigger
(delq nil
(mapcar 'cdr org-todo-key-alist
))
5172 org-todo-key-alist
(org-assign-fast-keys org-todo-key-alist
)))
5173 ;; Compute the regular expressions and other local variables.
5174 ;; Using `org-outline-regexp-bol' would complicate them much,
5175 ;; because of the fixed white space at the end of that string.
5176 (if (not org-done-keywords
)
5177 (setq org-done-keywords
(and org-todo-keywords-1
5178 (list (org-last org-todo-keywords-1
)))))
5179 (setq org-ds-keyword-length
(+ 2 (max (length org-deadline-string
)
5180 (length org-scheduled-string
)
5181 (length org-clock-string
)
5182 (length org-closed-string
)))
5183 org-not-done-keywords
5184 (org-delete-all org-done-keywords
(copy-sequence org-todo-keywords-1
))
5187 (mapconcat 'regexp-quote org-todo-keywords-1
"\\|")
5191 (mapconcat 'regexp-quote org-not-done-keywords
"\\|")
5193 org-not-done-heading-regexp
5194 (format org-heading-keyword-regexp-format org-not-done-regexp
)
5195 org-todo-line-regexp
5196 (format org-heading-keyword-maybe-regexp-format org-todo-regexp
)
5197 org-complex-heading-regexp
5198 (concat "^\\(\\*+\\)"
5199 "\\(?: +" org-todo-regexp
"\\)?"
5200 "\\(?: +\\(\\[#.\\]\\)\\)?"
5201 "\\(?: +\\(.*?\\)\\)??"
5202 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5204 org-complex-heading-regexp-format
5205 (concat "^\\(\\*+\\)"
5206 "\\(?: +" org-todo-regexp
"\\)?"
5207 "\\(?: +\\(\\[#.\\]\\)\\)?"
5209 ;; Stats cookies can be stuck to body.
5210 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5212 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5214 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5216 org-todo-line-tags-regexp
5217 (concat "^\\(\\*+\\)"
5218 "\\(?: +" org-todo-regexp
"\\)?"
5219 "\\(?: +\\(.*?\\)\\)??"
5220 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5222 org-deadline-regexp
(concat "\\<" org-deadline-string
)
5223 org-deadline-time-regexp
5224 (concat "\\<" org-deadline-string
" *<\\([^>]+\\)>")
5225 org-deadline-time-hour-regexp
5226 (concat "\\<" org-deadline-string
5227 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5228 org-deadline-line-regexp
5229 (concat "\\<\\(" org-deadline-string
"\\).*")
5230 org-scheduled-regexp
5231 (concat "\\<" org-scheduled-string
)
5232 org-scheduled-time-regexp
5233 (concat "\\<" org-scheduled-string
" *<\\([^>]+\\)>")
5234 org-scheduled-time-hour-regexp
5235 (concat "\\<" org-scheduled-string
5236 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5237 org-closed-time-regexp
5238 (concat "\\<" org-closed-string
" *\\[\\([^]]+\\)\\]")
5239 org-keyword-time-regexp
5240 (concat "\\<\\(" org-scheduled-string
5241 "\\|" org-deadline-string
5242 "\\|" org-closed-string
5243 "\\|" org-clock-string
"\\)"
5244 " *[[<]\\([^]>]+\\)[]>]")
5245 org-keyword-time-not-clock-regexp
5246 (concat "\\<\\(" org-scheduled-string
5247 "\\|" org-deadline-string
5248 "\\|" org-closed-string
5250 " *[[<]\\([^]>]+\\)[]>]")
5251 org-maybe-keyword-time-regexp
5252 (concat "\\(\\<\\(" org-scheduled-string
5253 "\\|" org-deadline-string
5254 "\\|" org-closed-string
5255 "\\|" org-clock-string
"\\)\\)?"
5256 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5257 org-all-time-keywords
5258 (mapcar (lambda (w) (substring w
0 -
1))
5259 (list org-scheduled-string org-deadline-string
5260 org-clock-string org-closed-string
)))
5262 (org-compute-latex-and-related-regexp))))
5264 (defun org-file-contents (file &optional noerror
)
5265 "Return the contents of FILE, as a string."
5266 (if (and file
(file-readable-p file
))
5268 (insert-file-contents file
)
5270 (funcall (if noerror
'message
'error
)
5271 "Cannot read file \"%s\"%s"
5273 (let ((from (buffer-file-name (buffer-base-buffer))))
5274 (if from
(concat " (referenced in file \"" from
"\")") "")))))
5276 (defun org-extract-log-state-settings (x)
5277 "Extract the log state setting from a TODO keyword string.
5278 This will extract info from a string like \"WAIT(w@/!)\"."
5279 (let (kw key log1 log2
)
5280 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x
)
5281 (setq kw
(match-string 1 x
)
5282 key
(and (match-end 2) (match-string 2 x
))
5283 log1
(and (match-end 3) (match-string 3 x
))
5284 log2
(and (match-end 4) (match-string 4 x
)))
5287 (and log1
(if (equal log1
"!") 'time
'note
))
5288 (and log2
(if (equal log2
"!") 'time
'note
)))))))
5290 (defun org-remove-keyword-keys (list)
5291 "Remove a pair of parenthesis at the end of each string in LIST."
5293 (if (string-match "(.*)$" x
)
5294 (substring x
0 (match-beginning 0))
5298 (defun org-assign-fast-keys (alist)
5299 "Assign fast keys to a keyword-key alist.
5300 Respect keys that are already there."
5301 (let (new e
(alt ?
0))
5302 (while (setq e
(pop alist
))
5303 (if (or (memq (car e
) '(:newline
:grouptags
:endgroup
:startgroup
))
5304 (cdr e
)) ;; Key already assigned.
5306 (let ((clist (string-to-list (downcase (car e
))))
5307 (used (append new alist
)))
5308 (when (= (car clist
) ?
@)
5310 (while (and clist
(rassoc (car clist
) used
))
5313 (while (rassoc alt used
)
5315 (push (cons (car e
) (or (car clist
) alt
)) new
))))
5318 ;;; Some variables used in various places
5320 (defvar org-window-configuration nil
5321 "Used in various places to store a window configuration.")
5322 (defvar org-selected-window nil
5323 "Used in various places to store a window configuration.")
5324 (defvar org-finish-function nil
5325 "Function to be called when `C-c C-c' is used.
5326 This is for getting out of special buffers like capture.")
5329 ;; FIXME: Occasionally check by commenting these, to make sure
5330 ;; no other functions uses these, forgetting to let-bind them.
5331 (org-no-warnings (defvar entry
)) ;; unprefixed, from calendar.el
5332 (defvar org-last-state
)
5333 (org-no-warnings (defvar date
)) ;; unprefixed, from calendar.el
5335 ;; Defined somewhere in this file, but used before definition.
5336 (defvar org-entities
) ;; defined in org-entities.el
5337 (defvar org-struct-menu
)
5338 (defvar org-org-menu
)
5339 (defvar org-tbl-menu
)
5341 ;;;; Define the Org-mode
5343 ;; We use a before-change function to check if a table might need
5345 (defvar org-table-may-need-update t
5346 "Indicates that a table might need an update.
5347 This variable is set by `org-before-change-function'.
5348 `org-table-align' sets it back to nil.")
5349 (defun org-before-change-function (beg end
)
5350 "Every change indicates that a table might need an update."
5351 (setq org-table-may-need-update t
))
5352 (defvar org-mode-map
)
5353 (defvar org-inhibit-startup-visibility-stuff nil
) ; Dynamically-scoped param.
5354 (defvar org-agenda-keep-modes nil
) ; Dynamically-scoped param.
5355 (defvar org-inhibit-logging nil
) ; Dynamically-scoped param.
5356 (defvar org-inhibit-blocking nil
) ; Dynamically-scoped param.
5357 (defvar org-table-buffer-is-an nil
)
5359 (defvar bidi-paragraph-direction
)
5360 (defvar buffer-face-mode-face
)
5363 (if (and (not (keymapp outline-mode-map
)) (featurep 'allout
))
5364 (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"))
5365 (require 'noutline
"noutline" 'noerror
) ;; stock XEmacs does not have it
5367 ;; Other stuff we need.
5368 (require 'time-date
)
5369 (unless (fboundp 'time-subtract
) (defalias 'time-subtract
'subtract-time
))
5373 ;; (require 'org-macs) moved higher up in the file before it is first used
5374 (require 'org-entities
)
5375 ;; (require 'org-compat) moved higher up in the file before it is first used
5376 (require 'org-faces
)
5378 (require 'org-pcomplete
)
5380 (require 'org-footnote
)
5381 (require 'org-macro
)
5387 (define-derived-mode org-mode outline-mode
"Org"
5388 "Outline-based notes management and organizer, alias
5389 \"Carsten's outline-mode for keeping track of everything.\"
5391 Org-mode develops organizational tasks around a NOTES file which
5392 contains information about projects as plain text. Org-mode is
5393 implemented on top of outline-mode, which is ideal to keep the content
5394 of large files well structured. It supports ToDo items, deadlines and
5395 time stamps, which magically appear in the diary listing of the Emacs
5396 calendar. Tables are easily created with a built-in table editor.
5397 Plain text URL-like links connect to websites, emails (VM), Usenet
5398 messages (Gnus), BBDB entries, and any files related to the project.
5399 For printing and sharing of notes, an Org-mode file (or a part of it)
5400 can be exported as a structured ASCII or HTML file.
5402 The following commands are available:
5406 ;; Get rid of Outline menus, they are not needed
5407 ;; Need to do this here because define-derived-mode sets up
5408 ;; the keymap so late. Still, it is a waste to call this each time
5409 ;; we switch another buffer into org-mode.
5410 (if (featurep 'xemacs
)
5411 (when (boundp 'outline-mode-menu-heading
)
5412 ;; Assume this is Greg's port, it uses easymenu
5413 (easy-menu-remove outline-mode-menu-heading
)
5414 (easy-menu-remove outline-mode-menu-show
)
5415 (easy-menu-remove outline-mode-menu-hide
))
5416 (define-key org-mode-map
[menu-bar headings
] 'undefined
)
5417 (define-key org-mode-map
[menu-bar hide
] 'undefined
)
5418 (define-key org-mode-map
[menu-bar show
] 'undefined
))
5420 (org-load-modules-maybe)
5421 (easy-menu-add org-org-menu
)
5422 (easy-menu-add org-tbl-menu
)
5423 (org-install-agenda-files-menu)
5424 (if org-descriptive-links
(add-to-invisibility-spec '(org-link)))
5425 (add-to-invisibility-spec '(org-cwidth))
5426 (add-to-invisibility-spec '(org-hide-block . t
))
5427 (when (featurep 'xemacs
)
5428 (org-set-local 'line-move-ignore-invisible t
))
5429 (org-set-local 'outline-regexp org-outline-regexp
)
5430 (org-set-local 'outline-level
'org-outline-level
)
5431 (setq bidi-paragraph-direction
'left-to-right
)
5432 (when (and org-ellipsis
5433 (fboundp 'set-display-table-slot
) (boundp 'buffer-display-table
)
5434 (fboundp 'make-glyph-code
))
5435 (unless org-display-table
5436 (setq org-display-table
(make-display-table)))
5437 (set-display-table-slot
5440 (lambda (c) (make-glyph-code c
(and (not (stringp org-ellipsis
))
5442 (if (stringp org-ellipsis
) org-ellipsis
"..."))))
5443 (setq buffer-display-table org-display-table
))
5444 (org-set-regexps-and-options-for-tags)
5445 (org-set-regexps-and-options)
5446 (org-set-font-lock-defaults)
5447 (when (and org-tag-faces
(not org-tags-special-faces-re
))
5448 ;; tag faces set outside customize.... force initialization.
5449 (org-set-tag-faces 'org-tag-faces org-tag-faces
))
5451 (org-set-local 'calc-embedded-open-mode
"# ")
5452 ;; Modify a few syntax entries
5453 (modify-syntax-entry ?
@ "w")
5454 (modify-syntax-entry ?
\" "\"")
5455 (modify-syntax-entry ?
\\ "_")
5456 (modify-syntax-entry ?~
"_")
5457 (if org-startup-truncated
(setq truncate-lines t
))
5458 (when org-startup-indented
(require 'org-indent
) (org-indent-mode 1))
5459 (org-set-local 'font-lock-unfontify-region-function
5460 'org-unfontify-region
)
5461 ;; Activate before-change-function
5462 (org-set-local 'org-table-may-need-update t
)
5463 (org-add-hook 'before-change-functions
'org-before-change-function nil
5465 ;; Check for running clock before killing a buffer
5466 (org-add-hook 'kill-buffer-hook
'org-check-running-clock nil
'local
)
5467 ;; Initialize macros templates.
5468 (org-macro-initialize-templates)
5469 ;; Initialize radio targets.
5470 (org-update-radio-target-regexp)
5472 (org-set-local 'indent-line-function
'org-indent-line
)
5473 (org-set-local 'indent-region-function
'org-indent-region
)
5474 ;; Filling and auto-filling.
5477 (org-setup-comments-handling)
5478 ;; Initialize cache.
5479 (org-element-cache-reset)
5480 ;; Beginning/end of defun
5481 (org-set-local 'beginning-of-defun-function
'org-backward-element
)
5482 (org-set-local 'end-of-defun-function
5484 (if (not (org-at-heading-p))
5485 (org-forward-element)
5486 (org-forward-element)
5487 (forward-char -
1))))
5488 ;; Next error for sparse trees
5489 (org-set-local 'next-error-function
'org-occur-next-match
)
5490 ;; Make sure dependence stuff works reliably, even for users who set it
5492 (if org-enforce-todo-dependencies
5493 (add-hook 'org-blocker-hook
5494 'org-block-todo-from-children-or-siblings-or-parent
)
5495 (remove-hook 'org-blocker-hook
5496 'org-block-todo-from-children-or-siblings-or-parent
))
5497 (if org-enforce-todo-checkbox-dependencies
5498 (add-hook 'org-blocker-hook
5499 'org-block-todo-from-checkboxes
)
5500 (remove-hook 'org-blocker-hook
5501 'org-block-todo-from-checkboxes
))
5503 ;; Align options lines
5505 'align-mode-rules-list
5506 '((org-in-buffer-settings
5507 (regexp .
"^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5508 (modes .
'(org-mode)))))
5511 (org-set-local 'imenu-create-index-function
5512 'org-imenu-get-tree
)
5514 ;; Make isearch reveal context
5515 (if (or (featurep 'xemacs
)
5516 (not (boundp 'outline-isearch-open-invisible-function
)))
5517 ;; Emacs 21 and XEmacs make use of the hook
5518 (org-add-hook 'isearch-mode-end-hook
'org-isearch-end
'append
'local
)
5519 ;; Emacs 22 deals with this through a special variable
5520 (org-set-local 'outline-isearch-open-invisible-function
5521 (lambda (&rest ignore
) (org-show-context 'isearch
))))
5523 ;; Setup the pcomplete hooks
5524 (set (make-local-variable 'pcomplete-command-completion-function
)
5525 'org-pcomplete-initial
)
5526 (set (make-local-variable 'pcomplete-command-name-function
)
5527 'org-command-at-point
)
5528 (set (make-local-variable 'pcomplete-default-completion-function
)
5530 (set (make-local-variable 'pcomplete-parse-arguments-function
)
5531 'org-parse-arguments
)
5532 (set (make-local-variable 'pcomplete-termination-string
) "")
5533 (when (>= emacs-major-version
23)
5534 (set (make-local-variable 'buffer-face-mode-face
) 'org-default
))
5536 ;; If empty file that did not turn on org-mode automatically, make it to.
5537 (if (and org-insert-mode-line-in-empty-file
5538 (org-called-interactively-p 'any
)
5539 (= (point-min) (point-max)))
5540 (insert "# -*- mode: org -*-\n\n"))
5541 (unless org-inhibit-startup
5543 (and org-startup-with-beamer-mode
(org-beamer-mode))
5544 (when org-startup-align-all-tables
5545 (org-table-map-tables 'org-table-align
'quietly
))
5546 (when org-startup-with-inline-images
5547 (org-display-inline-images))
5548 (when org-startup-with-latex-preview
5549 (org-toggle-latex-fragment))
5550 (unless org-inhibit-startup-visibility-stuff
5551 (org-set-startup-visibility))
5552 (org-refresh-effort-properties)))
5553 ;; Try to set org-hide correctly
5554 (let ((foreground (org-find-invisible-foreground)))
5556 (set-face-foreground 'org-hide foreground
))))
5558 ;; Update `customize-package-emacs-version-alist'
5559 (add-to-list 'customize-package-emacs-version-alist
5560 '(Org ("6.21b" .
"23.1") ("6.33x" .
"23.2")
5561 ("7.8.11" .
"24.1") ("7.9.4" .
"24.3")
5562 ("8.2.6" .
"24.4")))
5564 (defvar org-mode-transpose-word-syntax-table
5565 (let ((st (make-syntax-table)))
5566 (mapc (lambda(c) (modify-syntax-entry
5567 (string-to-char (car c
)) "w p" st
))
5571 (when (fboundp 'abbrev-table-put
)
5572 (abbrev-table-put org-mode-abbrev-table
5573 :parents
(list text-mode-abbrev-table
)))
5575 (defun org-find-invisible-foreground ()
5576 (let ((candidates (remove
5579 (list (face-background 'default
)
5580 (face-background 'org-default
))
5583 (when (boundp alist
)
5584 (cdr (assoc 'background-color
(symbol-value alist
)))))
5585 '(default-frame-alist initial-frame-alist window-system-default-frame-alist
))
5586 (list (face-foreground 'org-hide
))))))
5587 (car (remove nil candidates
))))
5589 (defun org-current-time (&optional rounding-minutes past
)
5590 "Current time, possibly rounded to ROUNDING-MINUTES.
5591 When ROUNDING-MINUTES is not an integer, fall back on the car of
5592 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5593 the rounding returns a past time."
5594 (let ((r (or (and (integerp rounding-minutes
) rounding-minutes
)
5595 (car org-time-stamp-rounding-minutes
)))
5596 (time (decode-time)) res
)
5601 (append (list 0 (* r
(floor (+ .5 (/ (float (nth 1 time
)) r
)))))
5603 (if (and past
(< (org-float-time (time-subtract (current-time) res
)) 0))
5604 (seconds-to-time (- (org-float-time res
) (* r
60)))
5608 "Return today date, considering `org-extend-today-until'."
5610 (time-subtract (current-time)
5611 (list 0 (* 3600 org-extend-today-until
) 0))))
5613 ;;;; Font-Lock stuff, including the activators
5615 (defvar org-mouse-map
(make-sparse-keymap))
5616 (org-defkey org-mouse-map
[mouse-2
] 'org-open-at-mouse
)
5617 (org-defkey org-mouse-map
[mouse-3
] 'org-find-file-at-mouse
)
5618 (when org-mouse-1-follows-link
5619 (org-defkey org-mouse-map
[follow-link
] 'mouse-face
))
5620 (when org-tab-follows-link
5621 (org-defkey org-mouse-map
[(tab)] 'org-open-at-point
)
5622 (org-defkey org-mouse-map
"\C-i" 'org-open-at-point
))
5624 (require 'font-lock
)
5626 (defconst org-non-link-chars
"]\t\n\r<>")
5627 (defvar org-link-types
'("http" "https" "ftp" "mailto" "file" "file+emacs"
5628 "file+sys" "news" "shell" "elisp" "doi" "message"
5630 (defvar org-link-types-re nil
5631 "Matches a link that has a url-like prefix like \"http:\"")
5632 (defvar org-link-re-with-space nil
5633 "Matches a link with spaces, optional angular brackets around it.")
5634 (defvar org-link-re-with-space2 nil
5635 "Matches a link with spaces, optional angular brackets around it.")
5636 (defvar org-link-re-with-space3 nil
5637 "Matches a link with spaces, only for internal part in bracket links.")
5638 (defvar org-angle-link-re nil
5639 "Matches link with angular brackets, spaces are allowed.")
5640 (defvar org-plain-link-re nil
5641 "Matches plain link, without spaces.")
5642 (defvar org-bracket-link-regexp nil
5643 "Matches a link in double brackets.")
5644 (defvar org-bracket-link-analytic-regexp nil
5645 "Regular expression used to analyze links.
5646 Here is what the match groups contain after a match:
5652 (defvar org-bracket-link-analytic-regexp
++ nil
5653 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5654 (defvar org-any-link-re nil
5655 "Regular expression matching any link.")
5657 (defconst org-match-sexp-depth
3
5658 "Number of stacked braces for sub/superscript matching.")
5660 (defun org-create-multibrace-regexp (left right n
)
5661 "Create a regular expression which will match a balanced sexp.
5662 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5663 as single character strings.
5664 The regexp returned will match the entire expression including the
5665 delimiters. It will also define a single group which contains the
5666 match except for the outermost delimiters. The maximum depth of
5667 stacked delimiters is N. Escaping delimiters is not possible."
5668 (let* ((nothing (concat "[^" left right
"]*?"))
5671 (next (concat "\\(?:" nothing left nothing right
"\\)+" nothing
)))
5674 re
(concat re or next
)
5675 next
(concat "\\(?:" nothing left next right
"\\)+" nothing
)))
5676 (concat left
"\\(" re
"\\)" right
)))
5678 (defconst org-match-substring-regexp
5680 "\\(\\S-\\)\\([_^]\\)\\("
5681 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth
) "\\)"
5683 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth
) "\\)"
5685 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5686 "The regular expression matching a sub- or superscript.")
5688 (defconst org-match-substring-with-braces-regexp
5690 "\\(\\S-\\)\\([_^]\\)"
5691 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth
) "\\)")
5692 "The regular expression matching a sub- or superscript, forcing braces.")
5694 (defun org-make-link-regexps ()
5695 "Update the link regular expressions.
5696 This should be called after the variable `org-link-types' has changed."
5697 (let ((types-re (regexp-opt org-link-types t
)))
5698 (setq org-link-types-re
5699 (concat "\\`" types-re
":")
5700 org-link-re-with-space
5701 (concat "<?" types-re
":"
5702 "\\([^" org-non-link-chars
" ]"
5703 "[^" org-non-link-chars
"]*"
5704 "[^" org-non-link-chars
" ]\\)>?")
5705 org-link-re-with-space2
5706 (concat "<?" types-re
":"
5707 "\\([^" org-non-link-chars
" ]"
5709 "[^" org-non-link-chars
" ]\\)>?")
5710 org-link-re-with-space3
5711 (concat "<?" types-re
":"
5712 "\\([^" org-non-link-chars
" ]"
5715 (concat "<" types-re
":"
5716 "\\([^" org-non-link-chars
" ]"
5717 "[^" org-non-link-chars
"]*"
5722 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5723 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5724 org-bracket-link-regexp
5725 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5726 org-bracket-link-analytic-regexp
5729 "\\(" types-re
":\\)?"
5732 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5734 org-bracket-link-analytic-regexp
++
5737 "\\(" (regexp-opt (cons "coderef" org-link-types
) t
) ":\\)?"
5740 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5743 (concat "\\(" org-bracket-link-regexp
"\\)\\|\\("
5744 org-angle-link-re
"\\)\\|\\("
5745 org-plain-link-re
"\\)"))))
5747 (org-make-link-regexps)
5749 (defvar org-emph-face nil
)
5751 (defun org-do-emphasis-faces (limit)
5752 "Run through the buffer and emphasize strings."
5754 (while (and (not rtn
) (re-search-forward org-emph-re limit t
))
5755 (let* ((border (char-after (match-beginning 3)))
5756 (bre (regexp-quote (char-to-string border
))))
5757 (if (and (not (= border
(char-after (match-beginning 4))))
5758 (not (save-match-data
5759 (string-match (concat bre
".*" bre
)
5760 (replace-regexp-in-string
5762 (substring (match-string 2) 1 -
1))))))
5765 (setq a
(assoc (match-string 3) org-emphasis-alist
))
5766 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5770 (org-remove-flyspell-overlays-in
5771 (match-beginning 0) (match-end 0)))
5772 (add-text-properties (match-beginning 2) (match-end 2)
5773 '(font-lock-multiline t org-emphasis t
))
5774 (when org-hide-emphasis-markers
5775 (add-text-properties (match-end 4) (match-beginning 5)
5776 '(invisible org-link
))
5777 (add-text-properties (match-beginning 3) (match-end 3)
5778 '(invisible org-link
))))))
5779 (goto-char (1+ (match-beginning 0))))
5782 (defun org-emphasize (&optional char
)
5783 "Insert or change an emphasis, i.e. a font like bold or italic.
5784 If there is an active region, change that region to a new emphasis.
5785 If there is no region, just insert the marker characters and position
5786 the cursor between them.
5787 CHAR should be the marker character. If it is a space, it means to
5788 remove the emphasis of the selected region.
5789 If CHAR is not given (for example in an interactive call) it will be
5792 (let ((erc org-emphasis-regexp-components
)
5794 (string "") beg end move c s
)
5795 (if (org-region-active-p)
5796 (setq beg
(region-beginning) end
(region-end)
5797 string
(buffer-substring beg end
))
5801 (message "Emphasis marker or tag: [%s]"
5802 (mapconcat (lambda(e) (car e
)) org-emphasis-alist
""))
5803 (setq char
(read-char-exclusive)))
5804 (if (equal char ?\
)
5805 (setq s
"" move nil
)
5806 (unless (assoc (char-to-string char
) org-emphasis-alist
)
5807 (user-error "No such emphasis marker: \"%c\"" char
))
5808 (setq s
(char-to-string char
)))
5809 (while (and (> (length string
) 1)
5810 (equal (substring string
0 1) (substring string -
1))
5811 (assoc (substring string
0 1) org-emphasis-alist
))
5812 (setq string
(substring string
1 -
1)))
5813 (setq string
(concat s string s
))
5814 (if beg
(delete-region beg end
))
5816 (string-match (concat "[" (nth 0 erc
) "\n]")
5817 (char-to-string (char-before (point)))))
5820 (string-match (concat "[" (nth 1 erc
) "\n]")
5821 (char-to-string (char-after (point)))))
5822 (insert " ") (backward-char 1))
5824 (and move
(backward-char 1))))
5826 (defconst org-nonsticky-props
5827 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link
))
5829 (defsubst org-rear-nonsticky-at
(pos)
5830 (add-text-properties (1- pos
) pos
(list 'rear-nonsticky org-nonsticky-props
)))
5832 (defun org-activate-plain-links (limit)
5833 "Add link properties for plain links."
5835 (when (and (re-search-forward (concat org-plain-link-re
) limit t
)
5836 (not (member 'org-tag
5837 (get-text-property (1- (match-beginning 0)) 'face
)))
5838 (not (org-in-src-block-p)))
5839 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5840 (setq f
(get-text-property (match-beginning 0) 'face
))
5841 (setq hl
(org-match-string-no-properties 0))
5842 (if (or (eq f
'org-tag
)
5843 (and (listp f
) (memq 'org-tag f
)))
5845 (add-text-properties (match-beginning 0) (match-end 0)
5846 (list 'mouse-face
'highlight
5848 'htmlize-link
`(:uri
,hl
)
5849 'keymap org-mouse-map
))
5850 (org-rear-nonsticky-at (match-end 0)))
5853 (defun org-activate-code (limit)
5854 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t
)
5856 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5857 (remove-text-properties (match-beginning 0) (match-end 0)
5858 '(display t invisible t intangible t
))
5861 (defcustom org-src-fontify-natively t
5862 "When non-nil, fontify code in code blocks."
5865 :package-version
'(Org .
"8.3")
5866 :group
'org-appearance
5869 (defcustom org-allow-promoting-top-level-subtree nil
5870 "When non-nil, allow promoting a top level subtree.
5871 The leading star of the top level headline will be replaced
5875 :group
'org-appearance
)
5877 (defun org-fontify-meta-lines-and-blocks (limit)
5879 (org-fontify-meta-lines-and-blocks-1 limit
)
5880 (error (message "org-mode fontification error"))))
5882 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5883 "Fontify #+ lines and blocks."
5884 (let ((case-fold-search t
))
5885 (if (re-search-forward
5886 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5888 (let ((beg (match-beginning 0))
5889 (block-start (match-end 0))
5891 (lang (match-string 7))
5892 (beg1 (line-beginning-position 2))
5893 (dc1 (downcase (match-string 2)))
5894 (dc3 (downcase (match-string 3)))
5895 end end1 quoting block-type ovl
)
5897 ((member dc1
'("+html:" "+ascii:" "+latex:"))
5898 ;; a single line of backend-specific content
5899 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5900 (remove-text-properties (match-beginning 0) (match-end 0)
5901 '(display t invisible t intangible t
))
5902 (add-text-properties (match-beginning 1) (match-end 3)
5903 '(font-lock-fontified t face org-meta-line
))
5904 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5905 '(font-lock-fontified t face org-block
))
5906 ; for backend-specific code
5908 ((and (match-end 4) (equal dc3
"+begin"))
5910 (setq block-type
(downcase (match-string 5))
5911 quoting
(member block-type org-protecting-blocks
))
5912 (when (re-search-forward
5913 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5914 nil t
) ;; on purpose, we look further than LIMIT
5915 (setq end
(min (point-max) (match-end 0))
5916 end1
(min (point-max) (1- (match-beginning 0))))
5917 (setq block-end
(match-beginning 0))
5919 (org-remove-flyspell-overlays-in beg1 end1
)
5920 (remove-text-properties beg end
5921 '(display t invisible t intangible t
)))
5922 (add-text-properties
5923 beg end
'(font-lock-fontified t font-lock-multiline t
))
5924 (add-text-properties beg beg1
'(face org-meta-line
))
5925 (org-remove-flyspell-overlays-in beg beg1
)
5926 (add-text-properties ; For end_src
5927 end1
(min (point-max) (1+ end
)) '(face org-meta-line
))
5928 (org-remove-flyspell-overlays-in end1 end
)
5930 ((and lang
(not (string= lang
"")) org-src-fontify-natively
)
5931 (org-src-font-lock-fontify-block lang block-start block-end
)
5932 (add-text-properties beg1 block-end
'(src-block t
)))
5934 (add-text-properties beg1
(min (point-max) (1+ end1
))
5935 '(face org-block
))) ; end of source block
5936 ((not org-fontify-quote-and-verse-blocks
))
5937 ((string= block-type
"quote")
5938 (add-text-properties beg1
(min (point-max) (1+ end1
)) '(face org-quote
)))
5939 ((string= block-type
"verse")
5940 (add-text-properties beg1
(min (point-max) (1+ end1
)) '(face org-verse
))))
5941 (add-text-properties beg beg1
'(face org-block-begin-line
))
5942 (add-text-properties (min (point-max) (1+ end
)) (min (point-max) (1+ end1
))
5943 '(face org-block-end-line
))
5945 ((member dc1
'("+title:" "+author:" "+email:" "+date:"))
5946 (org-remove-flyspell-overlays-in
5948 (if (equal "+title:" dc1
) (match-end 2) (match-end 0)))
5949 (add-text-properties
5951 (if (member (intern (substring dc1
1 -
1)) org-hidden-keywords
)
5952 '(font-lock-fontified t invisible t
)
5953 '(font-lock-fontified t face org-document-info-keyword
)))
5954 (add-text-properties
5955 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5956 (if (string-equal dc1
"+title:")
5957 '(font-lock-fontified t face org-document-title
)
5958 '(font-lock-fontified t face org-document-info
))))
5959 ((or (equal dc1
"+results")
5960 (member dc1
'("+begin:" "+end:" "+caption:" "+label:"
5961 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5962 "+call:" "+header:" "+headers:" "+name:"))
5963 (and (match-end 4) (equal dc3
"+attr")))
5964 (org-remove-flyspell-overlays-in
5966 (if (equal "+caption:" dc1
) (match-end 2) (match-end 0)))
5967 (add-text-properties
5969 '(font-lock-fontified t face org-meta-line
))
5971 ((member dc3
'(" " ""))
5972 (org-remove-flyspell-overlays-in beg
(match-end 0))
5973 (add-text-properties
5975 '(font-lock-fontified t face font-lock-comment-face
)))
5976 (t ;; just any other in-buffer setting, but not indented
5977 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5978 (add-text-properties
5980 '(font-lock-fontified t face org-meta-line
))
5983 (defun org-fontify-drawers (limit)
5985 (when (re-search-forward org-drawer-regexp limit t
)
5986 (add-text-properties
5987 (match-beginning 0) (match-end 0)
5988 '(font-lock-fontified t face org-special-keyword
))
5989 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5992 (defun org-fontify-macros (limit)
5994 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t
)
5995 (add-text-properties
5996 (match-beginning 0) (match-end 0)
5997 '(font-lock-fontified t face org-macro
))
5998 (when org-hide-macro-markers
5999 (add-text-properties (match-end 2) (match-beginning 2)
6001 (add-text-properties (match-beginning 1) (match-end 1)
6003 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6006 (defun org-activate-angle-links (limit)
6007 "Add text properties for angle links."
6008 (if (and (re-search-forward org-angle-link-re limit t
)
6009 (not (org-in-src-block-p)))
6011 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6012 (add-text-properties (match-beginning 0) (match-end 0)
6013 (list 'mouse-face
'highlight
6014 'keymap org-mouse-map
))
6015 (org-rear-nonsticky-at (match-end 0))
6018 (defun org-activate-footnote-links (limit)
6019 "Add text properties for footnotes."
6020 (let ((fn (org-footnote-next-reference-or-definition limit
)))
6022 (let* ((beg (nth 1 fn
))
6025 (referencep (/= (line-beginning-position) beg
)))
6026 (when (and referencep
(nth 3 fn
))
6029 (search-forward (or label
"fn:"))
6030 (org-remove-flyspell-overlays-in beg
(match-end 0))))
6031 (add-text-properties beg end
6032 (list 'mouse-face
'highlight
6033 'keymap org-mouse-map
6035 (if referencep
"Footnote reference"
6036 "Footnote definition")
6037 'font-lock-fontified t
6038 'font-lock-multiline t
6039 'face
'org-footnote
))))))
6041 (defun org-activate-bracket-links (limit)
6042 "Add text properties for bracketed links."
6043 (if (and (re-search-forward org-bracket-link-regexp limit t
)
6044 (not (org-in-src-block-p)))
6045 (let* ((hl (org-match-string-no-properties 1))
6046 (help (concat "LINK: " (save-match-data (org-link-unescape hl
))))
6047 (ip (org-maybe-intangible
6048 (list 'invisible
'org-link
6049 'keymap org-mouse-map
'mouse-face
'highlight
6050 'font-lock-multiline t
'help-echo help
6051 'htmlize-link
`(:uri
,hl
))))
6052 (vp (list 'keymap org-mouse-map
'mouse-face
'highlight
6053 'font-lock-multiline t
'help-echo help
6054 'htmlize-link
`(:uri
,hl
))))
6055 ;; We need to remove the invisible property here. Table narrowing
6056 ;; may have made some of this invisible.
6057 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6058 (remove-text-properties (match-beginning 0) (match-end 0)
6062 (add-text-properties (match-beginning 0) (match-beginning 3) ip
)
6063 (org-rear-nonsticky-at (match-beginning 3))
6064 (add-text-properties (match-beginning 3) (match-end 3) vp
)
6065 (org-rear-nonsticky-at (match-end 3))
6066 (add-text-properties (match-end 3) (match-end 0) ip
)
6067 (org-rear-nonsticky-at (match-end 0)))
6068 (add-text-properties (match-beginning 0) (match-beginning 1) ip
)
6069 (org-rear-nonsticky-at (match-beginning 1))
6070 (add-text-properties (match-beginning 1) (match-end 1) vp
)
6071 (org-rear-nonsticky-at (match-end 1))
6072 (add-text-properties (match-end 1) (match-end 0) ip
)
6073 (org-rear-nonsticky-at (match-end 0)))
6076 (defun org-activate-dates (limit)
6077 "Add text properties for dates."
6078 (if (and (re-search-forward org-tsr-regexp-both limit t
)
6079 (not (equal (char-before (match-beginning 0)) 91)))
6081 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6082 (add-text-properties (match-beginning 0) (match-end 0)
6083 (list 'mouse-face
'highlight
6084 'keymap org-mouse-map
))
6085 (org-rear-nonsticky-at (match-end 0))
6086 (when org-display-custom-times
6088 (org-display-custom-time (match-beginning 3) (match-end 3)))
6089 (org-display-custom-time (match-beginning 1) (match-end 1)))
6092 (defvar org-target-link-regexp nil
6093 "Regular expression matching radio targets in plain text.")
6094 (make-variable-buffer-local 'org-target-link-regexp
)
6096 (defconst org-target-regexp
(let ((border "[^<>\n\r \t]"))
6097 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6098 border border border
))
6099 "Regular expression matching a link target.")
6101 (defconst org-radio-target-regexp
(format "<%s>" org-target-regexp
)
6102 "Regular expression matching a radio target.")
6104 (defconst org-any-target-regexp
6105 (format "%s\\|%s" org-radio-target-regexp org-target-regexp
)
6106 "Regular expression matching any target.")
6108 (defun org-activate-target-links (limit)
6109 "Add text properties for target matches."
6110 (when org-target-link-regexp
6111 (let ((case-fold-search t
))
6112 (if (re-search-forward org-target-link-regexp limit t
)
6114 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6115 (add-text-properties (match-beginning 1) (match-end 1)
6116 (list 'mouse-face
'highlight
6117 'keymap org-mouse-map
6118 'help-echo
"Radio target link"
6119 'org-linked-text t
))
6120 (org-rear-nonsticky-at (match-end 1))
6123 (defun org-update-radio-target-regexp ()
6124 "Find all radio targets in this file and update the regular expression.
6125 Also refresh fontification if needed."
6127 (let ((old-regexp org-target-link-regexp
)
6128 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6129 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6131 (org-with-wide-buffer
6132 (goto-char (point-min))
6134 (while (re-search-forward org-radio-target-regexp nil t
)
6135 ;; Make sure point is really within the object.
6137 (let ((obj (org-element-context)))
6138 (when (eq (org-element-type obj
) 'radio-target
)
6139 (add-to-list 'rtn
(org-element-property :value obj
)))))
6141 (setq org-target-link-regexp
6146 (replace-regexp-in-string
6147 " +" "\\s-+" (regexp-quote x
) t t
))
6151 (unless (equal old-regexp org-target-link-regexp
)
6153 (let ((regexp (cond ((not old-regexp
) org-target-link-regexp
)
6154 ((not org-target-link-regexp
) old-regexp
)
6159 (substring re
(length before-re
)
6160 (- (length after-re
))))
6161 (list old-regexp org-target-link-regexp
)
6164 (org-with-wide-buffer
6165 (goto-char (point-min))
6166 (while (re-search-forward regexp nil t
)
6167 (org-element-cache-refresh (match-beginning 1)))))
6168 ;; Re fontify buffer.
6169 (when (memq 'radio org-highlight-links
)
6170 (org-restart-font-lock)))))
6172 (defun org-hide-wide-columns (limit)
6174 (setq s
(text-property-any (point) (or limit
(point-max))
6177 (setq e
(next-single-property-change s
'org-cwidth
))
6178 (add-text-properties s e
(org-maybe-intangible '(invisible org-cwidth
)))
6182 (defvar org-latex-and-related-regexp nil
6183 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6185 (defun org-compute-latex-and-related-regexp ()
6186 "Compute regular expression for LaTeX, entities and sub/superscript.
6187 Result depends on variable `org-highlight-latex-and-related'."
6189 'org-latex-and-related-regexp
6191 (cond ((not (memq 'script org-highlight-latex-and-related
)) nil
)
6192 ((eq org-use-sub-superscripts
'{})
6193 (list org-match-substring-with-braces-regexp
))
6194 (org-use-sub-superscripts (list org-match-substring-regexp
))))
6196 (when (memq 'latex org-highlight-latex-and-related
)
6197 (let ((matchers (plist-get org-format-latex-options
:matchers
)))
6200 (and (member (car x
) matchers
) (nth 1 x
)))
6201 org-latex-regexps
)))))
6203 (when (memq 'entities org-highlight-latex-and-related
)
6204 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6205 (mapconcat 'identity
(append re-latex re-entities re-sub
) "\\|"))))
6207 (defun org-do-latex-and-related (limit)
6208 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6209 LIMIT bounds the search for syntax to highlight. Stop at first
6210 highlighted object, if any. Return t if some highlighting was
6211 done, nil otherwise."
6212 (when (org-string-nw-p org-latex-and-related-regexp
)
6214 (while (re-search-forward org-latex-and-related-regexp limit t
)
6215 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6217 '(org-code org-verbatim underline
))
6218 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6222 (font-lock-prepend-text-property
6223 (+ offset
(match-beginning 0)) (match-end 0)
6224 'face
'org-latex-and-related
)
6225 (add-text-properties (+ offset
(match-beginning 0)) (match-end 0)
6226 '(font-lock-multiline t
)))
6230 (defun org-restart-font-lock ()
6231 "Restart `font-lock-mode', to force refontification."
6232 (when (and (boundp 'font-lock-mode
) font-lock-mode
)
6234 (font-lock-mode 1)))
6236 (defun org-activate-tags (limit)
6237 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t
)
6239 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6240 (add-text-properties (match-beginning 1) (match-end 1)
6241 (list 'mouse-face
'highlight
6242 'keymap org-mouse-map
))
6243 (org-rear-nonsticky-at (match-end 1))
6246 (defun org-outline-level ()
6247 "Compute the outline level of the heading at point.
6248 If this is called at a normal headline, the level is the number of stars.
6249 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6251 (if (not (ignore-errors (org-back-to-heading t
)))
6253 (looking-at org-outline-regexp
)
6254 (1- (- (match-end 0) (match-beginning 0))))))
6256 (defvar org-font-lock-keywords nil
)
6258 (defsubst org-re-property
(property &optional literal allow-null
)
6259 "Return a regexp matching a PROPERTY line.
6261 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6262 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6263 non-nil, match properties even without a value.
6265 Match group 3 is set to the value when it exists. If there is no
6266 value and ALLOW-NULL is non-nil, it is set to the empty string."
6269 (format "\\(?1::\\(?2:%s\\):\\)"
6270 (if literal property
(regexp-quote property
)))
6272 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$"
6273 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$")))
6275 (defconst org-property-re
6276 (org-re-property ".*?" 'literal t
)
6277 "Regular expression matching a property line.
6278 There are four matching groups:
6279 1: :PROPKEY: including the leading and trailing colon,
6280 2: PROPKEY without the leading and trailing colon,
6281 3: PROPVAL without leading or trailing spaces,
6282 4: the indentation of the current line,
6283 5: trailing whitespace.")
6285 (defvar org-font-lock-hook nil
6286 "Functions to be called for special font lock stuff.")
6288 (defvar org-font-lock-set-keywords-hook nil
6289 "Functions that can manipulate `org-font-lock-extra-keywords'.
6290 This is called after `org-font-lock-extra-keywords' is defined, but before
6291 it is installed to be used by font lock. This can be useful if something
6292 needs to be inserted at a specific position in the font-lock sequence.")
6294 (defun org-font-lock-hook (limit)
6295 "Run `org-font-lock-hook' within LIMIT."
6296 (run-hook-with-args 'org-font-lock-hook limit
))
6298 (defun org-set-font-lock-defaults ()
6299 "Set font lock defaults for the current buffer."
6300 (let* ((em org-fontify-emphasized-text
)
6301 (lk org-highlight-links
)
6302 (org-font-lock-extra-keywords
6305 '(org-font-lock-hook)
6307 `(,(if org-fontify-whole-heading-line
6308 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6309 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6310 (1 (org-get-level-face 1))
6311 (2 (org-get-level-face 2))
6312 (3 (org-get-level-face 3)))
6314 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6317 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t
))
6318 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t
))
6319 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t
))
6320 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t
))
6322 '(org-fontify-drawers)
6324 (list org-property-re
6325 '(1 'org-special-keyword t
)
6326 '(3 'org-property-value t
))
6328 (if (memq 'tag lk
) '(org-activate-tags (1 'org-tag prepend
)))
6329 (if (memq 'angle lk
) '(org-activate-angle-links (0 'org-link t
)))
6330 (if (memq 'plain lk
) '(org-activate-plain-links (0 'org-link t
)))
6331 (if (memq 'bracket lk
) '(org-activate-bracket-links (0 'org-link t
)))
6332 (if (memq 'radio lk
) '(org-activate-target-links (1 'org-link t
)))
6333 (if (memq 'date lk
) '(org-activate-dates (0 'org-date t
)))
6334 (if (memq 'footnote lk
) '(org-activate-footnote-links))
6336 (list org-any-target-regexp
'(0 'org-target t
))
6338 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t
))
6340 '(org-fontify-macros)
6341 '(org-hide-wide-columns (0 nil append
))
6343 (list (format org-heading-keyword-regexp-format
6345 '(2 (org-get-todo-face 2) t
))
6347 (if org-fontify-done-headline
6348 (list (format org-heading-keyword-regexp-format
6351 (mapconcat 'regexp-quote org-done-keywords
"\\|")
6353 '(2 'org-headline-done t
))
6356 '(org-font-lock-add-priority-faces)
6358 '(org-font-lock-add-tag-faces)
6360 (if (and org-group-tags org-tag-groups-alist
)
6361 (list (concat org-outline-regexp-bol
".+\\(:"
6362 (regexp-opt (mapcar 'car org-tag-groups-alist
))
6364 '(1 'org-tag-group prepend
)))
6366 (list (concat "\\<" org-comment-string
) '(0 'org-special-keyword t
))
6367 (list (concat "\\<" org-deadline-string
) '(0 'org-special-keyword t
))
6368 (list (concat "\\<" org-scheduled-string
) '(0 'org-special-keyword t
))
6369 (list (concat "\\<" org-closed-string
) '(0 'org-special-keyword t
))
6370 (list (concat "\\<" org-clock-string
) '(0 'org-special-keyword t
))
6373 (if (featurep 'xemacs
)
6374 '(org-do-emphasis-faces (0 nil append
))
6375 '(org-do-emphasis-faces)))
6377 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6378 1 'org-checkbox prepend
)
6379 (if (cdr (assq 'checkbox org-list-automatic-rules
))
6380 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6381 (0 (org-get-checkbox-statistics-face) t
)))
6382 ;; Description list items
6383 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6384 1 'org-list-dt prepend
)
6385 ;; ARCHIVEd headings
6387 org-outline-regexp-bol
6388 "\\(.*:" org-archive-tag
":.*\\)")
6389 '(1 'org-archived prepend
))
6391 '(org-do-latex-and-related)
6392 '(org-fontify-entities)
6393 '(org-raise-scripts)
6395 '(org-activate-code (1 'org-code t
))
6398 "^\\*\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6401 '(9 'org-special-keyword t
))
6402 ;; Blocks and meta lines
6403 '(org-fontify-meta-lines-and-blocks))))
6404 (setq org-font-lock-extra-keywords
(delq nil org-font-lock-extra-keywords
))
6405 (run-hooks 'org-font-lock-set-keywords-hook
)
6406 ;; Now set the full font-lock-keywords
6407 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords
)
6408 (org-set-local 'font-lock-defaults
6409 '(org-font-lock-keywords t nil nil backward-paragraph
))
6410 (kill-local-variable 'font-lock-keywords
) nil
))
6412 (defun org-toggle-pretty-entities ()
6413 "Toggle the composition display of entities as UTF8 characters."
6415 (org-set-local 'org-pretty-entities
(not org-pretty-entities
))
6416 (org-restart-font-lock)
6417 (if org-pretty-entities
6418 (message "Entities are now displayed as UTF8 characters")
6421 (org-decompose-region (point-min) (point-max))
6422 (message "Entities are now displayed as plain text"))))
6424 (defvar org-custom-properties-overlays nil
6425 "List of overlays used for custom properties.")
6426 (make-variable-buffer-local 'org-custom-properties-overlays
)
6428 (defun org-toggle-custom-properties-visibility ()
6429 "Display or hide properties in `org-custom-properties'."
6431 (if org-custom-properties-overlays
6432 (progn (mapc 'delete-overlay org-custom-properties-overlays
)
6433 (setq org-custom-properties-overlays nil
))
6434 (unless (not org-custom-properties
)
6438 (goto-char (point-min))
6439 (while (re-search-forward org-property-re nil t
)
6441 (when (equal p
(substring (match-string 1) 1 -
1))
6442 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6443 (overlay-put o
'invisible t
)
6444 (overlay-put o
'org-custom-property t
)
6445 (push o org-custom-properties-overlays
))))
6446 org-custom-properties
)))))))
6448 (defun org-fontify-entities (limit)
6449 "Find an entity to fontify."
6451 (when org-pretty-entities
6453 (while (re-search-forward
6454 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6456 (if (and (not (org-at-comment-p))
6457 (setq ee
(org-entity-get (match-string 1)))
6458 (= (length (nth 6 ee
)) 1))
6460 ((end (if (equal (match-string 2) "{}")
6463 (add-text-properties
6464 (match-beginning 0) end
6465 (list 'font-lock-fontified t
))
6466 (compose-region (match-beginning 0) end
6472 (defun org-fontify-like-in-org-mode (s &optional odd-levels
)
6473 "Fontify string S like in Org-mode."
6476 (let ((org-odd-levels-only odd-levels
))
6484 (defun org-get-level-face (n)
6485 "Get the right face for match N in font-lock matching of headlines."
6486 (setq org-l
(- (match-end 2) (match-beginning 1) 1))
6487 (if org-odd-levels-only
(setq org-l
(1+ (/ org-l
2))))
6488 (if org-cycle-level-faces
6489 (setq org-f
(nth (%
(1- org-l
) org-n-level-faces
) org-level-faces
))
6490 (setq org-f
(nth (1- (min org-l org-n-level-faces
)) org-level-faces
)))
6492 ((eq n
1) (if org-hide-leading-stars
'org-hide org-f
))
6494 (t (if org-level-color-stars-only nil org-f
))))
6497 (defun org-get-todo-face (kwd)
6498 "Get the right face for a TODO keyword KWD.
6499 If KWD is a number, get the corresponding match group."
6500 (if (numberp kwd
) (setq kwd
(match-string kwd
)))
6501 (or (org-face-from-face-or-color
6502 'todo
'org-todo
(cdr (assoc kwd org-todo-keyword-faces
)))
6503 (and (member kwd org-done-keywords
) 'org-done
)
6506 (defun org-face-from-face-or-color (context inherit face-or-color
)
6507 "Create a face list that inherits INHERIT, but sets the foreground color.
6508 When FACE-OR-COLOR is not a string, just return it."
6509 (if (stringp face-or-color
)
6510 (list :inherit inherit
6511 (cdr (assoc context org-faces-easy-properties
))
6515 (defun org-font-lock-add-tag-faces (limit)
6516 "Add the special tag faces."
6517 (when (and org-tag-faces org-tags-special-faces-re
)
6518 (while (re-search-forward org-tags-special-faces-re limit t
)
6519 (add-text-properties (match-beginning 1) (match-end 1)
6520 (list 'face
(org-get-tag-face 1)
6521 'font-lock-fontified t
))
6522 (backward-char 1))))
6524 (defun org-font-lock-add-priority-faces (limit)
6525 "Add the special priority faces."
6526 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t
)
6527 (when (save-match-data (org-at-heading-p))
6528 (add-text-properties
6529 (match-beginning 0) (match-end 0)
6530 (list 'face
(or (org-face-from-face-or-color
6531 'priority
'org-priority
6532 (cdr (assoc (char-after (match-beginning 1))
6533 org-priority-faces
)))
6535 'font-lock-fontified t
)))))
6537 (defun org-get-tag-face (kwd)
6538 "Get the right face for a TODO keyword KWD.
6539 If KWD is a number, get the corresponding match group."
6540 (if (numberp kwd
) (setq kwd
(match-string kwd
)))
6541 (or (org-face-from-face-or-color
6542 'tag
'org-tag
(cdr (assoc kwd org-tag-faces
)))
6545 (defun org-unfontify-region (beg end
&optional maybe_loudly
)
6546 "Remove fontification and activation overlays from links."
6547 (font-lock-default-unfontify-region beg end
)
6548 (let* ((buffer-undo-list t
)
6549 (inhibit-read-only t
) (inhibit-point-motion-hooks t
)
6550 (inhibit-modification-hooks t
)
6551 deactivate-mark buffer-file-name buffer-file-truename
)
6552 (org-decompose-region beg end
)
6553 (remove-text-properties beg end
6554 '(mouse-face t keymap t org-linked-text t
6555 invisible t intangible t
6557 (org-remove-font-lock-display-properties beg end
)))
6559 (defconst org-script-display
'(((raise -
0.3) (height 0.7))
6560 ((raise 0.3) (height 0.7))
6563 "Display properties for showing superscripts and subscripts.")
6565 (defun org-remove-font-lock-display-properties (beg end
)
6566 "Remove specific display properties that have been added by font lock.
6567 The will remove the raise properties that are used to show superscripts
6571 (setq next
(next-single-property-change beg
'display nil end
)
6572 prop
(get-text-property beg
'display
))
6573 (if (member prop org-script-display
)
6574 (put-text-property beg next
'display nil
))
6577 (defun org-raise-scripts (limit)
6578 "Add raise properties to sub/superscripts."
6579 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
)
6580 (if (re-search-forward
6581 (if (eq org-use-sub-superscripts t
)
6582 org-match-substring-regexp
6583 org-match-substring-with-braces-regexp
)
6585 (let* ((pos (point)) table-p comment-p
6586 (mpos (match-beginning 3))
6587 (emph-p (get-text-property mpos
'org-emphasis
))
6588 (link-p (get-text-property mpos
'mouse-face
))
6589 (keyw-p (eq 'org-special-keyword
(get-text-property mpos
'face
))))
6590 (goto-char (point-at-bol))
6591 (setq table-p
(org-looking-at-p org-table-dataline-regexp
)
6592 comment-p
(org-looking-at-p "^[ \t]*#[ +]"))
6595 (if (member (char-after) '(?_ ?^
)) (goto-char (1- pos
)))
6596 (if (or comment-p emph-p link-p keyw-p
)
6598 (put-text-property (match-beginning 3) (match-end 0)
6600 (if (equal (char-after (match-beginning 2)) ?^
)
6601 (nth (if table-p
3 1) org-script-display
)
6602 (nth (if table-p
2 0) org-script-display
)))
6603 (add-text-properties (match-beginning 2) (match-end 2)
6605 'org-dwidth t
'org-dwidth-n
1))
6606 (if (and (eq (char-after (match-beginning 3)) ?
{)
6607 (eq (char-before (match-end 3)) ?
}))
6609 (add-text-properties
6610 (match-beginning 3) (1+ (match-beginning 3))
6611 (list 'invisible t
'org-dwidth t
'org-dwidth-n
1))
6612 (add-text-properties
6613 (1- (match-end 3)) (match-end 3)
6614 (list 'invisible t
'org-dwidth t
'org-dwidth-n
1))))
6617 ;;;; Visibility cycling, including org-goto and indirect buffer
6621 (defvar org-cycle-global-status nil
)
6622 (make-variable-buffer-local 'org-cycle-global-status
)
6623 (put 'org-cycle-global-status
'org-state t
)
6624 (defvar org-cycle-subtree-status nil
)
6625 (make-variable-buffer-local 'org-cycle-subtree-status
)
6626 (put 'org-cycle-subtree-status
'org-state t
)
6628 (defvar org-inlinetask-min-level
)
6630 (defun org-unlogged-message (&rest args
)
6631 "Display a message, but avoid logging it in the *Messages* buffer."
6632 (let ((message-log-max nil
))
6633 (apply 'message args
)))
6636 (defun org-cycle (&optional arg
)
6637 "TAB-action and visibility cycling for Org-mode.
6639 This is the command invoked in Org-mode by the TAB key. Its main purpose
6640 is outline visibility cycling, but it also invokes other actions
6641 in special contexts.
6643 - When this function is called with a prefix argument, rotate the entire
6644 buffer through 3 states (global cycling)
6645 1. OVERVIEW: Show only top-level headlines.
6646 2. CONTENTS: Show all headlines of all levels, but no body text.
6647 3. SHOW ALL: Show everything.
6648 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6649 determined by the variable `org-startup-folded', and by any VISIBILITY
6650 properties in the buffer.
6651 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6652 including any drawers.
6654 - When inside a table, re-align the table and move to the next field.
6656 - When point is at the beginning of a headline, rotate the subtree started
6657 by this line through 3 different states (local cycling)
6658 1. FOLDED: Only the main headline is shown.
6659 2. CHILDREN: The main headline and the direct children are shown.
6660 From this state, you can move to one of the children
6661 and zoom in further.
6662 3. SUBTREE: Show the entire subtree, including body text.
6663 If there is no subtree, switch directly from CHILDREN to FOLDED.
6665 - When point is at the beginning of an empty headline and the variable
6666 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6667 of the headline by demoting and promoting it to likely levels. This
6668 speeds up creation document structure by pressing TAB once or several
6669 times right after creating a new headline.
6671 - When there is a numeric prefix, go up to a heading with level ARG, do
6672 a `show-subtree' and return to the previous cursor position. If ARG
6673 is negative, go up that many levels.
6675 - When point is not at the beginning of a headline, execute the global
6676 binding for TAB, which is re-indenting the line. See the option
6677 `org-cycle-emulate-tab' for details.
6679 - Special case: if point is at the beginning of the buffer and there is
6680 no headline in line 1, this function will act as if called with prefix arg
6681 (C-u TAB, same as S-TAB) also when called without prefix arg.
6682 But only if also the variable `org-cycle-global-at-bob' is t."
6684 (org-load-modules-maybe)
6685 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook
)
6686 (and org-cycle-level-after-item
/entry-creation
6687 (or (org-cycle-level)
6688 (org-cycle-item-indentation))))
6690 (or org-cycle-max-level
6691 (and (boundp 'org-inlinetask-min-level
)
6692 org-inlinetask-min-level
6693 (1- org-inlinetask-min-level
))))
6694 (nstars (and limit-level
6695 (if org-odd-levels-only
6696 (and limit-level
(1- (* limit-level
2)))
6699 (if (not (derived-mode-p 'org-mode
))
6701 (concat "\\*" (if nstars
(format "\\{1,%d\\} " nstars
) "+ "))))
6702 (bob-special (and org-cycle-global-at-bob
(not arg
) (bobp)
6703 (not (looking-at org-outline-regexp
))))
6706 (delq 'org-optimize-window-after-visibility-change
6707 (copy-sequence org-cycle-hook
))
6711 (if (or bob-special
(equal arg
'(4)))
6712 ;; special case: use global cycling
6718 (setq last-command
'dummy
)
6719 (org-set-startup-visibility)
6720 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6724 (org-unlogged-message "Entire buffer visible, including drawers"))
6726 ;; Try cdlatex TAB completion
6727 ((org-try-cdlatex-tab))
6729 ;; Table: enter it or move to the next field.
6730 ((org-at-table-p 'any
)
6731 (if (org-at-table.el-p
)
6732 (message "Use C-c ' to edit table.el tables")
6733 (if arg
(org-table-edit-field t
)
6734 (org-table-justify-field-maybe)
6735 (call-interactively 'org-table-next-field
))))
6737 ((run-hook-with-args-until-success
6738 'org-tab-after-check-for-table-hook
))
6740 ;; Global cycling: delegate to `org-cycle-internal-global'.
6741 ((eq arg t
) (org-cycle-internal-global))
6743 ;; Drawers: delegate to `org-flag-drawer'.
6745 (beginning-of-line 1)
6746 (looking-at org-drawer-regexp
))
6747 (org-flag-drawer ; toggle block visibility
6748 (not (get-char-property (match-end 0) 'invisible
))))
6750 ;; Show-subtree, ARG levels up from here.
6753 (org-back-to-heading)
6754 (outline-up-heading (if (< arg
0) (- arg
)
6755 (- (funcall outline-level
) arg
)))
6756 (org-show-subtree)))
6758 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6759 ((and (featurep 'org-inlinetask
)
6760 (org-inlinetask-at-task-p)
6761 (or (bolp) (not (eq org-cycle-emulate-tab
'exc-hl-bol
))))
6762 (org-inlinetask-toggle-visibility))
6764 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6765 ((and (or (and org-cycle-include-plain-lists
(org-at-item-p))
6766 (save-excursion (beginning-of-line 1)
6767 (looking-at org-outline-regexp
)))
6768 (or (bolp) (not (eq org-cycle-emulate-tab
'exc-hl-bol
))))
6769 (org-cycle-internal-local))
6771 ;; From there: TAB emulation and template completion.
6772 (buffer-read-only (org-back-to-heading))
6774 ((run-hook-with-args-until-success
6775 'org-tab-after-check-for-cycling-hook
))
6777 ((org-try-structure-completion))
6779 ((run-hook-with-args-until-success
6780 'org-tab-before-tab-emulation-hook
))
6782 ((and (eq org-cycle-emulate-tab
'exc-hl-bol
)
6784 (not (looking-at org-outline-regexp
))))
6785 (call-interactively (global-key-binding "\t")))
6787 ((if (and (memq org-cycle-emulate-tab
'(white whitestart
))
6788 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6789 (or (and (eq org-cycle-emulate-tab
'white
)
6790 (= (match-end 0) (point-at-eol)))
6791 (and (eq org-cycle-emulate-tab
'whitestart
)
6792 (>= (match-end 0) pos
))))
6794 (eq org-cycle-emulate-tab t
))
6795 (call-interactively (global-key-binding "\t")))
6798 (org-back-to-heading)
6801 (defun org-cycle-internal-global ()
6802 "Do the global cycling action."
6803 ;; Hack to avoid display of messages for .org attachments in Gnus
6804 (let ((ga (string-match "\\*fontification" (buffer-name))))
6806 ((and (eq last-command this-command
)
6807 (eq org-cycle-global-status
'overview
))
6808 ;; We just created the overview - now do table of contents
6809 ;; This can be slow in very large buffers, so indicate action
6810 (run-hook-with-args 'org-pre-cycle-hook
'contents
)
6811 (unless ga
(org-unlogged-message "CONTENTS..."))
6813 (unless ga
(org-unlogged-message "CONTENTS...done"))
6814 (setq org-cycle-global-status
'contents
)
6815 (run-hook-with-args 'org-cycle-hook
'contents
))
6817 ((and (eq last-command this-command
)
6818 (eq org-cycle-global-status
'contents
))
6819 ;; We just showed the table of contents - now show everything
6820 (run-hook-with-args 'org-pre-cycle-hook
'all
)
6822 (unless ga
(org-unlogged-message "SHOW ALL"))
6823 (setq org-cycle-global-status
'all
)
6824 (run-hook-with-args 'org-cycle-hook
'all
))
6827 ;; Default action: go to overview
6828 (run-hook-with-args 'org-pre-cycle-hook
'overview
)
6830 (unless ga
(org-unlogged-message "OVERVIEW"))
6831 (setq org-cycle-global-status
'overview
)
6832 (run-hook-with-args 'org-cycle-hook
'overview
)))))
6834 (defvar org-called-with-limited-levels nil
6835 "Non-nil when `org-with-limited-levels' is currently active.")
6837 (defun org-cycle-internal-local ()
6838 "Do the local cycling action."
6839 (let ((goal-column 0) eoh eol eos has-children children-skipped struct
)
6840 ;; First, determine end of headline (EOH), end of subtree or item
6841 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6846 (setq struct
(org-list-struct))
6847 (setq eoh
(point-at-eol))
6848 (setq eos
(org-list-get-item-end-before-blank (point) struct
))
6849 (setq has-children
(org-list-has-child-p (point) struct
)))
6850 (org-back-to-heading)
6851 (setq eoh
(save-excursion (outline-end-of-heading) (point)))
6852 (setq eos
(save-excursion (org-end-of-subtree t t
)
6853 (when (bolp) (backward-char)) (point)))
6856 (let ((level (funcall outline-level
)))
6857 (outline-next-heading)
6858 (and (org-at-heading-p t
)
6859 (> (funcall outline-level
) level
))))
6861 (org-list-search-forward (org-item-beginning-re) eos t
)))))
6862 ;; Determine end invisible part of buffer (EOL)
6863 (beginning-of-line 2)
6864 ;; XEmacs doesn't have `next-single-char-property-change'
6865 (if (featurep 'xemacs
)
6866 (while (and (not (eobp)) ;; this is like `next-line'
6867 (get-char-property (1- (point)) 'invisible
))
6868 (beginning-of-line 2))
6869 (while (and (not (eobp)) ;; this is like `next-line'
6870 (get-char-property (1- (point)) 'invisible
))
6871 (goto-char (next-single-char-property-change (point) 'invisible
))
6872 (and (eolp) (beginning-of-line 2))))
6874 ;; Find out what to do next and set `this-command'
6877 ;; Nothing is hidden behind this heading
6878 (unless (org-before-first-heading-p)
6879 (run-hook-with-args 'org-pre-cycle-hook
'empty
))
6880 (org-unlogged-message "EMPTY ENTRY")
6881 (setq org-cycle-subtree-status nil
)
6884 (outline-next-heading)
6885 (if (outline-invisible-p) (org-flag-heading nil
))))
6886 ((and (or (>= eol eos
)
6887 (not (string-match "\\S-" (buffer-substring eol eos
))))
6889 (not (setq children-skipped
6890 org-cycle-skip-children-state-if-no-children
))))
6891 ;; Entire subtree is hidden in one line: children view
6892 (unless (org-before-first-heading-p)
6893 (run-hook-with-args 'org-pre-cycle-hook
'children
))
6895 (org-list-set-item-visibility (point-at-bol) struct
'children
)
6897 (org-with-limited-levels (show-children))
6898 ;; FIXME: This slows down the func way too much.
6899 ;; How keep drawers hidden in subtree anyway?
6900 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6901 ;; (org-cycle-hide-drawers 'subtree))
6903 ;; Fold every list in subtree to top-level items.
6904 (when (eq org-cycle-include-plain-lists
'integrate
)
6906 (org-back-to-heading)
6907 (while (org-list-search-forward (org-item-beginning-re) eos t
)
6908 (beginning-of-line 1)
6909 (let* ((struct (org-list-struct))
6910 (prevs (org-list-prevs-alist struct
))
6911 (end (org-list-get-bottom-point struct
)))
6912 (mapc (lambda (e) (org-list-set-item-visibility e struct
'folded
))
6913 (org-list-get-all-items (point) struct prevs
))
6914 (goto-char (if (< end eos
) end eos
)))))))
6915 (org-unlogged-message "CHILDREN")
6918 (outline-next-heading)
6919 (if (outline-invisible-p) (org-flag-heading nil
)))
6920 (setq org-cycle-subtree-status
'children
)
6921 (unless (org-before-first-heading-p)
6922 (run-hook-with-args 'org-cycle-hook
'children
)))
6923 ((or children-skipped
6924 (and (eq last-command this-command
)
6925 (eq org-cycle-subtree-status
'children
)))
6926 ;; We just showed the children, or no children are there,
6927 ;; now show everything.
6928 (unless (org-before-first-heading-p)
6929 (run-hook-with-args 'org-pre-cycle-hook
'subtree
))
6930 (outline-flag-region eoh eos nil
)
6931 (org-unlogged-message
6932 (if children-skipped
"SUBTREE (NO CHILDREN)" "SUBTREE"))
6933 (setq org-cycle-subtree-status
'subtree
)
6934 (unless (org-before-first-heading-p)
6935 (run-hook-with-args 'org-cycle-hook
'subtree
)))
6937 ;; Default action: hide the subtree.
6938 (run-hook-with-args 'org-pre-cycle-hook
'folded
)
6939 (outline-flag-region eoh eos t
)
6940 (org-unlogged-message "FOLDED")
6941 (setq org-cycle-subtree-status
'folded
)
6942 (unless (org-before-first-heading-p)
6943 (run-hook-with-args 'org-cycle-hook
'folded
))))))
6946 (defun org-global-cycle (&optional arg
)
6947 "Cycle the global visibility. For details see `org-cycle'.
6948 With \\[universal-argument] prefix arg, switch to startup visibility.
6949 With a numeric prefix, show all headlines up to that level."
6951 (let ((org-cycle-include-plain-lists
6952 (if (derived-mode-p 'org-mode
) org-cycle-include-plain-lists nil
)))
6956 (hide-sublevels arg
)
6957 (setq org-cycle-global-status
'contents
))
6959 (org-set-startup-visibility)
6960 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6962 (org-cycle '(4))))))
6964 (defun org-set-startup-visibility ()
6965 "Set the visibility required by startup options and properties."
6967 ((eq org-startup-folded t
)
6969 ((eq org-startup-folded
'content
)
6971 ((or (eq org-startup-folded
'showeverything
)
6972 (eq org-startup-folded nil
))
6974 (unless (eq org-startup-folded
'showeverything
)
6975 (if org-hide-block-startup
(org-hide-block-all))
6976 (org-set-visibility-according-to-property 'no-cleanup
)
6977 (org-cycle-hide-archived-subtrees 'all
)
6978 (org-cycle-hide-drawers 'all
)
6979 (org-cycle-show-empty-lines t
)))
6981 (defun org-set-visibility-according-to-property (&optional no-cleanup
)
6982 "Switch subtree visibilities according to :VISIBILITY: property."
6984 (let (org-show-entry-below state
)
6986 (goto-char (point-min))
6987 (while (re-search-forward
6988 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6990 (setq state
(match-string 1))
6992 (org-back-to-heading t
)
6996 ((equal state
'("fold" "folded"))
6998 ((equal state
"children")
6999 (org-show-hidden-entry)
7001 ((equal state
"content")
7004 (org-narrow-to-subtree)
7006 ((member state
'("all" "showall"))
7009 (org-cycle-hide-archived-subtrees 'all
)
7010 (org-cycle-hide-drawers 'all
)
7011 (org-cycle-show-empty-lines 'all
)))))
7013 ;; This function uses outline-regexp instead of the more fundamental
7014 ;; org-outline-regexp so that org-cycle-global works outside of Org
7015 ;; buffers, where outline-regexp is needed.
7016 (defun org-overview ()
7017 "Switch to overview mode, showing only top-level headlines.
7018 This shows all headlines with a level equal or greater than the level
7019 of the first headline in the buffer. This is important, because if the
7020 first headline is not level one, then (hide-sublevels 1) gives confusing
7026 (goto-char (point-min))
7027 (if (re-search-forward (concat "^" outline-regexp
) nil t
)
7029 (goto-char (match-beginning 0))
7030 (funcall outline-level
))))))
7031 (and level
(hide-sublevels level
)))))
7033 (defun org-content (&optional arg
)
7034 "Show all headlines in the buffer, like a table of contents.
7035 With numerical argument N, show content up to level N."
7039 ;; Visit all headings and show their offspring
7040 (and (integerp arg
) (org-overview))
7041 (goto-char (point-max))
7043 (while (and (progn (condition-case nil
7044 (outline-previous-visible-heading 1)
7045 (error (goto-char (point-min))))
7047 (looking-at org-outline-regexp
))
7049 (show-children (1- arg
))
7051 (if (bobp) (throw 'exit nil
))))))
7053 (defun org-optimize-window-after-visibility-change (state)
7054 "Adjust the window after a change in outline visibility.
7055 This function is the default value of the hook `org-cycle-hook'."
7056 (when (get-buffer-window (current-buffer))
7058 ((eq state
'content
) nil
)
7059 ((eq state
'all
) nil
)
7060 ((eq state
'folded
) nil
)
7061 ((eq state
'children
) (or (org-subtree-end-visible-p) (recenter 1)))
7062 ((eq state
'subtree
) (or (org-subtree-end-visible-p) (recenter 1))))))
7064 (defun org-remove-empty-overlays-at (pos)
7065 "Remove outline overlays that do not contain non-white stuff."
7068 (and (eq 'outline
(overlay-get o
'invisible
))
7069 (not (string-match "\\S-" (buffer-substring (overlay-start o
)
7071 (delete-overlay o
)))
7074 (defun org-clean-visibility-after-subtree-move ()
7075 "Fix visibility issues after moving a subtree."
7076 ;; First, find a reasonable region to look at:
7077 ;; Start two siblings above, end three below
7078 (let* ((beg (save-excursion
7079 (and (org-get-last-sibling)
7080 (org-get-last-sibling))
7082 (end (save-excursion
7083 (and (org-get-next-sibling)
7084 (org-get-next-sibling)
7085 (org-get-next-sibling))
7086 (if (org-at-heading-p)
7089 (level (looking-at "\\*+"))
7090 (re (if level
(concat "^" (regexp-quote (match-string 0)) " "))))
7093 (narrow-to-region beg end
)
7095 ;; Properly fold already folded siblings
7096 (goto-char (point-min))
7097 (while (re-search-forward re nil t
)
7098 (if (and (not (outline-invisible-p))
7100 (goto-char (point-at-eol)) (outline-invisible-p)))
7102 (org-cycle-show-empty-lines 'overview
)
7103 (org-cycle-hide-drawers 'overview
)))))
7105 (defun org-cycle-show-empty-lines (state)
7106 "Show empty lines above all visible headlines.
7107 The region to be covered depends on STATE when called through
7108 `org-cycle-hook'. Lisp program can use t for STATE to get the
7109 entire buffer covered. Note that an empty line is only shown if there
7110 are at least `org-cycle-separator-lines' empty lines before the headline."
7111 (when (not (= org-cycle-separator-lines
0))
7113 (let* ((n (abs org-cycle-separator-lines
))
7115 ((= n
1) "\\(\n[ \t]*\n\\*+\\) ")
7116 ((= n
2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7117 (t (let ((ns (number-to-string (- n
2))))
7118 (concat "^\\(?:[ \t]*\n\\)\\{" ns
"," ns
"\\}"
7119 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7122 ((memq state
'(overview contents t
))
7123 (setq beg
(point-min) end
(point-max)))
7124 ((memq state
'(children folded
))
7125 (setq beg
(point) end
(progn (org-end-of-subtree t t
)
7126 (beginning-of-line 2)
7130 (while (re-search-forward re end t
)
7131 (unless (get-char-property (match-end 1) 'invisible
)
7132 (setq e
(match-end 1))
7133 (if (< org-cycle-separator-lines
0)
7134 (setq b
(save-excursion
7135 (goto-char (match-beginning 0))
7136 (org-back-over-empty-lines)
7138 (goto-char (max (point-min) (1- (point))))
7142 (setq b
(match-beginning 1)))
7143 (outline-flag-region b e nil
)))))))
7144 ;; Never hide empty lines at the end of the file.
7146 (goto-char (point-max))
7147 (outline-previous-heading)
7148 (outline-end-of-heading)
7149 (if (and (looking-at "[ \t\n]+")
7150 (= (match-end 0) (point-max)))
7151 (outline-flag-region (point) (match-end 0) nil
))))
7153 (defun org-show-empty-lines-in-parent ()
7154 "Move to the parent and re-show empty lines before visible headlines."
7156 (let ((context (if (org-up-heading-safe) 'children
'overview
)))
7157 (org-cycle-show-empty-lines context
))))
7159 (defun org-files-list ()
7160 "Return `org-agenda-files' list, plus all open org-mode files.
7161 This is useful for operations that need to scan all of a user's
7162 open and agenda-wise Org files."
7163 (let ((files (mapcar 'expand-file-name
(org-agenda-files))))
7164 (dolist (buf (buffer-list))
7165 (with-current-buffer buf
7166 (if (and (derived-mode-p 'org-mode
) (buffer-file-name))
7167 (let ((file (expand-file-name (buffer-file-name))))
7168 (unless (member file files
)
7169 (push file files
))))))
7172 (defsubst org-entry-beginning-position
()
7173 "Return the beginning position of the current entry."
7174 (save-excursion (outline-back-to-heading t
) (point)))
7176 (defsubst org-entry-end-position
()
7177 "Return the end position of the current entry."
7178 (save-excursion (outline-next-heading) (point)))
7180 (defun org-cycle-hide-drawers (state &optional exceptions
)
7181 "Re-hide all drawers after a visibility state change.
7182 When non-nil, optional argument EXCEPTIONS is a list of strings
7183 specifying which drawers should not be hidden."
7184 (when (and (derived-mode-p 'org-mode
)
7185 (not (memq state
'(overview folded contents
))))
7187 (let* ((globalp (memq state
'(contents all
)))
7188 (beg (if globalp
(point-min) (point)))
7189 (end (if globalp
(point-max)
7190 (if (eq state
'children
)
7191 (save-excursion (outline-next-heading) (point))
7192 (org-end-of-subtree t
)))))
7194 (while (re-search-forward org-drawer-regexp
(max end
(point)) t
)
7195 (unless (member-ignore-case (match-string 1) exceptions
)
7196 (let ((drawer (org-element-at-point)))
7197 (when (memq (org-element-type drawer
) '(drawer property-drawer
))
7198 (org-flag-drawer t drawer
)
7199 ;; Make sure to skip drawer entirely or we might flag
7200 ;; it another time when matching its ending line with
7201 ;; `org-drawer-regexp'.
7202 (goto-char (org-element-property :end drawer
))))))))))
7204 (defun org-cycle-hide-inline-tasks (state)
7205 "Re-hide inline tasks when switching to 'contents or 'children
7209 (when (org-bound-and-true-p org-inlinetask-min-level
)
7210 (hide-sublevels (1- org-inlinetask-min-level
))))
7212 (when (featurep 'org-inlinetask
)
7214 (while (and (outline-next-heading)
7215 (org-inlinetask-at-task-p))
7216 (org-inlinetask-toggle-visibility)
7217 (org-inlinetask-goto-end)))))))
7219 (defun org-flag-drawer (flag &optional element
)
7220 "When FLAG is non-nil, hide the drawer we are at.
7221 Otherwise make it visible. When optional argument ELEMENT is
7222 a parsed drawer, as returned by `org-element-at-point', hide or
7223 show that drawer instead."
7224 (when (save-excursion
7226 (org-looking-at-p org-drawer-regexp
))
7227 (let ((drawer (or element
(org-element-at-point))))
7228 (when (memq (org-element-type drawer
) '(drawer property-drawer
))
7229 (let ((post (org-element-property :post-affiliated drawer
)))
7231 (outline-flag-region
7232 (progn (goto-char post
) (line-end-position))
7233 (progn (goto-char (org-element-property :end drawer
))
7234 (skip-chars-backward " \r\t\n")
7235 (line-end-position))
7237 ;; When the drawer is hidden away, make sure point lies in
7238 ;; a visible part of the buffer.
7239 (when (and flag
(> (line-beginning-position) post
))
7240 (goto-char post
)))))))
7242 (defun org-subtree-end-visible-p ()
7243 "Is the end of the current subtree visible?"
7244 (pos-visible-in-window-p
7245 (save-excursion (org-end-of-subtree t
) (point))))
7247 (defun org-first-headline-recenter ()
7248 "Move cursor to the first headline and recenter the headline."
7249 (goto-char (point-min))
7250 (when (re-search-forward (concat "^\\(" org-outline-regexp
"\\)") nil t
)
7251 (set-window-start (selected-window) (point-at-bol))))
7253 ;;; Saving and restoring visibility
7255 (defun org-outline-overlay-data (&optional use-markers
)
7256 "Return a list of the locations of all outline overlays.
7257 These are overlays with the `invisible' property value `outline'.
7258 The return value is a list of cons cells, with start and stop
7259 positions for each overlay.
7260 If USE-MARKERS is set, return the positions as markers."
7267 (when (eq (overlay-get o
'invisible
) 'outline
)
7268 (setq beg
(overlay-start o
)
7269 end
(overlay-end o
))
7270 (and beg end
(> end beg
)
7272 (cons (copy-marker beg
)
7273 (copy-marker end t
))
7275 (overlays-in (point-min) (point-max))))))))
7277 (defun org-set-outline-overlay-data (data)
7278 "Create visibility overlays for all positions in DATA.
7279 DATA should have been made by `org-outline-overlay-data'."
7286 (outline-flag-region (car c
) (cdr c
) t
))
7289 ;;; Folding of blocks
7291 (defvar org-hide-block-overlays nil
7292 "Overlays hiding blocks.")
7293 (make-variable-buffer-local 'org-hide-block-overlays
)
7295 (defun org-block-map (function &optional start end
)
7296 "Call FUNCTION at the head of all source blocks in the current buffer.
7297 Optional arguments START and END can be used to limit the range."
7298 (let ((start (or start
(point-min)))
7299 (end (or end
(point-max))))
7302 (while (and (< (point) end
) (re-search-forward org-block-regexp end t
))
7305 (goto-char (match-beginning 0))
7306 (funcall function
)))))))
7308 (defun org-hide-block-toggle-all ()
7309 "Toggle the visibility of all blocks in the current buffer."
7310 (org-block-map 'org-hide-block-toggle
))
7312 (defun org-hide-block-all ()
7313 "Fold all blocks in the current buffer."
7315 (org-show-block-all)
7316 (org-block-map 'org-hide-block-toggle-maybe
))
7318 (defun org-show-block-all ()
7319 "Unfold all blocks in the current buffer."
7321 (mapc 'delete-overlay org-hide-block-overlays
)
7322 (setq org-hide-block-overlays nil
))
7324 (defun org-hide-block-toggle-maybe ()
7325 "Toggle visibility of block at point."
7327 (let ((case-fold-search t
))
7329 (beginning-of-line 1)
7330 (looking-at org-block-regexp
))
7331 (progn (org-hide-block-toggle)
7332 t
) ;; to signal that we took action
7333 nil
))) ;; to signal that we did not
7335 (defun org-hide-block-toggle (&optional force
)
7336 "Toggle the visibility of the current block.
7337 When optional argument FORCE is `off', make block visible. If it
7338 is non-nil, hide it unconditionally."
7340 (let ((element (org-element-at-point)))
7341 (unless (memq (org-element-type element
)
7342 '(center-block comment-block example-block quote-block
7343 src-block verse-block
))
7344 (user-error "Not at a block"))
7345 (let* ((start (save-excursion
7346 (goto-char (org-element-property :post-affiliated element
))
7347 (line-end-position)))
7348 (end (save-excursion
7349 (goto-char (org-element-property :end element
))
7350 (skip-chars-backward " \r\t\n")
7351 (line-end-position)))
7352 (overlays (overlays-at start
)))
7354 ;; Do nothing when not before or at the block opening line or
7355 ;; at the block closing line.
7356 ((let ((eol (line-end-position)))
7357 (and (> eol start
) (/= eol end
))))
7358 ((and (not (eq force
'off
))
7359 (not (memq t
(mapcar
7361 (eq (overlay-get o
'invisible
) 'org-hide-block
))
7363 (let ((ov (make-overlay start end
)))
7364 (overlay-put ov
'invisible
'org-hide-block
)
7365 ;; Make the block accessible to `isearch'.
7367 ov
'isearch-open-invisible
7369 (when (memq ov org-hide-block-overlays
)
7370 (setq org-hide-block-overlays
(delq ov org-hide-block-overlays
)))
7371 (when (eq (overlay-get ov
'invisible
) 'org-hide-block
)
7372 (delete-overlay ov
))))
7373 (push ov org-hide-block-overlays
)
7374 ;; When the block is hidden away, make sure point is left in
7375 ;; a visible part of the buffer.
7376 (when (> (line-beginning-position) start
)
7378 (beginning-of-line))))
7379 ((or (not force
) (eq force
'off
))
7380 (dolist (ov overlays
)
7381 (when (memq ov org-hide-block-overlays
)
7382 (setq org-hide-block-overlays
(delq ov org-hide-block-overlays
)))
7383 (when (eq (overlay-get ov
'invisible
) 'org-hide-block
)
7384 (delete-overlay ov
))))))))
7386 ;; org-tab-after-check-for-cycling-hook
7387 (add-hook 'org-tab-first-hook
'org-hide-block-toggle-maybe
)
7388 ;; Remove overlays when changing major mode
7389 (add-hook 'org-mode-hook
7390 (lambda () (org-add-hook 'change-major-mode-hook
7391 'org-show-block-all
'append
'local
)))
7395 (defvar org-goto-window-configuration nil
)
7396 (defvar org-goto-marker nil
)
7397 (defvar org-goto-map
)
7398 (defun org-goto-map ()
7399 "Set the keymap `org-goto'."
7401 (let ((map (make-sparse-keymap)))
7402 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7403 mouse-drag-region universal-argument org-occur
))
7405 (while (setq cmd
(pop cmds
))
7406 (substitute-key-definition cmd cmd map global-map
)))
7407 (suppress-keymap map
)
7408 (org-defkey map
"\C-m" 'org-goto-ret
)
7409 (org-defkey map
[(return)] 'org-goto-ret
)
7410 (org-defkey map
[(left)] 'org-goto-left
)
7411 (org-defkey map
[(right)] 'org-goto-right
)
7412 (org-defkey map
[(control ?g
)] 'org-goto-quit
)
7413 (org-defkey map
"\C-i" 'org-cycle
)
7414 (org-defkey map
[(tab)] 'org-cycle
)
7415 (org-defkey map
[(down)] 'outline-next-visible-heading
)
7416 (org-defkey map
[(up)] 'outline-previous-visible-heading
)
7417 (if org-goto-auto-isearch
7418 (if (fboundp 'define-key-after
)
7419 (define-key-after map
[t] 'org-goto-local-auto-isearch)
7421 (org-defkey map "q" 'org-goto-quit)
7422 (org-defkey map "n" 'outline-next-visible-heading)
7423 (org-defkey map "p" 'outline-previous-visible-heading)
7424 (org-defkey map "f" 'outline-forward-same-level)
7425 (org-defkey map "b" 'outline-backward-same-level)
7426 (org-defkey map "u" 'outline-up-heading))
7427 (org-defkey map "/" 'org-occur)
7428 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7429 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7430 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7431 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7432 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7435 (defconst org-goto-help
7436 "Browse buffer copy, to find location or copy text.%s
7437 RET=jump to location C-g=quit and return to previous location
7438 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7440 (defvar org-goto-start-pos) ; dynamically scoped parameter
7442 (defun org-goto (&optional alternative-interface)
7443 "Look up a different location in the current file, keeping current visibility.
7445 When you want look-up or go to a different location in a
7446 document, the fastest way is often to fold the entire buffer and
7447 then dive into the tree. This method has the disadvantage, that
7448 the previous location will be folded, which may not be what you
7451 This command works around this by showing a copy of the current
7452 buffer in an indirect buffer, in overview mode. You can dive
7453 into the tree in that copy, use org-occur and incremental search
7454 to find a location. When pressing RET or `Q', the command
7455 returns to the original buffer in which the visibility is still
7456 unchanged. After RET it will also jump to the location selected
7457 in the indirect buffer and expose the headline hierarchy above.
7459 With a prefix argument, use the alternative interface: e.g. if
7460 `org-goto-interface' is 'outline use 'outline-path-completion."
7463 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7464 (org-refile-use-outline-path t)
7465 (org-refile-target-verify-function nil)
7467 (if (not alternative-interface)
7469 (if (eq org-goto-interface 'outline)
7470 'outline-path-completion
7472 (org-goto-start-pos (point))
7474 (if (eq interface 'outline)
7475 (car (org-get-location (current-buffer) org-goto-help))
7476 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7477 (org-refile-check-position pa)
7481 (org-mark-ring-push org-goto-start-pos)
7482 (goto-char selected-point)
7483 (if (or (outline-invisible-p) (org-invisible-p2))
7484 (org-show-context 'org-goto)))
7487 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7488 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7489 (defvar org-goto-local-auto-isearch-map) ; defined below
7491 (defun org-get-location (buf help)
7492 "Let the user select a location in the Org-mode buffer BUF.
7493 This function uses a recursive edit. It returns the selected position
7496 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7497 (isearch-hide-immediately nil)
7498 (isearch-search-fun-function
7499 (lambda () 'org-goto-local-search-headings))
7500 (org-goto-selected-point org-goto-exit-command))
7502 (save-window-excursion
7503 (delete-other-windows)
7504 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7505 (org-pop-to-buffer-same-window
7507 (make-indirect-buffer (current-buffer) "*org-goto*")
7508 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7509 (with-output-to-temp-buffer "*Org Help*"
7510 (princ (format help (if org-goto-auto-isearch
7511 " Just type for auto-isearch."
7512 " n/p/f/b/u to navigate, q to quit."))))
7513 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7514 (setq buffer-read-only nil)
7515 (let ((org-startup-truncated t)
7516 (org-startup-folded nil)
7517 (org-startup-align-all-tables nil))
7520 (setq buffer-read-only t)
7521 (if (and (boundp 'org-goto-start-pos)
7522 (integer-or-marker-p org-goto-start-pos))
7523 (let ((org-show-hierarchy-above t)
7524 (org-show-siblings t)
7525 (org-show-following-heading t))
7526 (goto-char org-goto-start-pos)
7527 (and (outline-invisible-p) (org-show-context)))
7528 (goto-char (point-min)))
7529 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7530 (message "Select location and press RET")
7531 (use-local-map org-goto-map)
7533 (kill-buffer "*org-goto*")
7534 (cons org-goto-selected-point org-goto-exit-command))))
7536 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7537 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7538 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7539 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7541 (defun org-goto-local-search-headings (string bound noerror)
7542 "Search and make sure that any matches are in headlines."
7544 (while (if isearch-forward
7545 (search-forward string bound noerror)
7546 (search-backward string bound noerror))
7547 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7548 (and (member :headline context)
7549 (not (member :tags context))))
7550 (throw 'return (point))))))
7552 (defun org-goto-local-auto-isearch ()
7555 (goto-char (point-min))
7556 (let ((keys (this-command-keys)))
7557 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7559 (isearch-process-search-char (string-to-char keys)))))
7561 (defun org-goto-ret (&optional arg)
7562 "Finish `org-goto' by going to the new location."
7564 (setq org-goto-selected-point (point)
7565 org-goto-exit-command 'return)
7568 (defun org-goto-left ()
7569 "Finish `org-goto' by going to the new location."
7571 (if (org-at-heading-p)
7573 (beginning-of-line 1)
7574 (setq org-goto-selected-point (point)
7575 org-goto-exit-command 'left)
7577 (user-error "Not on a heading")))
7579 (defun org-goto-right ()
7580 "Finish `org-goto' by going to the new location."
7582 (if (org-at-heading-p)
7584 (setq org-goto-selected-point (point)
7585 org-goto-exit-command 'right)
7587 (user-error "Not on a heading")))
7589 (defun org-goto-quit ()
7590 "Finish `org-goto' without cursor motion."
7592 (setq org-goto-selected-point nil)
7593 (setq org-goto-exit-command 'quit)
7596 ;;; Indirect buffer display of subtrees
7598 (defvar org-indirect-dedicated-frame nil
7599 "This is the frame being used for indirect tree display.")
7600 (defvar org-last-indirect-buffer nil)
7602 (defun org-tree-to-indirect-buffer (&optional arg)
7603 "Create indirect buffer and narrow it to current subtree.
7604 With a numerical prefix ARG, go up to this level and then take that tree.
7605 If ARG is negative, go up that many levels.
7607 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7608 indirect buffer previously made with this command, to avoid proliferation of
7609 indirect buffers. However, when you call the command with a \
7610 \\[universal-argument] prefix, or
7611 when `org-indirect-buffer-display' is `new-frame', the last buffer
7612 is kept so that you can work with several indirect buffers at the same time.
7613 If `org-indirect-buffer-display' is `dedicated-frame', the \
7614 \\[universal-argument] prefix also
7615 requests that a new frame be made for the new buffer, so that the dedicated
7616 frame is not changed."
7618 (let ((cbuf (current-buffer))
7619 (cwin (selected-window))
7621 beg end level heading ibuf)
7623 (org-back-to-heading t)
7625 (setq level (org-outline-level))
7626 (if (< arg 0) (setq arg (+ level arg)))
7627 (while (> (setq level (org-outline-level)) arg)
7628 (org-up-heading-safe)))
7630 heading (org-get-heading))
7631 (org-end-of-subtree t t)
7632 (if (org-at-heading-p) (backward-char 1))
7634 (if (and (buffer-live-p org-last-indirect-buffer)
7635 (not (eq org-indirect-buffer-display 'new-frame))
7637 (kill-buffer org-last-indirect-buffer))
7638 (setq ibuf (org-get-indirect-buffer cbuf heading)
7639 org-last-indirect-buffer ibuf)
7641 ((or (eq org-indirect-buffer-display 'new-frame)
7642 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7643 (select-frame (make-frame))
7644 (delete-other-windows)
7645 (org-pop-to-buffer-same-window ibuf)
7646 (org-set-frame-title heading))
7647 ((eq org-indirect-buffer-display 'dedicated-frame)
7649 (select-frame (or (and org-indirect-dedicated-frame
7650 (frame-live-p org-indirect-dedicated-frame)
7651 org-indirect-dedicated-frame)
7652 (setq org-indirect-dedicated-frame (make-frame)))))
7653 (delete-other-windows)
7654 (org-pop-to-buffer-same-window ibuf)
7655 (org-set-frame-title (concat "Indirect: " heading)))
7656 ((eq org-indirect-buffer-display 'current-window)
7657 (org-pop-to-buffer-same-window ibuf))
7658 ((eq org-indirect-buffer-display 'other-window)
7659 (pop-to-buffer ibuf))
7660 (t (error "Invalid value")))
7661 (if (featurep 'xemacs)
7662 (save-excursion (org-mode) (turn-on-font-lock)))
7663 (narrow-to-region beg end)
7666 (run-hook-with-args 'org-cycle-hook 'all)
7667 (and (window-live-p cwin) (select-window cwin))))
7669 (defun org-get-indirect-buffer (&optional buffer heading)
7670 (setq buffer (or buffer (current-buffer)))
7671 (let ((n 1) (base (buffer-name buffer)) bname)
7672 (while (buffer-live-p
7676 (if heading (concat heading "-" (number-to-string n))
7677 (number-to-string n))))))
7680 (make-indirect-buffer buffer bname 'clone)
7681 (error (make-indirect-buffer buffer bname)))))
7683 (defun org-set-frame-title (title)
7684 "Set the title of the current frame to the string TITLE."
7685 ;; FIXME: how to name a single frame in XEmacs???
7686 (unless (featurep 'xemacs)
7687 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7689 ;;;; Structure editing
7691 ;;; Inserting headlines
7693 (defun org-previous-line-empty-p (&optional next)
7694 "Is the previous line a blank line?
7695 When NEXT is non-nil, check the next line instead."
7698 (or (beginning-of-line (if next 2 0)) t)
7700 (looking-at "[ \t]*$")))))
7702 (defun org-insert-heading (&optional arg invisible-ok)
7703 "Insert a new heading or an item with the same depth at point.
7705 If point is at the beginning of a heading or a list item, insert
7706 a new heading or a new item above the current one. If point is
7707 at the beginning of a normal line, turn the line into a heading.
7709 If point is in the middle of a headline or a list item, split the
7710 headline or the item and create a new headline/item with the text
7711 in the current line after point \(see `org-M-RET-may-split-line'
7712 on how to modify this behavior).
7714 With one universal prefix argument, set the user option
7715 `org-insert-heading-respect-content' to t for the duration of
7716 the command. This modifies the behavior described above in this
7717 ways: on list items and at the beginning of normal lines, force
7718 the insertion of a heading after the current subtree.
7720 With two universal prefix arguments, insert the heading at the
7721 end of the grandparent subtree. For example, if point is within
7722 a 2nd-level heading, then it will insert a 2nd-level heading at
7723 the end of the 1st-level parent heading.
7725 If point is at the beginning of a headline, insert a sibling
7726 before the current headline. If point is not at the beginning,
7727 split the line and create a new headline with the text in the
7728 current line after point \(see `org-M-RET-may-split-line' on how
7729 to modify this behavior).
7731 If point is at the beginning of a normal line, turn this line
7734 When INVISIBLE-OK is set, stop at invisible headlines when going
7735 back. This is important for non-interactive uses of the
7738 (if (org-called-interactively-p 'any) (org-reveal))
7739 (let ((itemp (org-in-item-p))
7740 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7741 (respect-content (or org-insert-heading-respect-content
7743 (initial-content "")
7744 (adjust-empty-lines t))
7748 ((or (= (buffer-size) 0)
7749 (and (not (save-excursion
7750 (and (ignore-errors (org-back-to-heading invisible-ok))
7751 (org-at-heading-p))))
7752 (or arg (not itemp))))
7753 ;; At beginning of buffer or so high up that only a heading
7755 (cond ((and (bolp) (not respect-content)) (insert "* "))
7756 ((not respect-content)
7757 (unless may-split (end-of-line))
7759 ((re-search-forward org-outline-regexp-bol nil t)
7763 (t (goto-char (point-max))
7765 (run-hooks 'org-insert-heading-hook))
7767 ((and itemp (not (member arg '((4) (16)))))
7772 ;; Maybe move at the end of the subtree
7773 (when (equal arg '(16))
7774 (org-up-heading-safe)
7775 (org-end-of-subtree t))
7780 (on-heading (org-at-heading-p))
7781 (empty-line-p (if on-heading
7782 (org-previous-line-empty-p)
7783 ;; We will decide later
7785 ;; Get a level string to fall back on
7787 (if (org-before-first-heading-p) "*"
7789 (org-back-to-heading t)
7790 (if (org-previous-line-empty-p) (setq empty-line-p t))
7791 (looking-at org-outline-regexp)
7792 (make-string (1- (length (match-string 0))) ?*))))
7797 (org-back-to-heading invisible-ok)
7798 (when (and (not on-heading)
7799 (featurep 'org-inlinetask)
7800 (integerp org-inlinetask-min-level)
7801 (>= (length (match-string 0))
7802 org-inlinetask-min-level))
7803 ;; Find a heading level before the inline task
7804 (while (and (setq level (org-up-heading-safe))
7805 (>= level org-inlinetask-min-level)))
7806 (if (org-at-heading-p)
7807 (org-back-to-heading invisible-ok)
7808 (error "This should not happen")))
7809 (unless (and (save-excursion
7811 (org-backward-heading-same-level
7813 (= (point) (match-beginning 0)))
7814 (not (org-previous-line-empty-p t)))
7815 (setq empty-line-p (or empty-line-p
7816 (org-previous-line-empty-p))))
7818 (error (or fix-level "* ")))))
7819 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7820 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7821 pos hide-previous previous-pos)
7823 ;; If we insert after content, move there and clean up whitespace
7824 (when (and respect-content
7825 (not (org-looking-at-p org-outline-regexp-bol)))
7826 (if (not (org-before-first-heading-p))
7827 (org-end-of-subtree nil t)
7828 (re-search-forward org-outline-regexp-bol)
7829 (beginning-of-line 0))
7830 (skip-chars-backward " \r\n")
7831 (and (not (looking-back "^\\*+"))
7832 (looking-at "[ \t]+") (replace-match ""))
7833 (unless (eobp) (forward-char 1))
7834 (when (looking-at "^\\*")
7835 (unless (bobp) (backward-char 1))
7838 ;; If we are splitting, grab the text that should be moved to the new headline
7840 (if (org-on-heading-p)
7841 ;; This is a heading, we split intelligently (keeping tags)
7842 (let ((pos (point)))
7843 (goto-char (point-at-bol))
7844 (unless (looking-at org-complex-heading-regexp)
7845 (error "This should not happen"))
7846 (when (and (match-beginning 4)
7847 (> pos (match-beginning 4))
7848 (< pos (match-end 4)))
7849 (setq initial-content (buffer-substring pos (match-end 4)))
7851 (delete-region (point) (match-end 4))
7852 (if (looking-at "[ \t]*$")
7854 (insert (make-string (length initial-content) ?\ )))
7855 (setq initial-content (org-trim initial-content)))
7858 (setq initial-content
7859 (org-trim (buffer-substring (point) (point-at-eol))))
7860 (delete-region (point) (point-at-eol))))
7862 ;; If we are at the beginning of the line, insert before it. Else after
7864 ((and (bolp) (looking-at "[ \t]*$")))
7865 ((and (bolp) (not (looking-at "[ \t]*$")))
7868 (goto-char (point-at-eol))
7871 ;; Insert the new heading
7874 (insert initial-content)
7875 (when adjust-empty-lines
7877 (and blank (not (org-previous-line-empty-p))))
7878 (org-N-empty-lines-before-current (if blank 1 0))))
7879 (run-hooks 'org-insert-heading-hook)))))))
7881 (defun org-N-empty-lines-before-current (N)
7882 "Make the number of empty lines before current exactly N.
7883 So this will delete or add empty lines."
7885 (goto-char (point-at-bol))
7886 (if (looking-back "\\s-+" nil 'greedy)
7888 (or (bobp) (insert "\n"))
7893 (defun org-get-heading (&optional no-tags no-todo)
7894 "Return the heading of the current entry, without the stars.
7895 When NO-TAGS is non-nil, don't include tags.
7896 When NO-TODO is non-nil, don't include TODO keywords."
7898 (org-back-to-heading t)
7900 ((and no-tags no-todo)
7901 (looking-at org-complex-heading-regexp)
7904 (looking-at (concat org-outline-regexp
7906 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7909 (looking-at org-todo-line-regexp)
7911 (t (looking-at org-heading-regexp)
7912 (match-string 2)))))
7914 (defvar orgstruct-mode) ; defined below
7916 (defun org-heading-components ()
7917 "Return the components of the current heading.
7918 This is a list with the following elements:
7919 - the level as an integer
7920 - the reduced level, different if `org-odd-levels-only' is set.
7921 - the TODO keyword, or nil
7922 - the priority character, like ?A, or nil if no priority is given
7923 - the headline text itself, or the tags string if no headline text
7924 - the tags string, or nil."
7926 (org-back-to-heading t)
7927 (if (let (case-fold-search)
7931 org-complex-heading-regexp)))
7933 (list (length (match-string 1))
7934 (org-reduced-level (length (match-string 1)))
7939 (list (length (match-string 1))
7940 (org-reduced-level (length (match-string 1)))
7941 (org-match-string-no-properties 2)
7942 (and (match-end 3) (aref (match-string 3) 2))
7943 (org-match-string-no-properties 4)
7944 (org-match-string-no-properties 5))))))
7946 (defun org-get-entry ()
7947 "Get the entry text, after heading, entire subtree."
7949 (org-back-to-heading t)
7950 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7952 (defun org-insert-heading-after-current ()
7953 "Insert a new heading with same level as current, after current subtree."
7955 (org-back-to-heading)
7956 (org-insert-heading)
7957 (org-move-subtree-down)
7960 (defun org-insert-heading-respect-content (&optional invisible-ok)
7961 "Insert heading with `org-insert-heading-respect-content' set to t."
7963 (org-insert-heading '(4) invisible-ok))
7965 (defun org-insert-todo-heading-respect-content (&optional force-state)
7966 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7968 (org-insert-todo-heading force-state '(4)))
7970 (defun org-insert-todo-heading (arg &optional force-heading)
7971 "Insert a new heading with the same level and TODO state as current heading.
7972 If the heading has no TODO state, or if the state is DONE, use the first
7973 state (TODO by default). Also with one prefix arg, force first state. With
7974 two prefix args, force inserting at the end of the parent subtree."
7976 (when (or force-heading (not (org-insert-item 'checkbox)))
7977 (org-insert-heading (or (and (equal arg '(16)) '(16))
7980 (org-back-to-heading)
7981 (outline-previous-heading)
7982 (looking-at org-todo-line-regexp))
7985 (if (or (equal arg '(4))
7986 (not (match-beginning 2))
7987 (member (match-string 2) org-done-keywords))
7988 (car org-todo-keywords-1)
7992 (run-hook-with-args-until-success
7993 'org-todo-get-default-hook new-mark-x nil)
7995 (beginning-of-line 1)
7996 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7997 (if org-treat-insert-todo-heading-as-state-change
7999 (insert new-mark " "))))
8000 (when org-provide-todo-statistics
8001 (org-update-parent-todo-statistics))))
8003 (defun org-insert-subheading (arg)
8004 "Insert a new subheading and demote it.
8005 Works for outline headings and for plain lists alike."
8007 (org-insert-heading arg)
8009 ((org-at-heading-p) (org-do-demote))
8010 ((org-at-item-p) (org-indent-item))))
8012 (defun org-insert-todo-subheading (arg)
8013 "Insert a new subheading with TODO keyword or checkbox and demote it.
8014 Works for outline headings and for plain lists alike."
8016 (org-insert-todo-heading arg)
8018 ((org-at-heading-p) (org-do-demote))
8019 ((org-at-item-p) (org-indent-item))))
8021 ;;; Promotion and Demotion
8023 (defvar org-after-demote-entry-hook nil
8024 "Hook run after an entry has been demoted.
8025 The cursor will be at the beginning of the entry.
8026 When a subtree is being demoted, the hook will be called for each node.")
8028 (defvar org-after-promote-entry-hook nil
8029 "Hook run after an entry has been promoted.
8030 The cursor will be at the beginning of the entry.
8031 When a subtree is being promoted, the hook will be called for each node.")
8033 (defun org-promote-subtree ()
8034 "Promote the entire subtree.
8035 See also `org-promote'."
8038 (org-with-limited-levels (org-map-tree 'org-promote)))
8039 (org-fix-position-after-promote))
8041 (defun org-demote-subtree ()
8042 "Demote the entire subtree. See `org-demote'.
8043 See also `org-promote'."
8046 (org-with-limited-levels (org-map-tree 'org-demote)))
8047 (org-fix-position-after-promote))
8050 (defun org-do-promote ()
8051 "Promote the current heading higher up the tree.
8052 If the region is active in `transient-mark-mode', promote all headings
8056 (if (org-region-active-p)
8057 (org-map-region 'org-promote (region-beginning) (region-end))
8059 (org-fix-position-after-promote))
8061 (defun org-do-demote ()
8062 "Demote the current heading lower down the tree.
8063 If the region is active in `transient-mark-mode', demote all headings
8067 (if (org-region-active-p)
8068 (org-map-region 'org-demote (region-beginning) (region-end))
8070 (org-fix-position-after-promote))
8072 (defun org-fix-position-after-promote ()
8073 "Make sure that after pro/demotion cursor position is right."
8074 (let ((pos (point)))
8075 (when (save-excursion
8076 (beginning-of-line 1)
8077 (looking-at org-todo-line-regexp)
8078 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8079 (cond ((eobp) (insert " "))
8080 ((eolp) (insert " "))
8081 ((equal (char-after) ?\ ) (forward-char 1))))))
8083 (defun org-current-level ()
8084 "Return the level of the current entry, or nil if before the first headline.
8085 The level is the number of stars at the beginning of the headline."
8087 (org-with-limited-levels
8088 (if (ignore-errors (org-back-to-heading t))
8089 (funcall outline-level)))))
8091 (defun org-get-previous-line-level ()
8092 "Return the outline depth of the last headline before the current line.
8093 Returns 0 for the first headline in the buffer, and nil if before the
8095 (and (org-current-level)
8096 (or (and (/= (line-beginning-position) (point-min))
8097 (save-excursion (beginning-of-line 0) (org-current-level)))
8100 (defun org-reduced-level (l)
8101 "Compute the effective level of a heading.
8102 This takes into account the setting of `org-odd-levels-only'."
8105 (org-odd-levels-only (1+ (floor (/ l 2))))
8108 (defun org-level-increment ()
8109 "Return the number of stars that will be added or removed at a
8110 time to headlines when structure editing, based on the value of
8111 `org-odd-levels-only'."
8112 (if org-odd-levels-only 2 1))
8114 (defun org-get-valid-level (level &optional change)
8115 "Rectify a level change under the influence of `org-odd-levels-only'
8116 LEVEL is a current level, CHANGE is by how much the level should be
8117 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8118 even level numbers will become the next higher odd number."
8119 (if org-odd-levels-only
8120 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8121 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8122 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8123 (max 1 (+ level (or change 0)))))
8125 (if (boundp 'define-obsolete-function-alias)
8126 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8127 (define-obsolete-function-alias 'org-get-legal-level
8128 'org-get-valid-level)
8129 (define-obsolete-function-alias 'org-get-legal-level
8130 'org-get-valid-level "23.1")))
8132 (defun org-promote ()
8133 "Promote the current heading higher up the tree.
8134 If the region is active in `transient-mark-mode', promote all headings
8136 (org-back-to-heading t)
8137 (let* ((level (save-match-data (funcall outline-level)))
8138 (after-change-functions (remove 'flyspell-after-change-function
8139 after-change-functions))
8140 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8141 (diff (abs (- level (length up-head) -1))))
8142 (cond ((and (= level 1) org-called-with-limited-levels
8143 org-allow-promoting-top-level-subtree)
8144 (replace-match "# " nil t))
8146 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8147 (t (replace-match up-head nil t)))
8148 ;; Fixup tag positioning
8150 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8151 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8152 (run-hooks 'org-after-promote-entry-hook)))
8154 (defun org-demote ()
8155 "Demote the current heading lower down the tree.
8156 If the region is active in `transient-mark-mode', demote all headings
8158 (org-back-to-heading t)
8159 (let* ((level (save-match-data (funcall outline-level)))
8160 (after-change-functions (remove 'flyspell-after-change-function
8161 after-change-functions))
8162 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8163 (diff (abs (- level (length down-head) -1))))
8164 (replace-match down-head nil t)
8165 ;; Fixup tag positioning
8166 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8167 (if org-adapt-indentation (org-fixup-indentation diff))
8168 (run-hooks 'org-after-demote-entry-hook)))
8170 (defun org-cycle-level ()
8171 "Cycle the level of an empty headline through possible states.
8172 This goes first to child, then to parent, level, then up the hierarchy.
8173 After top level, it switches back to sibling level."
8175 (let ((org-adapt-indentation nil))
8176 (when (org-point-at-end-of-empty-headline)
8177 (setq this-command 'org-cycle-level) ; Only needed for caching
8178 (let ((cur-level (org-current-level))
8179 (prev-level (org-get-previous-line-level)))
8181 ;; If first headline in file, promote to top-level.
8183 (loop repeat (/ (- cur-level 1) (org-level-increment))
8184 do (org-do-promote)))
8185 ;; If same level as prev, demote one.
8186 ((= prev-level cur-level)
8188 ;; If parent is top-level, promote to top level if not already.
8190 (loop repeat (/ (- cur-level 1) (org-level-increment))
8191 do (org-do-promote)))
8192 ;; If top-level, return to prev-level.
8194 (loop repeat (/ (- prev-level 1) (org-level-increment))
8195 do (org-do-demote)))
8196 ;; If less than prev-level, promote one.
8197 ((< cur-level prev-level)
8199 ;; If deeper than prev-level, promote until higher than
8201 ((> cur-level prev-level)
8202 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8203 do (org-do-promote))))
8206 (defun org-map-tree (fun)
8207 "Call FUN for every heading underneath the current one."
8208 (org-back-to-heading)
8209 (let ((level (funcall outline-level)))
8213 (outline-next-heading)
8214 (> (funcall outline-level) level))
8218 (defun org-map-region (fun beg end)
8219 "Call FUN for every heading between BEG and END."
8220 (let ((org-ignore-region t))
8222 (setq end (copy-marker end))
8224 (if (and (re-search-forward org-outline-regexp-bol nil t)
8228 (outline-next-heading)
8233 (defvar org-property-end-re) ; silence byte-compiler
8234 (defun org-fixup-indentation (diff)
8235 "Change the indentation in the current entry by DIFF.
8236 However, if any line in the current entry has no indentation, or if it
8237 would end up with no indentation after the change, nothing at all is done."
8239 (let ((end (save-excursion (outline-next-heading)
8241 (prohibit (if (> diff 0)
8243 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8245 (unless (save-excursion (end-of-line 1)
8246 (re-search-forward prohibit end t))
8247 (while (and (< (point) end)
8248 (re-search-forward "^[ \t]+" end t))
8249 (goto-char (match-end 0))
8250 (setq col (current-column))
8251 (if (< diff 0) (replace-match ""))
8252 (org-indent-to-column (+ diff col))))
8253 (move-marker end nil))))
8255 (defun org-convert-to-odd-levels ()
8256 "Convert an org-mode file with all levels allowed to one with odd levels.
8257 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8260 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8261 (let ((outline-level 'org-outline-level)
8262 (org-odd-levels-only nil) n)
8264 (goto-char (point-min))
8265 (while (re-search-forward "^\\*\\*+ " nil t)
8266 (setq n (- (length (match-string 0)) 2))
8267 (while (>= (setq n (1- n)) 0)
8269 (end-of-line 1))))))
8271 (defun org-convert-to-oddeven-levels ()
8272 "Convert an org-mode file with only odd levels to one with odd/even levels.
8273 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8274 file contains a section with an even level, conversion would
8275 destroy the structure of the file. An error is signaled in this
8278 (goto-char (point-min))
8279 ;; First check if there are no even levels
8280 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8281 (org-show-context t)
8282 (error "Not all levels are odd in this file. Conversion not possible"))
8283 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8284 (let ((outline-regexp org-outline-regexp)
8285 (outline-level 'org-outline-level)
8286 (org-odd-levels-only nil) n)
8288 (goto-char (point-min))
8289 (while (re-search-forward "^\\*\\*+ " nil t)
8290 (setq n (/ (1- (length (match-string 0))) 2))
8291 (while (>= (setq n (1- n)) 0)
8293 (end-of-line 1))))))
8295 (defun org-tr-level (n)
8296 "Make N odd if required."
8297 (if org-odd-levels-only (1+ (/ n 2)) n))
8299 ;;; Vertical tree motion, cutting and pasting of subtrees
8301 (defun org-move-subtree-up (&optional arg)
8302 "Move the current subtree up past ARG headlines of the same level."
8304 (org-move-subtree-down (- (prefix-numeric-value arg))))
8306 (defun org-move-subtree-down (&optional arg)
8307 "Move the current subtree down past ARG headlines of the same level."
8309 (setq arg (prefix-numeric-value arg))
8310 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8311 'org-get-last-sibling))
8312 (ins-point (make-marker))
8314 (col (current-column))
8315 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8317 (org-back-to-heading)
8320 (setq ne-beg (org-back-over-empty-lines))
8323 (save-excursion (outline-end-of-heading)
8324 (setq folded (outline-invisible-p)))
8325 (progn (org-end-of-subtree nil t)
8326 (unless (eobp) (backward-char))))
8327 (outline-next-heading)
8328 (setq ne-end (org-back-over-empty-lines))
8331 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8332 ;; include less whitespace
8335 (forward-line (- ne-beg ne-end))
8336 (setq beg (point))))
8337 ;; Find insertion point, with error handling
8339 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8340 (progn (goto-char beg0)
8341 (user-error "Cannot move past superior level or buffer limit")))
8342 (setq cnt (1- cnt)))
8344 ;; Moving forward - still need to move over subtree
8345 (progn (org-end-of-subtree t t)
8347 (org-back-over-empty-lines)
8348 (or (bolp) (newline)))))
8349 (setq ne-ins (org-back-over-empty-lines))
8350 (move-marker ins-point (point))
8351 (setq txt (buffer-substring beg end))
8352 (org-save-markers-in-region beg end)
8353 (delete-region beg end)
8354 (org-remove-empty-overlays-at beg)
8355 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8356 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8357 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8358 (let ((bbb (point)))
8359 (insert-before-markers txt)
8360 (org-reinstall-markers-in-region bbb)
8361 (move-marker ins-point bbb))
8362 (or (bolp) (insert "\n"))
8363 (setq ins-end (point))
8364 (goto-char ins-point)
8365 (org-skip-whitespace)
8366 (when (and (< arg 0)
8367 (org-first-sibling-p)
8369 ;; Move whitespace back to beginning
8372 (let ((kill-whole-line t))
8373 (kill-line (- ne-ins ne-beg)) (point)))
8374 (insert (make-string (- ne-ins ne-beg) ?\n)))
8375 (move-marker ins-point nil)
8380 (org-cycle-hide-drawers 'children))
8381 (org-clean-visibility-after-subtree-move)
8382 ;; move back to the initial column we were at
8383 (move-to-column col)))
8385 (defvar org-subtree-clip ""
8386 "Clipboard for cut and paste of subtrees.
8387 This is actually only a copy of the kill, because we use the normal kill
8388 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8390 (defvar org-subtree-clip-folded nil
8391 "Was the last copied subtree folded?
8392 This is used to fold the tree back after pasting.")
8394 (defun org-cut-subtree (&optional n)
8395 "Cut the current subtree into the clipboard.
8396 With prefix arg N, cut this many sequential subtrees.
8397 This is a short-hand for marking the subtree and then cutting it."
8399 (org-copy-subtree n 'cut))
8401 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8402 "Copy the current subtree it in the clipboard.
8403 With prefix arg N, copy this many sequential subtrees.
8404 This is a short-hand for marking the subtree and then copying it.
8405 If CUT is non-nil, actually cut the subtree.
8406 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8407 of some markers in the region, even if CUT is non-nil. This is
8408 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8410 (let (beg end folded (beg0 (point)))
8411 (if (org-called-interactively-p 'any)
8412 (org-back-to-heading nil) ; take what looks like a subtree
8413 (org-back-to-heading t)) ; take what is really there
8415 (skip-chars-forward " \t\r\n")
8418 (outline-next-heading)
8419 (save-excursion (outline-end-of-heading)
8420 (setq folded (outline-invisible-p)))
8421 (ignore-errors (org-forward-heading-same-level (1- n) t))
8422 (org-end-of-subtree t t)))
8426 (setq org-subtree-clip-folded folded)
8427 (when (or cut force-store-markers)
8428 (org-save-markers-in-region beg end))
8429 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8430 (setq org-subtree-clip (current-kill 0))
8431 (message "%s: Subtree(s) with %d characters"
8432 (if cut "Cut" "Copied")
8433 (length org-subtree-clip)))))
8435 (defun org-paste-subtree (&optional level tree for-yank remove)
8436 "Paste the clipboard as a subtree, with modification of headline level.
8437 The entire subtree is promoted or demoted in order to match a new headline
8440 If the cursor is at the beginning of a headline, the same level as
8441 that headline is used to paste the tree.
8443 If not, the new level is derived from the *visible* headings
8444 before and after the insertion point, and taken to be the inferior headline
8445 level of the two. So if the previous visible heading is level 3 and the
8446 next is level 4 (or vice versa), level 4 will be used for insertion.
8447 This makes sure that the subtree remains an independent subtree and does
8448 not swallow low level entries.
8450 You can also force a different level, either by using a numeric prefix
8451 argument, or by inserting the heading marker by hand. For example, if the
8452 cursor is after \"*****\", then the tree will be shifted to level 5.
8454 If optional TREE is given, use this text instead of the kill ring.
8456 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8457 move back over whitespace before inserting, and move point to the end of
8458 the inserted text when done.
8460 When REMOVE is non-nil, remove the subtree from the clipboard."
8462 (setq tree (or tree (and kill-ring (current-kill 0))))
8463 (unless (org-kill-is-subtree-p tree)
8465 (substitute-command-keys
8466 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8467 (org-with-limited-levels
8468 (let* ((visp (not (outline-invisible-p)))
8470 (^re_ "\\(\\*+\\)[ \t]*")
8471 (old-level (if (string-match org-outline-regexp-bol txt)
8472 (- (match-end 0) (match-beginning 0) 1)
8474 (force-level (cond (level (prefix-numeric-value level))
8475 ((and (looking-at "[ \t]*$")
8477 "^\\*+$" (buffer-substring
8478 (point-at-bol) (point))))
8479 (- (match-end 0) (match-beginning 0)))
8481 (looking-at org-outline-regexp))
8482 (- (match-end 0) (point) 1))))
8483 (previous-level (save-excursion
8486 (outline-previous-visible-heading 1)
8487 (if (looking-at ^re_)
8488 (- (match-end 0) (match-beginning 0) 1)
8491 (next-level (save-excursion
8494 (or (looking-at org-outline-regexp)
8495 (outline-next-visible-heading 1))
8496 (if (looking-at ^re_)
8497 (- (match-end 0) (match-beginning 0) 1)
8500 (new-level (or force-level (max previous-level next-level)))
8501 (shift (if (or (= old-level -1)
8503 (= old-level new-level))
8505 (- new-level old-level)))
8506 (delta (if (> shift 0) -1 1))
8507 (func (if (> shift 0) 'org-demote 'org-promote))
8508 (org-odd-levels-only nil)
8510 ;; Remove the forced level indicator
8512 (delete-region (point-at-bol) (point)))
8514 (beginning-of-line (if (bolp) 1 2))
8516 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8517 (insert-before-markers txt)
8518 (unless (string-match "\n\\'" txt) (insert "\n"))
8519 (setq newend (point))
8520 (org-reinstall-markers-in-region beg)
8523 (skip-chars-forward " \t\n\r")
8525 (if (and (outline-invisible-p) visp)
8526 (save-excursion (outline-show-heading)))
8527 ;; Shift if necessary
8530 (narrow-to-region beg end)
8531 (while (not (= shift 0))
8532 (org-map-region func (point-min) (point-max))
8533 (setq shift (+ delta shift)))
8534 (goto-char (point-min))
8535 (setq newend (point-max))))
8536 (when (or (org-called-interactively-p 'interactive) for-yank)
8537 (message "Clipboard pasted as level %d subtree" new-level))
8538 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8540 (eq org-subtree-clip (current-kill 0))
8541 org-subtree-clip-folded)
8542 ;; The tree was folded before it was killed/copied
8544 (and for-yank (goto-char newend))
8545 (and remove (setq kill-ring (cdr kill-ring))))))
8547 (defun org-kill-is-subtree-p (&optional txt)
8548 "Check if the current kill is an outline subtree, or a set of trees.
8549 Returns nil if kill does not start with a headline, or if the first
8550 headline level is not the largest headline level in the tree.
8551 So this will actually accept several entries of equal levels as well,
8552 which is OK for `org-paste-subtree'.
8553 If optional TXT is given, check this string instead of the current kill."
8554 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8555 (re (org-get-limited-outline-regexp))
8556 (^re (concat "^" re))
8557 (start-level (and kill
8559 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8561 (- (match-end 2) (match-beginning 2) 1)))
8562 (start (1+ (or (match-beginning 2) -1))))
8563 (if (not start-level)
8565 nil) ;; does not even start with a heading
8567 (while (setq start (string-match ^re kill (1+ start)))
8568 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8572 (defvar org-markers-to-move nil
8573 "Markers that should be moved with a cut-and-paste operation.
8574 Those markers are stored together with their positions relative to
8575 the start of the region.")
8577 (defun org-save-markers-in-region (beg end)
8578 "Check markers in region.
8579 If these markers are between BEG and END, record their position relative
8580 to BEG, so that after moving the block of text, we can put the markers back
8582 This function gets called just before an entry or tree gets cut from the
8583 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8584 called immediately, to move the markers with the entries."
8585 (setq org-markers-to-move nil)
8586 (when (featurep 'org-clock)
8587 (org-clock-save-markers-for-cut-and-paste beg end))
8588 (when (featurep 'org-agenda)
8589 (org-agenda-save-markers-for-cut-and-paste beg end)))
8591 (defun org-check-and-save-marker (marker beg end)
8592 "Check if MARKER is between BEG and END.
8593 If yes, remember the marker and the distance to BEG."
8594 (when (and (marker-buffer marker)
8595 (equal (marker-buffer marker) (current-buffer)))
8596 (if (and (>= marker beg) (< marker end))
8597 (push (cons marker (- marker beg)) org-markers-to-move))))
8599 (defun org-reinstall-markers-in-region (beg)
8600 "Move all remembered markers to their position relative to BEG."
8602 (move-marker (car x) (+ beg (cdr x))))
8603 org-markers-to-move)
8604 (setq org-markers-to-move nil))
8606 (defun org-narrow-to-subtree ()
8607 "Narrow buffer to the current subtree."
8611 (org-with-limited-levels
8613 (progn (org-back-to-heading t) (point))
8614 (progn (org-end-of-subtree t t)
8615 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8618 (defun org-narrow-to-block ()
8619 "Narrow buffer to the current block."
8621 (let* ((case-fold-search t)
8622 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8623 "^[ \t]*#\\+end_.*")))
8625 (narrow-to-region (car blockp) (cdr blockp))
8626 (user-error "Not in a block"))))
8629 (defvar org-property-drawer-re))
8631 (defvar org-property-start-re) ;; defined below
8632 (defun org-clone-subtree-with-time-shift (n &optional shift)
8633 "Clone the task (subtree) at point N times.
8634 The clones will be inserted as siblings.
8636 In interactive use, the user will be prompted for the number of
8637 clones to be produced. If the entry has a timestamp, the user
8638 will also be prompted for a time shift, which may be a repeater
8639 as used in time stamps, for example `+3d'. To disable this,
8640 you can call the function with a universal prefix argument.
8642 When a valid repeater is given and the entry contains any time
8643 stamps, the clones will become a sequence in time, with time
8644 stamps in the subtree shifted for each clone produced. If SHIFT
8645 is nil or the empty string, time stamps will be left alone. The
8646 ID property of the original subtree is removed.
8648 If the original subtree did contain time stamps with a repeater,
8649 the following will happen:
8650 - the repeater will be removed in each clone
8651 - an additional clone will be produced, with the current, unshifted
8652 date(s) in the entry.
8653 - the original entry will be placed *after* all the clones, with
8655 - the start days in the repeater in the original entry will be shifted
8656 to past the last clone.
8657 In this way you can spell out a number of instances of a repeating task,
8658 and still retain the repeater to cover future instances of the task."
8659 (interactive "nNumber of clones to produce: ")
8662 (if (and (not (equal current-prefix-arg '(4)))
8664 (re-search-forward org-ts-regexp-both
8666 (org-end-of-subtree t)
8668 (read-from-minibuffer
8669 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8670 ""))) ;; No time shift
8672 (drawer-re org-drawer-regexp)
8673 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8674 beg end template task idprop
8675 shift-n shift-what doshift nmin nmax)
8676 (if (not (and (integerp n) (> n 0)))
8677 (user-error "Invalid number of replications %s" n))
8678 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8679 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8681 (user-error "Invalid shift specification %s" shift))
8683 (setq shift-n (string-to-number (match-string 1 shift))
8684 shift-what (cdr (assoc (match-string 2 shift)
8685 '(("d" . day) ("w" . week)
8686 ("m" . month) ("y" . year))))))
8687 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8688 (setq nmin 1 nmax n)
8689 (org-back-to-heading t)
8691 (setq idprop (org-entry-get nil "ID"))
8692 (org-end-of-subtree t t)
8693 (or (bolp) (insert "\n"))
8695 (setq template (buffer-substring beg end))
8697 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8698 (delete-region beg end)
8700 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8702 (loop for n from nmin to nmax do
8707 (goto-char (point-min))
8709 (and idprop (if org-clone-delete-id
8710 (org-entry-delete nil "ID")
8711 (org-id-get-create t)))
8713 (while (re-search-forward org-clock-re nil t)
8715 (goto-char (point-min))
8716 (while (re-search-forward drawer-re nil t)
8717 (org-remove-empty-drawer-at (point))))
8718 (goto-char (point-min))
8720 (while (re-search-forward org-ts-regexp-both nil t)
8721 (org-timestamp-change (* n shift-n) shift-what))
8722 (unless (= n n-no-remove)
8723 (goto-char (point-min))
8724 (while (re-search-forward org-ts-regexp nil t)
8726 (goto-char (match-beginning 0))
8727 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8728 (delete-region (match-beginning 1) (match-end 1)))))))
8729 (setq task (buffer-string)))
8735 (defun org-sort (with-case)
8736 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8737 Optional argument WITH-CASE means sort case-sensitively."
8740 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8741 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8743 (org-call-with-arg 'org-sort-entries with-case))))
8745 (defun org-sort-remove-invisible (s)
8746 "Remove invisible links from string S."
8747 (remove-text-properties 0 (length s) org-rm-props s)
8748 (while (string-match org-bracket-link-regexp s)
8749 (setq s (replace-match (if (match-end 2)
8751 (match-string 1 s)) t t s)))
8752 (let ((st (format " %s " s)))
8753 (while (string-match org-emph-re st)
8754 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8755 (setq s (substring st 1 -1)))
8758 (defvar org-priority-regexp) ; defined later in the file
8760 (defvar org-after-sorting-entries-or-items-hook nil
8761 "Hook that is run after a bunch of entries or items have been sorted.
8762 When children are sorted, the cursor is in the parent line when this
8763 hook gets called. When a region or a plain list is sorted, the cursor
8764 will be in the first entry of the sorted region/list.")
8766 (defun org-sort-entries
8767 (&optional with-case sorting-type getkey-func compare-func property)
8768 "Sort entries on a certain level of an outline tree.
8769 If there is an active region, the entries in the region are sorted.
8770 Else, if the cursor is before the first entry, sort the top-level items.
8771 Else, the children of the entry at point are sorted.
8773 Sorting can be alphabetically, numerically, by date/time as given by
8774 a time stamp, by a property, by priority order, or by a custom function.
8776 The command prompts for the sorting type unless it has been given to the
8777 function through the SORTING-TYPE argument, which needs to be a character,
8778 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8779 the precise meaning of each character:
8781 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8782 c By creation time, which is assumed to be the first inactive time stamp
8783 at the beginning of a line.
8784 d By deadline date/time.
8786 n Numerically, by converting the beginning of the entry/item to a number.
8787 o By order of TODO keywords.
8788 p By priority according to the cookie.
8789 r By the value of a property.
8790 s By scheduled date/time.
8791 t By date/time, either the first active time stamp in the entry, or, if
8792 none exist, by the first inactive one.
8794 Capital letters will reverse the sort order.
8796 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8797 called with point at the beginning of the record. It must return either
8798 a string or a number that should serve as the sorting key for that record.
8800 Comparing entries ignores case by default. However, with an optional argument
8801 WITH-CASE, the sorting considers case as well.
8803 Sorting is done against the visible part of the headlines, it ignores hidden
8806 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8808 (let ((case-func (if with-case 'identity 'downcase))
8810 ;; The clock marker is lost when using `sort-subr', let's
8811 ;; store the clocking string.
8812 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8814 (goto-char org-clock-marker)
8815 (looking-back "^.*") (match-string-no-properties 0))))
8816 start beg end stars re re2
8818 ;; Find beginning and end of region to sort
8820 ((org-region-active-p)
8821 ;; we will sort the region
8822 (setq end (region-end)
8824 (goto-char (region-beginning))
8825 (if (not (org-at-heading-p)) (outline-next-heading))
8826 (setq start (point)))
8827 ((or (org-at-heading-p)
8828 (ignore-errors (progn (org-back-to-heading) t)))
8829 ;; we will sort the children of the current headline
8830 (org-back-to-heading)
8832 end (progn (org-end-of-subtree t t)
8833 (or (bolp) (insert "\n"))
8834 (when (>= (org-back-over-empty-lines) 1)
8840 (outline-next-heading))
8842 ;; we will sort the top-level entries in this file
8843 (goto-char (point-min))
8844 (or (org-at-heading-p) (outline-next-heading))
8845 (setq start (point))
8846 (goto-char (point-max))
8847 (beginning-of-line 1)
8848 (when (looking-at ".*?\\S-")
8849 ;; File ends in a non-white line
8852 (setq end (point-max))
8853 (setq what "top-level")
8858 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8860 (looking-at "\\(\\*+\\)")
8861 (setq stars (match-string 1)
8862 re (concat "^" (regexp-quote stars) " +")
8863 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8864 txt (buffer-substring beg end))
8865 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8866 (if (and (not (equal stars "*")) (string-match re2 txt))
8867 (user-error "Region to sort contains a level above the first entry"))
8869 (unless sorting-type
8871 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8872 [t]ime
[s]cheduled [d]eadline [c]reated cloc[k]ing
8873 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8875 (setq sorting-type (read-char-exclusive))
8878 (and (= (downcase sorting-type) ?f)
8880 (org-icompleting-read "Sort using function: "
8881 obarray 'fboundp t nil nil))
8882 (setq getkey-func (intern getkey-func))))
8884 (and (= (downcase sorting-type) ?r)
8887 (org-icompleting-read "Property: "
8888 (mapcar 'list (org-buffer-property-keys t))
8891 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8892 (message "Sorting entries...")
8895 (narrow-to-region start end)
8896 (let ((dcst (downcase sorting-type))
8897 (case-fold-search nil)
8898 (now (current-time)))
8900 (/= dcst sorting-type)
8901 ;; This function moves to the beginning character of the "record" to
8904 (if (re-search-forward re nil t)
8905 (goto-char (match-beginning 0))
8906 (goto-char (point-max))))
8907 ;; This function moves to the last character of the "record" being
8912 (outline-forward-same-level 1)
8914 (goto-char (point-max))))))
8915 ;; This function returns the value that gets sorted against.
8919 (if (looking-at org-complex-heading-regexp)
8920 (string-to-number (org-sort-remove-invisible (match-string 4)))
8923 (if (looking-at org-complex-heading-regexp)
8924 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8927 (or (get-text-property (point) :org-clock-minutes) 0))
8929 (let ((end (save-excursion (outline-next-heading) (point))))
8930 (if (or (re-search-forward org-ts-regexp end t)
8931 (re-search-forward org-ts-regexp-both end t))
8932 (org-time-string-to-seconds (match-string 0))
8933 (org-float-time now))))
8935 (let ((end (save-excursion (outline-next-heading) (point))))
8936 (if (re-search-forward
8937 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8939 (org-time-string-to-seconds (match-string 0))
8940 (org-float-time now))))
8942 (let ((end (save-excursion (outline-next-heading) (point))))
8943 (if (re-search-forward org-scheduled-time-regexp end t)
8944 (org-time-string-to-seconds (match-string 1))
8945 (org-float-time now))))
8947 (let ((end (save-excursion (outline-next-heading) (point))))
8948 (if (re-search-forward org-deadline-time-regexp end t)
8949 (org-time-string-to-seconds (match-string 1))
8950 (org-float-time now))))
8952 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8953 (string-to-char (match-string 2))
8954 org-default-priority))
8956 (or (org-entry-get nil property) ""))
8958 (if (looking-at org-complex-heading-regexp)
8959 (let* ((m (match-string 2))
8960 (s (if (member m org-done-keywords) '- '+)))
8961 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8965 (setq tmp (funcall getkey-func))
8966 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8968 (error "Invalid key function `%s'" getkey-func)))
8969 (t (error "Invalid sorting type `%c'" sorting-type))))
8972 ((= dcst ?a) 'string<)
8973 ((= dcst ?f) compare-func)
8974 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
8975 (run-hooks 'org-after-sorting-entries-or-items-hook)
8976 ;; Reset the clock marker if needed
8980 (search-forward cmstr nil t)
8981 (move-marker org-clock-marker (point))))
8982 (message "Sorting entries...done")))
8984 (defun org-do-sort (table what &optional with-case sorting-type)
8985 "Sort TABLE of WHAT according to SORTING-TYPE.
8986 The user will be prompted for the SORTING-TYPE if the call to this
8987 function does not specify it.
8988 WHAT is only for the prompt, to indicate what is being sorted.
8989 The sorting key will be extracted from the car of the elements of
8991 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8992 (unless sorting-type
8994 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8996 (setq sorting-type (read-char-exclusive)))
8997 (let ((dcst (downcase sorting-type))
8998 extractfun comparefun)
8999 ;; Define the appropriate functions
9002 (setq extractfun 'string-to-number
9003 comparefun (if (= dcst sorting-type) '< '>)))
9005 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
9006 (lambda(x) (downcase (org-sort-remove-invisible x))))
9007 comparefun (if (= dcst sorting-type)
9009 (lambda (a b) (and (not (string< a b))
9010 (not (string= a b)))))))
9014 (cond ((or (string-match org-ts-regexp x)
9015 (string-match org-ts-regexp-both x))
9017 (org-time-string-to-time (match-string 0 x))))
9018 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" x)
9019 (org-hh:mm-string-to-minutes x))
9021 comparefun (if (= dcst sorting-type) '< '>)))
9022 (t (error "Invalid sorting type `%c'" sorting-type)))
9024 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
9026 (lambda (a b) (funcall comparefun (car a) (car b))))))
9029 ;;; The orgstruct minor mode
9031 ;; Define a minor mode which can be used in other modes in order to
9032 ;; integrate the org-mode structure editing commands.
9034 ;; This is really a hack, because the org-mode structure commands use
9035 ;; keys which normally belong to the major mode. Here is how it
9036 ;; works: The minor mode defines all the keys necessary to operate the
9037 ;; structure commands, but wraps the commands into a function which
9038 ;; tests if the cursor is currently at a headline or a plain list
9039 ;; item. If that is the case, the structure command is used,
9040 ;; temporarily setting many Org-mode variables like regular
9041 ;; expressions for filling etc. However, when any of those keys is
9042 ;; used at a different location, function uses `key-binding' to look
9043 ;; up if the key has an associated command in another currently active
9044 ;; keymap (minor modes, major mode, global), and executes that
9045 ;; command. There might be problems if any of the keys is otherwise
9046 ;; used as a prefix key.
9048 (defcustom orgstruct-heading-prefix-regexp ""
9049 "Regexp that matches the custom prefix of Org headlines in
9050 orgstruct(++)-mode."
9053 :package-version '(Org . "8.3")
9055 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9057 (defcustom orgstruct-setup-hook nil
9058 "Hook run after orgstruct-mode-map is filled."
9061 :package-version '(Org . "8.0")
9064 (defvar orgstruct-initialized nil)
9066 (defvar org-local-vars nil
9067 "List of local variables, for use by `orgstruct-mode'.")
9070 (define-minor-mode orgstruct-mode
9071 "Toggle the minor mode `orgstruct-mode'.
9072 This mode is for using Org-mode structure commands in other
9073 modes. The following keys behave as if Org-mode were active, if
9074 the cursor is on a headline, or on a plain list item (both as
9075 defined by Org-mode)."
9076 nil " OrgStruct" (make-sparse-keymap)
9077 (funcall (if orgstruct-mode
9078 'add-to-invisibility-spec
9079 'remove-from-invisibility-spec)
9081 (when orgstruct-mode
9082 (org-load-modules-maybe)
9083 (unless orgstruct-initialized
9085 (setq orgstruct-initialized t))))
9088 (defun turn-on-orgstruct ()
9089 "Unconditionally turn on `orgstruct-mode'."
9092 (defvar org-fb-vars nil)
9093 (make-variable-buffer-local 'org-fb-vars)
9094 (defun orgstruct++-mode (&optional arg)
9095 "Toggle `orgstruct-mode', the enhanced version of it.
9096 In addition to setting orgstruct-mode, this also exports all
9097 indentation and autofilling variables from org-mode into the
9098 buffer. It will also recognize item context in multiline items."
9100 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9102 (progn (orgstruct-mode -1)
9104 (org-set-local (car v)
9105 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
9108 (setq org-fb-vars nil)
9109 (unless org-local-vars
9110 (setq org-local-vars (org-get-local-variables)))
9115 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9116 (symbol-name (car x)))
9117 (setq var (car x) val (nth 1 x))
9118 (push (list var `(quote ,(eval var))) org-fb-vars)
9119 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9121 (org-set-local 'orgstruct-is-++ t))))
9123 (defvar orgstruct-is-++ nil
9124 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9125 (make-variable-buffer-local 'orgstruct-is-++)
9128 (defun turn-on-orgstruct++ ()
9129 "Unconditionally turn on `orgstruct++-mode'."
9130 (orgstruct++-mode 1))
9132 (defun orgstruct-error ()
9133 "Error when there is no default binding for a structure key."
9135 (funcall (if (fboundp 'user-error)
9138 "This key has no function outside structure elements"))
9140 (defun orgstruct-setup ()
9141 "Setup orgstruct keymap."
9142 (dolist (cell '((org-demote . t)
9146 (org-shiftmetaleft . t)
9147 (org-shiftmetaright . t)
9148 org-backward-element
9149 org-backward-heading-same-level
9154 org-forward-heading-same-level
9156 org-insert-heading-respect-content
9157 org-kill-note-or-show-branches
9162 org-narrow-to-subtree
9177 outline-next-visible-heading
9178 outline-previous-visible-heading
9182 (let ((f (or (car-safe cell) cell))
9183 (disable-when-heading-prefix (cdr-safe cell)))
9185 (let ((new-bindings))
9186 (dolist (binding (nconc (where-is-internal f org-mode-map)
9187 (where-is-internal f outline-mode-map)))
9188 (push binding new-bindings)
9189 ;; TODO use local-function-key-map
9190 (dolist (rep '(("<tab>" . "TAB")
9191 ("<return>" . "RET")
9192 ("<escape>" . "ESC")
9193 ("<delete>" . "DEL")))
9194 (setq binding (read-kbd-macro
9195 (let ((case-fold-search))
9196 (replace-regexp-in-string
9197 (regexp-quote (cdr rep))
9199 (key-description binding)))))
9200 (pushnew binding new-bindings :test 'equal)))
9201 (dolist (binding new-bindings)
9202 (let ((key (lookup-key orgstruct-mode-map binding)))
9203 (when (or (not key) (numberp key))
9205 (org-defkey orgstruct-mode-map
9207 (orgstruct-make-binding
9208 f binding disable-when-heading-prefix))))))))))
9209 (run-hooks 'orgstruct-setup-hook))
9211 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9212 "Create a function for binding in the structure minor mode.
9213 FUN is the command to call inside a table. KEY is the key that
9214 should be checked in for a command to execute outside of tables.
9215 Non-nil `disable-when-heading-prefix' means to disable the command
9216 if `orgstruct-heading-prefix-regexp' is not empty."
9217 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9220 (while (fboundp (intern nname))
9221 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9222 (setq name (intern nname)))
9224 (let ((bindings '((org-heading-regexp
9226 orgstruct-heading-prefix-regexp
9227 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9229 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9230 (org-outline-regexp-bol
9231 (concat "^" org-outline-regexp))
9232 (outline-regexp org-outline-regexp)
9233 (outline-heading-end-regexp "\n")
9234 (outline-level 'org-outline-level)
9235 (outline-heading-alist))))
9237 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9238 "Outside of structure, run the binding of `"
9239 (key-description key) "'."
9240 (when disable-when-heading-prefix
9242 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9243 "back to the default binding due to limitations of Org's implementation of\n"
9244 "`" (symbol-name fun) "'.")))
9247 ,(and disable-when-heading-prefix
9248 '(not (string= orgstruct-heading-prefix-regexp ""))))
9253 (org-context-p 'headline 'item
9255 '(org-insert-heading
9256 org-insert-heading-respect-content
9258 '(when orgstruct-is-++
9261 (let* ((orgstruct-mode)
9263 (loop with key = ,key
9266 ("<\\([^>]*\\)tab>" . "\\1TAB")
9267 ("<\\([^>]*\\)return>" . "\\1RET")
9268 ("<\\([^>]*\\)escape>" . "\\1ESC")
9269 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9272 (setq key (read-kbd-macro
9273 (let ((case-fold-search))
9274 (replace-regexp-in-string
9277 (key-description key))))))
9278 thereis (key-binding key))))
9279 (if (keymapp binding)
9280 (org-set-transient-map binding)
9281 (let ((func (or binding
9283 'orgstruct-error))))
9285 (call-interactively func)))))
9286 (org-run-like-in-org-mode
9290 (call-interactively ',fun)))))))))
9293 (defun org-contextualize-keys (alist contexts)
9294 "Return valid elements in ALIST depending on CONTEXTS.
9296 `org-agenda-custom-commands' or `org-capture-templates' are the
9297 values used for ALIST, and `org-agenda-custom-commands-contexts'
9298 or `org-capture-templates-contexts' are the associated contexts
9301 ;; normalize contexts
9303 (lambda(c) (cond ((listp (cadr c))
9304 (list (car c) (car c) (cadr c)))
9305 ((string= "" (cadr c))
9306 (list (car c) (car c) (caddr c)))
9309 ;; loop over all commands or templates
9310 (while (setq c (pop a))
9313 ((not (assoc (car c) contexts))
9315 ((and (assoc (car c) contexts)
9316 (setq vrules (org-contextualize-validate-key
9319 (when (not (equal (car vr) (cadr vr)))
9320 (setq repl vr))) vrules)
9321 (if (not repl) (push c r)
9322 (push (cadr repl) s)
9325 (cdr (or (assoc (cadr repl) alist)
9326 (error "Undefined key `%s' as contextual replacement for `%s'"
9327 (cadr repl) (car c)))))
9329 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9334 (let ((tpl (car x)))
9338 (equal y tpl)) s))) x)))
9341 (defun org-contextualize-validate-key (key contexts)
9342 "Check CONTEXTS for agenda or capture KEY."
9344 (while (setq r (pop contexts))
9348 (and (equal key (car r))
9349 (if (functionp rr) (funcall rr)
9350 (or (and (eq (car rr) 'in-file)
9352 (string-match (cdr rr) (buffer-file-name)))
9353 (and (eq (car rr) 'in-mode)
9354 (string-match (cdr rr) (symbol-name major-mode)))
9355 (and (eq (car rr) 'in-buffer)
9356 (string-match (cdr rr) (buffer-name)))
9357 (when (and (eq (car rr) 'not-in-file)
9359 (not (string-match (cdr rr) (buffer-file-name))))
9360 (when (eq (car rr) 'not-in-mode)
9361 (not (string-match (cdr rr) (symbol-name major-mode))))
9362 (when (eq (car rr) 'not-in-buffer)
9363 (not (string-match (cdr rr) (buffer-name)))))))
9366 (delete-dups (delq nil res))))
9368 (defun org-context-p (&rest contexts)
9369 "Check if local context is any of CONTEXTS.
9370 Possible values in the list of contexts are `table', `headline', and `item'."
9371 (let ((pos (point)))
9372 (goto-char (point-at-bol))
9373 (prog1 (or (and (memq 'table contexts)
9374 (looking-at "[ \t]*|"))
9375 (and (memq 'headline contexts)
9376 (looking-at org-outline-regexp))
9377 (and (memq 'item contexts)
9378 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9379 (and (memq 'item-body contexts)
9383 (defun org-get-local-variables ()
9384 "Return a list of all local variables in an Org mode buffer."
9386 (with-current-buffer (get-buffer-create "*Org tmp*")
9389 (setq varlist (buffer-local-variables)))
9390 (kill-buffer "*Org tmp*")
9397 (list (car x) (cdr x))))
9398 (if (and (not (get (car x) 'org-state))
9400 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9401 (symbol-name (car x))))
9405 (defun org-clone-local-variables (from-buffer &optional regexp)
9406 "Clone local variables from FROM-BUFFER.
9407 Optional argument REGEXP selects variables to clone."
9410 (and (symbolp (car pair))
9412 (string-match regexp (symbol-name (car pair))))
9413 (set (make-local-variable (car pair))
9415 (buffer-local-variables from-buffer)))
9418 (defun org-run-like-in-org-mode (cmd)
9419 "Run a command, pretending that the current buffer is in Org-mode.
9420 This will temporarily bind local variables that are typically bound in
9421 Org-mode to the values they have in Org-mode, and then interactively
9423 (org-load-modules-maybe)
9424 (unless org-local-vars
9425 (setq org-local-vars (org-get-local-variables)))
9427 (dolist (var org-local-vars)
9428 (when (or (not (boundp (car var)))
9429 (eq (symbol-value (car var))
9430 (default-value (car var))))
9431 (push (list (car var) `(quote ,(cadr var))) binds)))
9433 (call-interactively (quote ,cmd))))))
9435 (defun org-get-category (&optional pos force-refresh)
9436 "Get the category applying to position POS."
9438 (if force-refresh (org-refresh-category-properties))
9439 (let ((pos (or pos (point))))
9440 (or (get-text-property pos 'org-category)
9441 (progn (org-refresh-category-properties)
9442 (get-text-property pos 'org-category))))))
9444 ;;; Refresh properties
9446 (defun org-refresh-properties (dprop tprop)
9447 "Refresh buffer text properties.
9448 DPROP is the drawer property and TPROP is either the
9449 corresponding text property to set, or an alist with each element
9450 being a text property (as a symbol) and a function to apply to
9451 the value of the drawer property."
9452 (let ((case-fold-search t)
9453 (inhibit-read-only t))
9454 (org-with-silent-modifications
9458 (goto-char (point-min))
9459 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9460 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9462 (defun org-refresh-property (tprop p)
9463 "Refresh the buffer text property TPROP from the drawer property P.
9464 The refresh happens only for the current tree (not subtree)."
9466 (org-back-to-heading t)
9467 ;; tprop is a text property symbol
9470 (point) (or (outline-next-heading) (point-max)) tprop p)
9471 ;; tprop is an alist with (properties . function) elements
9475 (point-at-bol) (or (outline-next-heading) (point-max))
9477 (funcall (cdr al) p))))
9480 (defun org-refresh-category-properties ()
9481 "Refresh category text properties in the buffer."
9482 (let ((case-fold-search t)
9483 (inhibit-read-only t)
9485 ((null org-category)
9486 (if buffer-file-name
9487 (file-name-sans-extension
9488 (file-name-nondirectory buffer-file-name))
9490 ((symbolp org-category) (symbol-name org-category))
9492 beg end cat pos optionp)
9493 (org-with-silent-modifications
9497 (goto-char (point-min))
9498 (put-text-property (point) (point-max) 'org-category def-cat)
9499 (while (re-search-forward
9500 "^[ \t]*\\(\\(?:#\\+\\|:\\)CATEGORY:\\)\\(.*\\)" nil t)
9501 (setq pos (match-end 0)
9502 optionp (equal (char-after (match-beginning 0)) ?#)
9503 cat (org-trim (match-string 2)))
9505 (setq beg (point-at-bol) end (point-max))
9506 (org-back-to-heading t)
9507 (setq beg (point) end (org-end-of-subtree t t)))
9508 (put-text-property beg end 'org-category cat)
9509 (goto-char pos)))))))
9511 (defun org-refresh-stats-properties ()
9512 "Refresh stats text properties in the buffer."
9514 (org-with-silent-modifications
9518 (goto-char (point-min))
9519 (while (re-search-forward
9520 (concat org-outline-regexp-bol ".*"
9521 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9523 (setq stats (cond ((equal (match-string 3) "0") 0)
9525 (/ (* (string-to-number (match-string 2)) 100)
9526 (string-to-number (match-string 3))))
9527 (t (string-to-number (match-string 1)))))
9528 (org-back-to-heading t)
9529 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9530 'org-stats stats)))))))
9532 (defun org-refresh-effort-properties ()
9533 "Refresh effort properties"
9534 (org-refresh-properties
9536 '((effort . identity)
9537 (effort-minutes . org-duration-string-to-minutes))))
9541 ;;; Link abbreviations
9543 (defun org-link-expand-abbrev (link)
9544 "Apply replacements as defined in `org-link-abbrev-alist'."
9545 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9546 (let* ((key (match-string 1 link))
9547 (as (or (assoc key org-link-abbrev-alist-local)
9548 (assoc key org-link-abbrev-alist)))
9549 (tag (and (match-end 2) (match-string 3 link)))
9555 ((symbolp rpl) (funcall rpl tag))
9556 ((string-match "%(\\([^)]+\\))" rpl)
9559 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9560 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9561 ((string-match "%h" rpl)
9562 (replace-match (url-hexify-string (or tag "")) t t rpl))
9563 (t (concat rpl tag)))))
9566 ;;; Storing and inserting links
9568 (defvar org-insert-link-history nil
9569 "Minibuffer history for links inserted with `org-insert-link'.")
9571 (defvar org-stored-links nil
9572 "Contains the links stored with `org-store-link'.")
9574 (defvar org-store-link-plist nil
9575 "Plist with info about the most recently link created with `org-store-link'.")
9577 (defvar org-link-protocols nil
9578 "Link protocols added to Org-mode using `org-add-link-type'.")
9580 (defvar org-store-link-functions nil
9581 "List of functions that are called to create and store a link.
9582 Each function will be called in turn until one returns a non-nil
9583 value. Each function should check if it is responsible for creating
9584 this link (for example by looking at the major mode).
9585 If not, it must exit and return nil.
9586 If yes, it should return a non-nil value after a calling
9587 `org-store-link-props' with a list of properties and values.
9588 Special properties are:
9590 :type The link prefix, like \"http\". This must be given.
9591 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9592 This is obligatory as well.
9593 :description Optional default description for the second pair
9594 of brackets in an Org-mode link. The user can still change
9595 this when inserting this link into an Org-mode buffer.
9597 In addition to these, any additional properties can be specified
9598 and then used in capture templates.")
9600 (defun org-add-link-type (type &optional follow export)
9601 "Add TYPE to the list of `org-link-types'.
9602 Re-compute all regular expressions depending on `org-link-types'
9604 FOLLOW and EXPORT are two functions.
9606 FOLLOW should take the link path as the single argument and do whatever
9607 is necessary to follow the link, for example find a file or display
9610 EXPORT should format the link path for export to one of the export formats.
9611 It should be a function accepting three arguments:
9613 path the path of the link, the text after the prefix (like \"http:\")
9614 desc the description of the link, if any, or a description added by
9615 org-export-normalize-links if there is none
9616 format the export format, a symbol like `html' or `latex' or `ascii'..
9618 The function may use the FORMAT information to return different values
9619 depending on the format. The return value will be put literally into
9620 the exported file. If the return value is nil, this means Org should
9621 do what it normally does with links which do not have EXPORT defined.
9623 Org-mode has a built-in default for exporting links. If you are happy with
9624 this default, there is no need to define an export function for the link
9625 type. For a simple example of an export function, see `org-bbdb.el'."
9626 (add-to-list 'org-link-types type t)
9627 (org-make-link-regexps)
9628 (if (assoc type org-link-protocols)
9629 (setcdr (assoc type org-link-protocols) (list follow export))
9630 (push (list type follow export) org-link-protocols)))
9632 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9633 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9636 (defun org-store-link (arg)
9637 "\\<org-mode-map>Store an org-link to the current location.
9638 This link is added to `org-stored-links' and can later be inserted
9639 into an org-buffer with \\[org-insert-link].
9641 For some link types, a prefix arg is interpreted.
9642 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9643 For file links, arg negates `org-context-in-file-links'.
9645 A double prefix arg force skipping storing functions that are not
9648 A triple prefix arg force storing a link for each line in the
9651 (org-load-modules-maybe)
9652 (if (and (equal arg '(64)) (org-region-active-p))
9654 (let ((end (region-end)))
9655 (goto-char (region-beginning))
9657 (while (< (point-at-eol) end)
9658 (move-end-of-line 1) (activate-mark)
9659 (let (current-prefix-arg)
9660 (call-interactively 'org-store-link))
9661 (move-beginning-of-line 2)
9662 (set-mark (point)))))
9663 (org-with-limited-levels
9664 (setq org-store-link-plist nil)
9665 (let (link cpltxt desc description search
9666 txt custom-id agenda-link sfuns sfunsn)
9669 ;; Store a link using an external link type
9670 ((and (not (equal arg '(16)))
9673 nil (mapcar (lambda (f)
9674 (let (fs) (if (funcall f) (push f fs))))
9675 org-store-link-functions))
9676 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9677 (or (and (cdr sfuns)
9680 "Which function for creating the link? "
9681 sfunsn nil t (car sfunsn)))))
9682 (funcall (caar sfuns)))
9683 (setq link (plist-get org-store-link-plist :link)
9684 desc (or (plist-get org-store-link-plist
9685 :description) link))))
9687 ;; Store a link from a source code buffer
9688 ((org-src-edit-buffer-p)
9690 (while (or (not label)
9694 (goto-char (point-min))
9696 (regexp-quote (format org-coderef-label-format label))
9698 (when label (message "Label exists already") (sit-for 2))
9699 (setq label (read-string "Code line label: " label)))
9701 (setq link (format org-coderef-label-format label))
9702 (setq gc (- 79 (length link)))
9703 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9705 (setq link (concat "(" label ")") desc nil)))
9707 ;; We are in the agenda, link to referenced location
9708 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9709 (let ((m (or (get-text-property (point) 'org-hd-marker)
9710 (get-text-property (point) 'org-marker))))
9712 (org-with-point-at m
9714 (if (org-called-interactively-p 'any)
9715 (call-interactively 'org-store-link)
9716 (org-store-link nil)))))))
9718 ((eq major-mode 'calendar-mode)
9719 (let ((cd (calendar-cursor-to-date)))
9722 (car org-time-stamp-formats)
9724 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9726 (org-store-link-props :type "calendar" :date cd)))
9728 ((eq major-mode 'help-mode)
9729 (setq link (concat "help:" (save-excursion
9730 (goto-char (point-min))
9731 (looking-at "^[^ ]+")
9733 (org-store-link-props :type "help"))
9735 ((eq major-mode 'w3-mode)
9736 (setq cpltxt (if (and (buffer-name)
9737 (not (string-match "Untitled" (buffer-name))))
9740 link (url-view-url t))
9741 (org-store-link-props :type "w3" :url (url-view-url t)))
9743 ((eq major-mode 'image-mode)
9744 (setq cpltxt (concat "file:"
9745 (abbreviate-file-name buffer-file-name))
9747 (org-store-link-props :type "image" :file buffer-file-name))
9749 ;; In dired, store a link to the file of the current line
9750 ((derived-mode-p 'dired-mode)
9751 (let ((file (dired-get-filename nil t)))
9753 (abbreviate-file-name
9754 (expand-file-name (dired-get-filename nil t)))
9755 ;; otherwise, no file so use current directory.
9757 (setq cpltxt (concat "file:" file)
9760 ((setq search (run-hook-with-args-until-success
9761 'org-create-file-search-functions))
9762 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9764 (setq cpltxt (or description link)))
9766 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9767 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9769 ;; Store a link using the target at point
9770 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9773 (abbreviate-file-name
9774 (buffer-file-name (buffer-base-buffer)))
9775 "::" (match-string 1))
9777 ((and (featurep 'org-id)
9778 (or (eq org-id-link-to-org-use-id t)
9779 (and (org-called-interactively-p 'any)
9780 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9781 (and (eq org-id-link-to-org-use-id
9782 'create-if-interactive-and-no-custom-id)
9784 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9785 ;; Store a link using the ID at point
9786 (setq link (condition-case nil
9787 (prog1 (org-id-store-link)
9788 (setq desc (or (plist-get org-store-link-plist
9792 ;; Probably before first headline, link only to file
9794 (abbreviate-file-name
9795 (buffer-file-name (buffer-base-buffer))))))))
9797 ;; Just link to current headline
9798 (setq cpltxt (concat "file:"
9799 (abbreviate-file-name
9800 (buffer-file-name (buffer-base-buffer)))))
9801 ;; Add a context search string
9802 (when (org-xor org-context-in-file-links arg)
9803 (let* ((ee (org-element-at-point))
9804 (et (org-element-type ee))
9805 (ev (plist-get (cadr ee) :value))
9806 (ek (plist-get (cadr ee) :key))
9807 (eok (and (stringp ek) (string-match "name" ek))))
9809 ((org-at-heading-p) nil)
9810 ((and (eq et 'keyword) eok) ev)
9811 ((org-region-active-p)
9812 (buffer-substring (region-beginning) (region-end)))))
9813 (when (or (null txt) (string-match "\\S-" txt))
9817 (org-make-org-heading-search-string txt)
9819 desc (or (and (eq et 'keyword) eok ev)
9820 (nth 4 (ignore-errors (org-heading-components)))
9822 (if (string-match "::\\'" cpltxt)
9823 (setq cpltxt (substring cpltxt 0 -2)))
9824 (setq link cpltxt))))
9826 ((buffer-file-name (buffer-base-buffer))
9827 ;; Just link to this file here.
9828 (setq cpltxt (concat "file:"
9829 (abbreviate-file-name
9830 (buffer-file-name (buffer-base-buffer)))))
9831 ;; Add a context string.
9832 (when (org-xor org-context-in-file-links arg)
9833 (setq txt (if (org-region-active-p)
9834 (buffer-substring (region-beginning) (region-end))
9835 (buffer-substring (point-at-bol) (point-at-eol))))
9836 ;; Only use search option if there is some text.
9837 (when (string-match "\\S-" txt)
9839 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9843 ((org-called-interactively-p 'interactive)
9844 (user-error "No method for storing a link from this buffer"))
9846 (t (setq link nil)))
9848 ;; We're done setting link and desc, clean up
9849 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9850 (setq link (or link cpltxt)
9851 desc (or desc cpltxt))
9852 (cond ((equal desc "NONE") (setq desc nil))
9853 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9854 (let ((d0 (match-string 3 desc))
9855 (p0 (match-string 5 desc)))
9857 (replace-regexp-in-string
9858 org-bracket-link-regexp
9860 (if (equal (length (match-string 0 desc))
9861 (length desc)) "*" "")) desc)))))
9864 (if (not (and (or (org-called-interactively-p 'any)
9865 executing-kbd-macro) link))
9866 (or agenda-link (and link (org-make-link-string link desc)))
9867 (push (list link desc) org-stored-links)
9868 (message "Stored: %s" (or desc link))
9870 (setq link (concat "file:" (abbreviate-file-name
9871 (buffer-file-name)) "::#" custom-id))
9872 (push (list link desc) org-stored-links))
9873 (car org-stored-links))))))
9875 (defun org-store-link-props (&rest plist)
9876 "Store link properties, extract names and addresses."
9878 (when (setq x (plist-get plist :from))
9879 (setq adr (mail-extract-address-components x))
9880 (setq plist (plist-put plist :fromname (car adr)))
9881 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9882 (when (setq x (plist-get plist :to))
9883 (setq adr (mail-extract-address-components x))
9884 (setq plist (plist-put plist :toname (car adr)))
9885 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9886 (let ((from (plist-get plist :from))
9887 (to (plist-get plist :to)))
9888 (when (and from to org-from-is-user-regexp)
9890 (plist-put plist :fromto
9891 (if (string-match org-from-is-user-regexp from)
9893 (concat "from %f"))))))
9894 (setq org-store-link-plist plist))
9896 (defun org-add-link-props (&rest plist)
9897 "Add these properties to the link property list."
9900 (setq key (pop plist) value (pop plist))
9901 (setq org-store-link-plist
9902 (plist-put org-store-link-plist key value)))))
9904 (defun org-email-link-description (&optional fmt)
9905 "Return the description part of an email link.
9906 This takes information from `org-store-link-plist' and formats it
9907 according to FMT (default from `org-email-link-description-format')."
9908 (setq fmt (or fmt org-email-link-description-format))
9909 (let* ((p org-store-link-plist)
9910 (to (plist-get p :toaddress))
9911 (from (plist-get p :fromaddress))
9914 (cons "%c" (plist-get p :fromto))
9915 (cons "%F" (plist-get p :from))
9916 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9917 (cons "%T" (plist-get p :to))
9918 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9919 (cons "%s" (plist-get p :subject))
9920 (cons "%d" (plist-get p :date))
9921 (cons "%m" (plist-get p :message-id)))))
9922 (when (string-match "%c" fmt)
9923 ;; Check if the user wrote this message
9924 (if (and org-from-is-user-regexp from to
9925 (save-match-data (string-match org-from-is-user-regexp from)))
9926 (setq fmt (replace-match "to %t" t t fmt))
9927 (setq fmt (replace-match "from %f" t t fmt))))
9928 (org-replace-escapes fmt table)))
9930 (defun org-make-org-heading-search-string (&optional string)
9931 "Make search string for the current headline or STRING."
9933 (and (derived-mode-p 'org-mode)
9935 (org-back-to-heading t)
9936 (org-element-property :raw-value (org-element-at-point))))))
9937 (lines org-context-in-file-links))
9938 (or string (setq s (concat "*" s))) ; Add * for headlines
9939 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9940 (when (and string (integerp lines) (> lines 0))
9941 (let ((slines (org-split-string s "\n")))
9942 (when (< lines (length slines))
9945 (reverse (nthcdr (- (length slines) lines)
9946 (reverse slines))) "\n")))))
9947 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9949 (defun org-make-link-string (link &optional description)
9950 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9951 (unless (string-match "\\S-" link)
9952 (error "Empty link"))
9953 (when (and description
9954 (stringp description)
9955 (not (string-match "\\S-" description)))
9956 (setq description nil))
9957 (when (stringp description)
9958 ;; Remove brackets from the description, they are fatal.
9959 (while (string-match "\\[" description)
9960 (setq description (replace-match "{" t t description)))
9961 (while (string-match "\\]" description)
9962 (setq description (replace-match "}" t t description))))
9963 (when (equal link description)
9964 ;; No description needed, it is identical
9965 (setq description nil))
9966 (when (and (not description)
9967 (not (string-match (org-image-file-name-regexp) link))
9968 (not (equal link (org-link-escape link))))
9969 (setq description (org-extract-attributes link)))
9971 (cond ((string-match (org-image-file-name-regexp) link) link)
9972 ((string-match org-link-types-re link)
9973 (concat (match-string 1 link)
9974 (org-link-escape (substring link (match-end 1)))))
9975 (t (org-link-escape link))))
9976 (concat "[[" link "]"
9977 (if description (concat "[" description "]") "")
9980 (defconst org-link-escape-chars
9983 "List of characters that should be escaped in a link when stored to Org.
9984 This is the list that is used for internal purposes.")
9986 (defconst org-link-escape-chars-browser
9989 "List of characters to be escaped before handing over to the browser.
9990 If you consider using this constant then you probably want to use
9991 the function `org-link-escape-browser' instead. See there why
9992 this constant is a candidate to be removed once Org drops support
9993 for Emacs 24.1 and 24.2.")
9995 (defun org-link-escape (text &optional table merge)
9996 "Return percent escaped representation of TEXT.
9997 TEXT is a string with the text to escape.
9998 Optional argument TABLE is a list with characters that should be
9999 escaped. When nil, `org-link-escape-chars' is used.
10000 If optional argument MERGE is set, merge TABLE into
10001 `org-link-escape-chars'."
10002 ;; Don't escape chars in internal links
10003 (if (string-match "^\\*[[:alnum:]]+" text)
10007 (mapc (lambda (defchr)
10008 (unless (member defchr table)
10009 (setq table (cons defchr table))))
10010 org-link-escape-chars))
10012 (setq table org-link-escape-chars)))
10015 (if (or (member char table)
10016 (and (or (< char 32) (= char ?\%) (> char 126))
10018 (mapconcat (lambda (sequence-element)
10019 (format "%%%.2X" sequence-element))
10020 (or (encode-coding-char char 'utf-8)
10021 (error "Unable to percent escape character: %s"
10022 (char-to-string char))) "")
10023 (char-to-string char))) text "")))
10025 (defun org-link-escape-browser (text)
10026 "Escape some characters before handing over to the browser.
10027 This function is a candidate to be removed together with the
10028 constant `org-link-escape-chars-browser' once Org drops support
10029 for Emacs 24.1 and 24.2. All calls to this function will have to
10030 be replaced with `url-encode-url' which is available since Emacs
10032 ;; Example with the Org link
10033 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10034 ;; to open the browser with +subject:"Release 8.2" filled into the
10035 ;; query field: In this case the variable TEXT contains the
10036 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10037 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10038 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10039 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10040 (if (fboundp 'url-encode-url)
10041 (url-encode-url text)
10042 (if (org-string-match-p
10043 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10045 (org-link-escape text org-link-escape-chars-browser)
10048 (defun org-link-unescape (str)
10049 "Unhex hexified Unicode strings as returned from the JavaScript function
10050 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
10051 (unless (and (null str) (string= "" str))
10052 (let ((pos 0) (case-fold-search t) unhexed)
10053 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
10054 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
10055 (setq str (replace-match unhexed t t str))
10056 (setq pos (+ pos (length unhexed))))))
10059 (defun org-link-unescape-compound (hex)
10060 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10061 Note: this function also decodes single byte encodings like
10062 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10064 (let* ((bytes (cdr (split-string hex "%")))
10069 (let* ((val (string-to-number (pop bytes) 16))
10073 ((>= val 252) (cons 6 252))
10074 ((>= val 248) (cons 5 248))
10075 ((>= val 240) (cons 4 240))
10076 ((>= val 224) (cons 3 224))
10077 ((>= val 192) (cons 2 192))
10080 (if (>= val 192) (setq eat (car shift-xor)))
10081 (setq val (logxor val (cdr shift-xor)))
10082 (setq sum (+ (lsh sum (car shift-xor)) val))
10083 (if (> eat 0) (setq eat (- eat 1)))
10085 ((= 0 eat) ;multi byte
10086 (setq ret (concat ret (org-char-to-string sum)))
10088 ((not bytes) ; single byte(s)
10089 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10092 (defun org-link-unescape-single-byte-sequence (hex)
10093 "Unhexify hex-encoded single byte character sequences."
10094 (mapconcat (lambda (byte)
10095 (char-to-string (string-to-number byte 16)))
10096 (cdr (split-string hex "%")) ""))
10098 (defun org-xor (a b)
10102 (defun org-fixup-message-id-for-http (s)
10103 "Replace special characters in a message id, so it can be used in an http query."
10104 (when (string-match "%" s)
10105 (setq s (mapconcat (lambda (c)
10108 (char-to-string c)))
10110 (while (string-match "<" s)
10111 (setq s (replace-match "%3C" t t s)))
10112 (while (string-match ">" s)
10113 (setq s (replace-match "%3E" t t s)))
10114 (while (string-match "@" s)
10115 (setq s (replace-match "%40" t t s)))
10118 (defun org-link-prettify (link)
10119 "Return a human-readable representation of LINK.
10120 The car of LINK must be a raw link.
10121 The cdr of LINK must be either a link description or nil."
10122 (let ((desc (or (cadr link) "<no description>")))
10123 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10124 "<" (car link) ">")))
10127 (defun org-insert-link-global ()
10128 "Insert a link like Org-mode does.
10129 This command can be called in any mode to insert a link in Org-mode syntax."
10131 (org-load-modules-maybe)
10132 (org-run-like-in-org-mode 'org-insert-link))
10134 (defun org-insert-all-links (arg &optional pre post)
10135 "Insert all links in `org-stored-links'.
10136 When a universal prefix, do not delete the links from `org-stored-links'.
10137 When `ARG' is a number, insert the last N link(s).
10138 `PRE' and `POST' are optional arguments to define a string to
10139 prepend or to append."
10141 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10142 (links (copy-seq org-stored-links))
10144 (po (or post "\n"))
10146 (if (null org-stored-links)
10147 (message "No link to insert")
10148 (while (and (or (listp arg) (>= arg cnt))
10149 (setq l (if (listp arg)
10151 (pop org-stored-links))))
10152 (setq cnt (1+ cnt))
10154 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10157 (defun org-insert-last-stored-link (arg)
10158 "Insert the last link stored in `org-stored-links'."
10160 (org-insert-all-links arg "" "\n"))
10162 (defun org-link-fontify-links-to-this-file ()
10163 "Fontify links to the current file in `org-stored-links'."
10164 (let ((f (buffer-file-name)) a b)
10165 (setq a (mapcar (lambda(l)
10166 (let ((ll (car l)))
10167 (when (and (string-match "^file:\\(.+\\)::" ll)
10168 (equal f (expand-file-name (match-string 1 ll))))
10171 (when (featurep 'org-id)
10172 (setq b (mapcar (lambda(l)
10173 (let ((ll (car l)))
10174 (when (and (string-match "^id:\\(.+\\)$" ll)
10175 (equal f (expand-file-name
10176 (or (org-id-find-id-file
10177 (match-string 1 ll)) ""))))
10179 org-stored-links)))
10181 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10182 (delq nil (append a b)))))
10184 (defvar org-link-links-in-this-file nil)
10185 (defun org-insert-link (&optional complete-file link-location default-description)
10186 "Insert a link. At the prompt, enter the link.
10188 Completion can be used to insert any of the link protocol prefixes like
10189 http or ftp in use.
10191 The history can be used to select a link previously stored with
10192 `org-store-link'. When the empty string is entered (i.e. if you just
10193 press RET at the prompt), the link defaults to the most recently
10194 stored link. As SPC triggers completion in the minibuffer, you need to
10195 use M-SPC or C-q SPC to force the insertion of a space character.
10197 You will also be prompted for a description, and if one is given, it will
10198 be displayed in the buffer instead of the link.
10200 If there is already a link at point, this command will allow you to edit link
10201 and description parts.
10203 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10204 be selected using completion. The path to the file will be relative to the
10205 current directory if the file is in the current directory or a subdirectory.
10206 Otherwise, the link will be the absolute path as completed in the minibuffer
10207 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10208 option `org-link-file-path-type'.
10210 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10211 the current directory or below.
10213 With three \\[universal-argument] prefixes, negate the meaning of
10214 `org-keep-stored-link-after-insertion'.
10216 If `org-make-link-description-function' is non-nil, this function will be
10217 called with the link target, and the result will be the default
10220 If the LINK-LOCATION parameter is non-nil, this value will be
10221 used as the link location instead of reading one interactively.
10223 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10224 be used as the default description."
10226 (let* ((wcf (current-window-configuration))
10227 (origbuf (current-buffer))
10228 (region (if (org-region-active-p)
10229 (buffer-substring (region-beginning) (region-end))))
10230 (remove (and region (list (region-beginning) (region-end))))
10232 tmphist ; byte-compile incorrectly complains about this
10233 (link link-location)
10234 (abbrevs org-link-abbrev-alist-local)
10235 entry file all-prefixes auto-desc)
10237 (link-location) ; specified by arg, just use it.
10238 ((org-in-regexp org-bracket-link-regexp 1)
10239 ;; We do have a link at point, and we are going to edit it.
10240 (setq remove (list (match-beginning 0) (match-end 0)))
10241 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10242 (setq link (read-string "Link: "
10244 (org-match-string-no-properties 1)))))
10245 ((or (org-in-regexp org-angle-link-re)
10246 (org-in-regexp org-plain-link-re))
10247 ;; Convert to bracket link
10248 (setq remove (list (match-beginning 0) (match-end 0))
10249 link (read-string "Link: "
10250 (org-remove-angle-brackets (match-string 0)))))
10251 ((member complete-file '((4) (16)))
10252 ;; Completing read for file names.
10253 (setq link (org-file-complete-link complete-file)))
10255 ;; Read link, with completion for stored links.
10256 (org-link-fontify-links-to-this-file)
10257 (org-switch-to-buffer-other-window "*Org Links*")
10258 (with-current-buffer "*Org Links*"
10260 (insert "Insert a link.
10261 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10262 (when org-stored-links
10263 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10264 (insert (mapconcat 'org-link-prettify
10265 (reverse org-stored-links) "\n")))
10266 (goto-char (point-min)))
10267 (let ((cw (selected-window)))
10268 (select-window (get-buffer-window "*Org Links*" 'visible))
10269 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10270 (unless (pos-visible-in-window-p (point-max))
10271 (org-fit-window-to-buffer))
10272 (and (window-live-p cw) (select-window cw)))
10273 ;; Fake a link history, containing the stored links.
10274 (setq tmphist (append (mapcar 'car org-stored-links)
10275 org-insert-link-history))
10276 (setq all-prefixes (append (mapcar 'car abbrevs)
10277 (mapcar 'car org-link-abbrev-alist)
10282 (org-completing-read
10285 (mapcar (lambda (x) (concat x ":"))
10287 (mapcar 'car org-stored-links))
10290 (caar org-stored-links)))
10291 (if (not (string-match "\\S-" link))
10292 (user-error "No link selected"))
10294 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10296 (if (or (member link all-prefixes)
10297 (and (equal ":" (substring link -1))
10298 (member (substring link 0 -1) all-prefixes)
10299 (setq link (substring link 0 -1))))
10300 (setq link (with-current-buffer origbuf
10301 (org-link-try-special-completion link)))))
10302 (set-window-configuration wcf)
10303 (kill-buffer "*Org Links*"))
10304 (setq entry (assoc link org-stored-links))
10305 (or entry (push link org-insert-link-history))
10306 (setq desc (or desc (nth 1 entry)))))
10308 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10309 (not org-keep-stored-link-after-insertion))
10310 (setq org-stored-links (delq (assoc link org-stored-links)
10311 org-stored-links)))
10313 (if (and (string-match org-plain-link-re link)
10314 (not (string-match org-ts-regexp link)))
10315 ;; URL-like link, normalize the use of angular brackets.
10316 (setq link (org-remove-angle-brackets link)))
10318 ;; Check if we are linking to the current file with a search
10319 ;; option If yes, simplify the link by using only the search
10321 (when (and buffer-file-name
10322 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10323 (let* ((path (match-string 1 link))
10324 (case-fold-search nil)
10325 (search (match-string 2 link)))
10327 (if (equal (file-truename buffer-file-name) (file-truename path))
10328 ;; We are linking to this same file, with a search option
10329 (setq link search)))))
10331 ;; Check if we can/should use a relative path. If yes, simplify the link
10332 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10333 (let* ((type (match-string 1 link))
10334 (path (match-string 2 link))
10336 (case-fold-search nil))
10338 ((or (eq org-link-file-path-type 'absolute)
10339 (equal complete-file '(16)))
10340 (setq path (abbreviate-file-name (expand-file-name path))))
10341 ((eq org-link-file-path-type 'noabbrev)
10342 (setq path (expand-file-name path)))
10343 ((eq org-link-file-path-type 'relative)
10344 (setq path (file-relative-name path)))
10347 (if (string-match (concat "^" (regexp-quote
10349 (file-name-as-directory
10350 default-directory))))
10351 (expand-file-name path))
10352 ;; We are linking a file with relative path name.
10353 (setq path (substring (expand-file-name path)
10355 (setq path (abbreviate-file-name (expand-file-name path)))))))
10356 (setq link (concat type path))
10357 (if (equal desc origpath)
10358 (setq desc path))))
10360 (if org-make-link-description-function
10362 (or (condition-case nil
10363 (funcall org-make-link-description-function link desc)
10364 (error (progn (message "Can't get link description from `%s'"
10365 (symbol-name org-make-link-description-function))
10367 (read-string "Description: " default-description)))
10368 (if default-description (setq desc default-description)
10369 (setq desc (or (and auto-desc desc)
10370 (read-string "Description: " desc)))))
10372 (unless (string-match "\\S-" desc) (setq desc nil))
10373 (if remove (apply 'delete-region remove))
10374 (insert (org-make-link-string link desc))))
10376 (defun org-link-try-special-completion (type)
10377 "If there is completion support for link type TYPE, offer it."
10378 (let ((fun (intern (concat "org-" type "-complete-link"))))
10379 (if (functionp fun)
10381 (read-string "Link (no completion support): " (concat type ":")))))
10383 (defun org-file-complete-link (&optional arg)
10384 "Create a file link using completion."
10386 (setq file (org-iread-file-name "File: "))
10387 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10388 (pwd1 (file-name-as-directory (abbreviate-file-name
10389 (expand-file-name ".")))))
10394 (abbreviate-file-name (expand-file-name file)))))
10395 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10396 (setq link (concat "file:" (match-string 1 file))))
10397 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10398 (expand-file-name file))
10400 "file:" (match-string 1 (expand-file-name file)))))
10401 (t (setq link (concat "file:" file)))))
10404 (defun org-iread-file-name (&rest args)
10405 "Read-file-name using `ido-mode' speedup if available.
10406 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10407 See `read-file-name' for a description of parameters."
10408 (org-without-partial-completion
10409 (if (and org-completion-use-ido
10410 (fboundp 'ido-read-file-name)
10411 (boundp 'ido-mode) ido-mode
10412 (listp (second args)))
10413 (let ((ido-enter-matching-directory nil))
10414 (apply 'ido-read-file-name args))
10415 (apply 'read-file-name args))))
10417 (defun org-completing-read (&rest args)
10418 "Completing-read with SPACE being a normal character."
10419 (let ((enable-recursive-minibuffers t)
10420 (minibuffer-local-completion-map
10421 (copy-keymap minibuffer-local-completion-map)))
10422 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10423 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10424 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10425 (apply 'org-icompleting-read args)))
10427 (defun org-completing-read-no-i (&rest args)
10428 (let (org-completion-use-ido org-completion-use-iswitchb)
10429 (apply 'org-completing-read args)))
10431 (defun org-iswitchb-completing-read (prompt choices &rest args)
10432 "Use iswitch as a completing-read replacement to choose from choices.
10433 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10435 (let* ((iswitchb-use-virtual-buffers nil)
10436 (iswitchb-make-buflist-hook
10438 (setq iswitchb-temp-buflist choices))))
10439 (iswitchb-read-buffer prompt)))
10441 (defun org-icompleting-read (&rest args)
10442 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10443 (org-without-partial-completion
10444 (if (and org-completion-use-ido
10445 (fboundp 'ido-completing-read)
10446 (boundp 'ido-mode) ido-mode
10447 (listp (second args)))
10448 (let ((ido-enter-matching-directory nil))
10449 (apply 'ido-completing-read (concat (car args))
10450 (if (consp (car (nth 1 args)))
10451 (mapcar 'car (nth 1 args))
10454 (if (and org-completion-use-iswitchb
10455 (boundp 'iswitchb-mode) iswitchb-mode
10456 (listp (second args)))
10457 (apply 'org-iswitchb-completing-read (concat (car args))
10458 (if (consp (car (nth 1 args)))
10459 (mapcar 'car (nth 1 args))
10462 (apply 'completing-read args)))))
10464 (defun org-extract-attributes (s)
10465 "Extract the attributes cookie from a string and set as text property."
10466 (let (a attr (start 0) key value)
10468 (when (string-match "{{\\([^}]+\\)}}$" s)
10469 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10470 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10471 (setq key (match-string 1 a) value (match-string 2 a)
10472 start (match-end 0)
10473 attr (plist-put attr (intern key) value))))
10474 (org-add-props s nil 'org-attr attr))
10477 ;;; Opening/following a link
10479 (defvar org-link-search-failed nil)
10481 (defvar org-open-link-functions nil
10482 "Hook for functions finding a plain text link.
10483 These functions must take a single argument, the link content.
10484 They will be called for links that look like [[link text][description]]
10485 when LINK TEXT does not have a protocol like \"http:\" and does not look
10486 like a filename (e.g. \"./blue.png\").
10488 These functions will be called *before* Org attempts to resolve the
10489 link by doing text searches in the current buffer - so if you want a
10490 link \"[[target]]\" to still find \"<<target>>\", your function should
10491 handle this as a special case.
10493 When the function does handle the link, it must return a non-nil value.
10494 If it decides that it is not responsible for this link, it must return
10495 nil to indicate that that Org-mode can continue with other options
10496 like exact and fuzzy text search.")
10498 (defun org-next-link (&optional search-backward)
10499 "Move forward to the next link.
10500 If the link is in hidden text, expose it."
10502 (when (and org-link-search-failed (eq this-command last-command))
10503 (goto-char (point-min))
10504 (message "Link search wrapped back to beginning of buffer"))
10505 (setq org-link-search-failed nil)
10506 (let* ((pos (point))
10508 (a (assoc :link ct))
10509 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10510 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10511 ((looking-at org-any-link-re)
10512 ;; Don't stay stuck at link without an org-link face
10513 (forward-char (if search-backward -1 1))))
10514 (if (funcall srch-fun org-any-link-re nil t)
10516 (goto-char (match-beginning 0))
10517 (if (outline-invisible-p) (org-show-context)))
10519 (setq org-link-search-failed t)
10520 (message "No further link found"))))
10522 (defun org-previous-link ()
10523 "Move backward to the previous link.
10524 If the link is in hidden text, expose it."
10526 (funcall 'org-next-link t))
10528 (defun org-translate-link (s)
10529 "Translate a link string if a translation function has been defined."
10530 (if (and org-link-translation-function
10531 (fboundp org-link-translation-function)
10532 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10534 (setq s (funcall org-link-translation-function
10535 (match-string 1 s) (match-string 2 s)))
10536 (concat (car s) ":" (cdr s)))
10539 (defun org-translate-link-from-planner (type path)
10540 "Translate a link from Emacs Planner syntax so that Org can follow it.
10541 This is still an experimental function, your mileage may vary."
10543 ((member type '("http" "https" "news" "ftp"))
10544 ;; standard Internet links are the same.
10546 ((and (equal type "irc") (string-match "^//" path))
10547 ;; Planner has two / at the beginning of an irc link, we have 1.
10548 ;; We should have zero, actually....
10549 (setq path (substring path 1)))
10550 ((and (equal type "lisp") (string-match "^/" path))
10551 ;; Planner has a slash, we do not.
10552 (setq type "elisp" path (substring path 1)))
10553 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10554 ;; A typical message link. Planner has the id after the final slash,
10555 ;; we separate it with a hash mark
10556 (setq path (concat (match-string 1 path) "#"
10557 (org-remove-angle-brackets (match-string 2 path))))))
10560 (defun org-find-file-at-mouse (ev)
10561 "Open file link or URL at mouse."
10563 (mouse-set-point ev)
10564 (org-open-at-point 'in-emacs))
10566 (defun org-open-at-mouse (ev)
10567 "Open file link or URL at mouse.
10568 See the docstring of `org-open-file' for details."
10570 (mouse-set-point ev)
10571 (if (eq major-mode 'org-agenda-mode)
10572 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10573 (org-open-at-point))
10575 (defvar org-window-config-before-follow-link nil
10576 "The window configuration before following a link.
10577 This is saved in case the need arises to restore it.")
10579 (defvar org-open-link-marker (make-marker)
10580 "Marker pointing to the location where `org-open-at-point' was called.")
10583 (defun org-open-at-point-global ()
10584 "Follow a link like Org-mode does.
10585 This command can be called in any mode to follow a link that has
10588 (org-run-like-in-org-mode 'org-open-at-point))
10591 (defun org-open-link-from-string (s &optional arg reference-buffer)
10592 "Open a link in the string S, as if it was in Org-mode."
10593 (interactive "sLink: \nP")
10594 (let ((reference-buffer (or reference-buffer (current-buffer))))
10596 (let ((org-inhibit-startup (not reference-buffer)))
10599 (goto-char (point-min))
10600 (when reference-buffer
10601 (setq org-link-abbrev-alist-local
10602 (with-current-buffer reference-buffer
10603 org-link-abbrev-alist-local)))
10604 (org-open-at-point arg reference-buffer)))))
10606 (defvar org-open-at-point-functions nil
10607 "Hook that is run when following a link at point.
10609 Functions in this hook must return t if they identify and follow
10610 a link at point. If they don't find anything interesting at point,
10611 they must return nil.")
10613 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10614 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10615 (defun org-open-at-point (&optional arg reference-buffer)
10616 "Open link, timestamp, footnote or tags at point.
10618 When point is on a link, follow it. Normally, files will be
10619 opened by an appropriate application. If the optional prefix
10620 argument ARG is non-nil, Emacs will visit the file. With
10621 a double prefix argument, try to open outside of Emacs, in the
10622 application the system uses for this file type.
10624 When point is on a timestamp, open the agenda at the day
10627 When point is a footnote definition, move to the first reference
10628 found. If it is on a reference, move to the associated
10631 When point is on a headline, display a list of every link in the
10632 entry, so it is possible to pick one, or all, of them. If point
10633 is on a tag, call `org-tags-view' instead.
10635 When optional argument REFERENCE-BUFFER is non-nil, it should
10636 specify a buffer from where the link search should happen. This
10637 is used internally by `org-open-link-from-string'.
10639 On top of syntactically correct links, this function will open
10640 the link at point in comments or comment blocks and the first
10641 link in a property drawer line."
10643 ;; On a code block, open block's results.
10644 (unless (call-interactively 'org-babel-open-src-block-result)
10645 (org-load-modules-maybe)
10646 (move-marker org-open-link-marker (point))
10647 (setq org-window-config-before-follow-link (current-window-configuration))
10648 (org-remove-occur-highlights nil nil t)
10649 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10650 (let* ((context (org-element-context)) type value)
10651 ;; On an unsupported type, check if point is contained within
10653 (while (and (not (memq (setq type (org-element-type context))
10654 '(comment comment-block
10655 headline inlinetask link
10656 footnote-definition footnote-reference
10657 node-property timestamp)))
10658 (setq context (org-element-property :parent context))))
10659 (setq value (org-element-property :value context))
10661 ;; Blank lines at the beginning of buffer: bail out.
10662 ((not context) (user-error "No link found"))
10663 ;; Exception n°1: links in property drawers
10664 ((eq type 'node-property)
10665 (org-open-link-from-string
10666 (and (string-match org-any-link-re value)
10667 (match-string-no-properties 0 value))))
10668 ;; Exception n°2: links in comments.
10669 ((memq type '(comment comment-block))
10671 (skip-chars-forward "\\S-" (point-at-eol))
10672 (let ((string-rear (replace-regexp-in-string
10673 "^[ \t]*# [ \t]*" ""
10674 (buffer-substring (point) (line-beginning-position))))
10675 (string-front (buffer-substring (point) (line-end-position))))
10677 (let ((org-inhibit-startup t)) (org-mode))
10679 (goto-char (point-min))
10680 (when (and (search-forward string-rear nil t)
10681 (search-forward string-front (line-end-position) t))
10682 (goto-char (match-beginning 0))
10683 (org-open-at-point)
10684 (when (string= string-rear "") (forward-char)))))))
10685 ;; On a headline or an inlinetask, but not on a timestamp,
10686 ;; a link, a footnote reference or on tags.
10687 ((and (memq type '(headline inlinetask))
10689 (progn (save-excursion (beginning-of-line)
10690 (looking-at org-complex-heading-regexp))
10691 (or (not (match-beginning 5))
10692 (< (point) (match-beginning 5)))))
10693 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10695 (links-end (cdr data)))
10697 (dolist (link (if (stringp links) (list links) links))
10698 (search-forward link nil links-end)
10699 (goto-char (match-beginning 0))
10700 (org-open-at-point))
10701 (require 'org-attach)
10702 (org-attach-reveal 'if-exists))))
10703 ;; Do nothing on white spaces after an object, unless point
10704 ;; is right after it.
10707 (goto-char (org-element-property :end context))
10708 (skip-chars-backward " \t")
10710 (user-error "No link found"))
10711 ((eq type 'timestamp) (org-follow-timestamp-link))
10712 ;; On tags within a headline or an inlinetask.
10713 ((and (memq type '(headline inlinetask))
10714 (progn (save-excursion (beginning-of-line)
10715 (looking-at org-complex-heading-regexp))
10716 (and (match-beginning 5)
10717 (>= (point) (match-beginning 5)))))
10718 (org-tags-view arg (substring (match-string 5) 0 -1)))
10720 (let ((type (org-element-property :type context))
10721 (path (org-link-unescape (org-element-property :path context))))
10722 ;; Switch back to REFERENCE-BUFFER needed when called in
10723 ;; a temporary buffer through `org-open-link-from-string'.
10724 (with-current-buffer (or reference-buffer (current-buffer))
10726 ((equal type "file")
10727 (if (string-match "[*?{]" (file-name-nondirectory path))
10729 ;; Look into `org-link-protocols' in order to find
10730 ;; a DEDICATED-FUNCTION to open file. The function
10731 ;; will be applied on raw link instead of parsed
10732 ;; link due to the limitation in `org-add-link-type'
10733 ;; ("open" function called with a single argument).
10734 ;; If no such function is found, fallback to
10735 ;; `org-open-file'.
10737 ;; Note : "file+emacs" and "file+sys" types are
10738 ;; hard-coded in order to escape the previous
10740 (let* ((option (org-element-property :search-option context))
10741 (app (org-element-property :application context))
10742 (dedicated-function
10743 (nth 1 (assoc app org-link-protocols))))
10744 (if dedicated-function
10745 (funcall dedicated-function
10747 (and option (concat "::" option))))
10748 (apply 'org-open-file
10751 ((equal app "emacs") 'emacs)
10752 ((equal app "sys") 'system))
10753 (cond ((not option) nil)
10754 ((org-string-match-p "\\`[0-9]+\\'" option)
10755 (list (string-to-number option)))
10757 (org-link-unescape option)))))))))
10758 ((assoc type org-link-protocols)
10759 (funcall (nth 1 (assoc type org-link-protocols)) path))
10760 ((equal type "help")
10761 (let ((f-or-v (intern path)))
10762 (cond ((fboundp f-or-v) (describe-function f-or-v))
10763 ((boundp f-or-v) (describe-variable f-or-v))
10764 (t (error "Not a known function or variable")))))
10765 ((member type '("http" "https" "ftp" "mailto" "news"))
10766 (browse-url (org-link-escape-browser (concat type ":" path))))
10767 ((equal type "doi")
10769 (org-link-escape-browser (concat org-doi-server-url path))))
10770 ((equal type "message") (browse-url (concat type ":" path)))
10771 ((equal type "shell")
10772 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10774 (if (or (and (org-string-nw-p
10775 org-confirm-shell-link-not-regexp)
10777 org-confirm-shell-link-not-regexp cmd))
10778 (not org-confirm-shell-link-function)
10779 (funcall org-confirm-shell-link-function
10780 (format "Execute \"%s\" in shell? "
10781 (org-add-props cmd nil
10782 'face 'org-warning))))
10784 (message "Executing %s" cmd)
10785 (shell-command cmd buf)
10786 (when (featurep 'midnight)
10787 (setq clean-buffer-list-kill-buffer-names
10789 clean-buffer-list-kill-buffer-names))))
10790 (user-error "Abort"))))
10791 ((equal type "elisp")
10793 (if (or (and (org-string-nw-p
10794 org-confirm-elisp-link-not-regexp)
10795 (org-string-match-p
10796 org-confirm-elisp-link-not-regexp cmd))
10797 (not org-confirm-elisp-link-function)
10798 (funcall org-confirm-elisp-link-function
10799 (format "Execute \"%s\" as elisp? "
10800 (org-add-props cmd nil
10801 'face 'org-warning))))
10802 (message "%s => %s" cmd
10803 (if (eq (string-to-char cmd) ?\()
10805 (call-interactively (read cmd))))
10806 (user-error "Abort"))))
10809 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10810 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10811 (unless (run-hook-with-args-until-success
10812 'org-open-link-functions path)
10813 (if (not arg) (org-mark-ring-push)
10814 (switch-to-buffer-other-window
10815 (org-get-buffer-for-internal-link (current-buffer))))
10816 (let ((cmd `(org-link-search
10817 ,(if (member type '("custom-id" "coderef"))
10818 (org-element-property :raw-link context)
10820 ,(cond ((equal arg '(4)) 'occur)
10821 ((equal arg '(16)) 'org-occur))
10822 ,(org-element-property :begin context))))
10823 (condition-case nil
10824 (let ((org-link-search-inhibit-query t))
10826 (error (progn (widen) (eval cmd)))))))
10827 (t (browse-url-at-point))))))
10828 ;; On a footnote reference or at a footnote definition's label.
10829 ((or (eq type 'footnote-reference)
10830 (and (eq type 'footnote-definition)
10832 ;; Do not validate action when point is on the
10833 ;; spaces right after the footnote label, in
10834 ;; order to be on par with behaviour on links.
10835 (skip-chars-forward " \t")
10837 (org-element-property :contents-begin context)))
10838 (if begin (< (point) begin)
10839 (= (org-element-property :post-affiliated context)
10840 (line-beginning-position)))))))
10841 (org-footnote-action))
10842 (t (user-error "No link found")))))
10843 (move-marker org-open-link-marker nil)
10844 (run-hook-with-args 'org-follow-link-hook)))
10846 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10847 "Offer links in the current entry and return the selected link.
10848 If there is only one link, return it.
10849 If NTH is an integer, return the NTH link found.
10850 If ZERO is a string, check also this string for a link, and if
10851 there is one, return it."
10852 (with-current-buffer buffer
10858 (in-emacs (if (integerp nth) nil nth))
10859 have-zero end links link c)
10860 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10861 (push (match-string 0 zero) links)
10862 (setq cnt (1- cnt) have-zero t))
10864 (org-back-to-heading t)
10865 (setq end (save-excursion (outline-next-heading) (point)))
10866 (while (re-search-forward org-any-link-re end t)
10867 (push (match-string 0) links))
10868 (setq links (org-uniquify (reverse links))))
10871 (message "No links"))
10872 ((equal (length links) 1)
10873 (setq link (car links)))
10874 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10875 (setq link (nth (if have-zero nth (1- nth)) links)))
10876 (t ; we have to select a link
10878 (save-window-excursion
10879 (delete-other-windows)
10880 (with-output-to-temp-buffer "*Select Link*"
10882 (if (not (string-match org-bracket-link-regexp l))
10883 (princ (format "[%c] %s\n" (incf cnt)
10884 (org-remove-angle-brackets l)))
10886 (princ (format "[%c] %s (%s)\n" (incf cnt)
10887 (match-string 3 l) (match-string 1 l)))
10888 (princ (format "[%c] %s\n" (incf cnt)
10889 (match-string 1 l))))))
10891 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10892 (message "Select link to open, RET to open all:")
10893 (setq c (read-char-exclusive))
10894 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10895 (when (equal c ?q) (user-error "Abort"))
10896 (if (equal c ?\C-m)
10898 (setq nth (- c ?0))
10899 (if have-zero (setq nth (1+ nth)))
10900 (unless (and (integerp nth) (>= (length links) nth))
10901 (user-error "Invalid link selection"))
10902 (setq link (nth (1- nth) links)))))
10903 (cons link end))))))
10905 ;; TODO: These functions are deprecated since `org-open-at-point'
10906 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10907 (defun org-open-file-with-system (path)
10908 "Open file at PATH using the system way of opening it."
10909 (org-open-file path 'system))
10910 (defun org-open-file-with-emacs (path)
10911 "Open file at PATH in Emacs."
10912 (org-open-file path 'emacs))
10917 (defvar org-create-file-search-functions nil
10918 "List of functions to construct the right search string for a file link.
10919 These functions are called in turn with point at the location to
10920 which the link should point.
10922 A function in the hook should first test if it would like to
10923 handle this file type, for example by checking the `major-mode'
10924 or the file extension. If it decides not to handle this file, it
10925 should just return nil to give other functions a chance. If it
10926 does handle the file, it must return the search string to be used
10927 when following the link. The search string will be part of the
10928 file link, given after a double colon, and `org-open-at-point'
10929 will automatically search for it. If special measures must be
10930 taken to make the search successful, another function should be
10931 added to the companion hook `org-execute-file-search-functions',
10934 A function in this hook may also use `setq' to set the variable
10935 `description' to provide a suggestion for the descriptive text to
10936 be used for this link when it gets inserted into an Org-mode
10937 buffer with \\[org-insert-link].")
10939 (defvar org-execute-file-search-functions nil
10940 "List of functions to execute a file search triggered by a link.
10942 Functions added to this hook must accept a single argument, the
10943 search string that was part of the file link, the part after the
10944 double colon. The function must first check if it would like to
10945 handle this search, for example by checking the `major-mode' or
10946 the file extension. If it decides not to handle this search, it
10947 should just return nil to give other functions a chance. If it
10948 does handle the search, it must return a non-nil value to keep
10949 other functions from trying.
10951 Each function can access the current prefix argument through the
10952 variable `current-prefix-arg'. Note that a single prefix is used
10953 to force opening a link in Emacs, so it may be good to only use a
10954 numeric or double prefix to guide the search function.
10956 In case this is needed, a function in this hook can also restore
10957 the window configuration before `org-open-at-point' was called using:
10959 (set-window-configuration org-window-config-before-follow-link)")
10961 (defun org-link-search (s &optional type avoid-pos stealth)
10962 "Search for a link search option.
10963 If S is surrounded by forward slashes, it is interpreted as a
10964 regular expression. In org-mode files, this will create an `org-occur'
10965 sparse tree. In ordinary files, `occur' will be used to list matches.
10966 If the current buffer is in `dired-mode', grep will be used to search
10967 in all files. If AVOID-POS is given, ignore matches near that position.
10969 When optional argument STEALTH is non-nil, do not modify
10970 visibility around point, thus ignoring
10971 `org-show-hierarchy-above', `org-show-following-heading' and
10972 `org-show-siblings' variables."
10973 (let ((case-fold-search t)
10974 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10975 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10976 (append '(("") (" ") ("\t") ("\n"))
10977 org-emphasis-alist)
10980 (pre nil) (post nil)
10981 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10983 ;; First check if there are any special search functions
10984 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10985 ;; Now try the builtin stuff
10986 ((and (equal (string-to-char s0) ?#)
10989 (goto-char (point-min))
10992 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10993 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10994 (setq type 'dedicated
10995 pos (match-beginning 0))))
10996 ;; There is an exact target for this
10998 (org-back-to-heading t)))
11000 (goto-char (point-min))
11003 (concat "<<" (regexp-quote s0) ">>") nil t)
11004 (setq type 'dedicated
11005 pos (match-beginning 0))))
11006 ;; There is an exact target for this
11009 (goto-char (point-min))
11012 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
11013 (setq type 'dedicated pos (match-beginning 0))))
11014 ;; Found an element with a matching #+name affiliated keyword.
11016 ((and (string-match "^(\\(.*\\))$" s0)
11018 (goto-char (point-min))
11021 (concat "[^[]" (regexp-quote
11022 (format org-coderef-label-format
11023 (match-string 1 s0))))
11025 (setq type 'dedicated
11026 pos (1+ (match-beginning 0))))))
11027 ;; There is a coderef target for this
11029 ((string-match "^/\\(.*\\)/$" s)
11030 ;; A regular expression
11032 ((derived-mode-p 'org-mode)
11033 (org-occur (match-string 1 s)))
11034 (t (org-do-occur (match-string 1 s)))))
11035 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
11036 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
11037 (goto-char (point-min))
11039 ((let (case-fold-search)
11040 (re-search-forward (format org-complex-heading-regexp-format
11043 ;; OK, found a match
11044 (setq type 'dedicated)
11045 (goto-char (match-beginning 0)))
11046 ((and (not org-link-search-inhibit-query)
11047 (eq org-link-search-must-match-exact-headline 'query-to-create)
11048 (y-or-n-p "No match - create this as a new heading? "))
11049 (goto-char (point-max))
11050 (or (bolp) (newline))
11051 (insert "* " s "\n")
11052 (beginning-of-line 0))
11055 (error "No match"))))
11057 ;; A normal search string
11058 (when (equal (string-to-char s) ?*)
11059 ;; Anchor on headlines, post may include tags.
11060 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
11061 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
11062 s (substring s 1)))
11063 (remove-text-properties
11065 '(face nil mouse-face nil keymap nil fontified nil) s)
11066 ;; Make a series of regular expressions to find a match
11067 (setq words (org-split-string s "[ \n\r\t]+")
11069 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11070 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11072 re2a_ (concat "\\(" (mapconcat 'downcase words
11073 "[ \t\r\n]+") "\\)[ \t\r\n]")
11074 re2a (concat "[ \t\r\n]" re2a_)
11075 re4_ (concat "\\(" (mapconcat 'downcase words
11076 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11077 re4 (concat "[^a-zA-Z_]" re4_)
11079 re1 (concat pre re2 post)
11080 re3 (concat pre (if pre re4_ re4) post)
11081 re5 (concat pre ".*" re4)
11082 re2 (concat pre re2)
11083 re2a (concat pre (if pre re2a_ re2a))
11084 re4 (concat pre (if pre re4_ re4))
11085 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
11086 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
11089 ((eq type 'org-occur) (org-occur reall))
11090 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11091 (t (goto-char (point-min))
11093 (if (or (and (org-search-not-self 1 re0 nil t)
11094 (setq type 'dedicated))
11095 (org-search-not-self 1 re1 nil t)
11096 (org-search-not-self 1 re2 nil t)
11097 (org-search-not-self 1 re2a nil t)
11098 (org-search-not-self 1 re3 nil t)
11099 (org-search-not-self 1 re4 nil t)
11100 (org-search-not-self 1 re5 nil t))
11101 (goto-char (match-beginning 1))
11103 (error "No match"))))))
11104 (and (derived-mode-p 'org-mode)
11106 (org-show-context 'link-search))
11109 (defun org-search-not-self (group &rest args)
11110 "Execute `re-search-forward', but only accept matches that do not
11111 enclose the position of `org-open-link-marker'."
11112 (let ((m org-open-link-marker))
11114 (while (apply 're-search-forward args)
11115 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11116 (goto-char (match-end group))
11117 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11118 (> (match-beginning 0) (marker-position m))
11119 (< (match-end 0) (marker-position m)))
11121 (or (not (org-in-regexp
11122 org-bracket-link-analytic-regexp 1))
11123 (not (match-end 4)) ; no description
11124 (and (<= (match-beginning 4) (point))
11125 (>= (match-end 4) (point))))))
11126 (throw 'exit (point))))))))
11128 (defun org-get-buffer-for-internal-link (buffer)
11129 "Return a buffer to be used for displaying the link target of internal links."
11131 ((not org-display-internal-link-with-indirect-buffer)
11133 ((string-match "(Clone)$" (buffer-name buffer))
11134 (message "Buffer is already a clone, not making another one")
11135 ;; we also do not modify visibility in this case
11137 (t ; make a new indirect buffer for displaying the link
11138 (let* ((bn (buffer-name buffer))
11139 (ibn (concat bn "(Clone)"))
11140 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11141 (with-current-buffer ib (org-overview))
11144 (defun org-do-occur (regexp &optional cleanup)
11145 "Call the Emacs command `occur'.
11146 If CLEANUP is non-nil, remove the printout of the regular expression
11147 in the *Occur* buffer. This is useful if the regex is long and not useful
11151 (let ((cwin (selected-window)) win beg end)
11152 (when (setq win (get-buffer-window "*Occur*"))
11153 (select-window win))
11154 (goto-char (point-min))
11155 (when (re-search-forward "match[a-z]+" nil t)
11156 (setq beg (match-end 0))
11157 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11158 (setq end (1- (match-beginning 0)))))
11159 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11160 (goto-char (point-min))
11161 (select-window cwin))))
11163 ;;; The mark ring for links jumps
11165 (defvar org-mark-ring nil
11166 "Mark ring for positions before jumps in Org-mode.")
11167 (defvar org-mark-ring-last-goto nil
11168 "Last position in the mark ring used to go back.")
11169 ;; Fill and close the ring
11170 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11171 (loop for i from 1 to org-mark-ring-length do
11172 (push (make-marker) org-mark-ring))
11173 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11176 (defun org-mark-ring-push (&optional pos buffer)
11177 "Put the current position or POS into the mark ring and rotate it."
11179 (setq pos (or pos (point)))
11180 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11181 (move-marker (car org-mark-ring)
11183 (or buffer (current-buffer)))
11185 (substitute-command-keys
11186 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11188 (defun org-mark-ring-goto (&optional n)
11189 "Jump to the previous position in the mark ring.
11190 With prefix arg N, jump back that many stored positions. When
11191 called several times in succession, walk through the entire ring.
11192 Org-mode commands jumping to a different position in the current file,
11193 or to another Org-mode file, automatically push the old position
11197 (if (eq last-command this-command)
11198 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11199 (setq p org-mark-ring))
11200 (setq org-mark-ring-last-goto p)
11202 (org-pop-to-buffer-same-window (marker-buffer m))
11204 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11206 (defun org-remove-angle-brackets (s)
11207 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11208 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11210 (defun org-add-angle-brackets (s)
11211 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11212 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11214 (defun org-remove-double-quotes (s)
11215 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11216 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11219 ;;; Following specific links
11221 (defun org-follow-timestamp-link ()
11222 "Open an agenda view for the time-stamp date/range at point."
11224 ((org-at-date-range-p t)
11225 (let ((org-agenda-start-on-weekday)
11226 (t1 (match-string 1))
11227 (t2 (match-string 2)) tt1 tt2)
11228 (setq tt1 (time-to-days (org-time-string-to-time t1))
11229 tt2 (time-to-days (org-time-string-to-time t2)))
11230 (let ((org-agenda-buffer-tmp-name
11231 (format "*Org Agenda(a:%s)"
11232 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11233 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11234 ((org-at-timestamp-p t)
11235 (let ((org-agenda-buffer-tmp-name
11236 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11237 (org-agenda-list nil (time-to-days (org-time-string-to-time
11238 (substring (match-string 1) 0 10)))
11240 (t (error "This should not happen"))))
11243 ;;; Following file links
11244 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11245 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11246 (declare-function mailcap-mime-info
11247 "mailcap" (string &optional request no-decode))
11248 (defvar org-wait nil)
11249 (defun org-open-file (path &optional in-emacs line search)
11250 "Open the file at PATH.
11251 First, this expands any special file name abbreviations. Then the
11252 configuration variable `org-file-apps' is checked if it contains an
11253 entry for this file type, and if yes, the corresponding command is launched.
11255 If no application is found, Emacs simply visits the file.
11257 With optional prefix argument IN-EMACS, Emacs will visit the file.
11258 With a double \\[universal-argument] \\[universal-argument] \
11259 prefix arg, Org tries to avoid opening in Emacs
11260 and to use an external application to visit the file.
11262 Optional LINE specifies a line to go to, optional SEARCH a string
11263 to search for. If LINE or SEARCH is given, the file will be
11264 opened in Emacs, unless an entry from org-file-apps that makes
11265 use of groups in a regexp matches.
11267 If you want to change the way frames are used when following a
11268 link, please customize `org-link-frame-setup'.
11270 If the file does not exist, an error is thrown."
11271 (let* ((file (if (equal path "")
11273 (substitute-in-file-name (expand-file-name path))))
11274 (file-apps (append org-file-apps (org-default-apps)))
11275 (apps (org-remove-if
11276 'org-file-apps-entry-match-against-dlink-p file-apps))
11277 (apps-dlink (org-remove-if-not
11278 'org-file-apps-entry-match-against-dlink-p file-apps))
11279 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11280 (dirp (if remp nil (file-directory-p file)))
11281 (file (if (and dirp org-open-directory-means-index-dot-org)
11282 (concat (file-name-as-directory file) "index.org")
11284 (a-m-a-p (assq 'auto-mode apps))
11285 (dfile (downcase file))
11286 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11287 (link (cond ((and (eq line nil)
11291 (concat file "::" (number-to-string line)))
11293 (concat file "::" search))))
11294 (dlink (downcase link))
11295 (old-buffer (current-buffer))
11297 (old-mode major-mode)
11298 ext cmd link-match-data)
11299 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11300 (setq ext (match-string 1 dfile))
11301 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11302 (setq ext (match-string 1 dfile))))
11304 ((member in-emacs '((16) system))
11305 (setq cmd (cdr (assoc 'system apps))))
11306 (in-emacs (setq cmd 'emacs))
11308 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11309 (and dirp (cdr (assoc 'directory apps)))
11310 ; first, try matching against apps-dlink
11311 ; if we get a match here, store the match data for later
11312 (let ((match (assoc-default dlink apps-dlink
11315 (progn (setq link-match-data (match-data))
11317 (progn (setq in-emacs (or in-emacs line search))
11318 nil))) ; if we have no match in apps-dlink,
11319 ; always open the file in emacs if line or search
11320 ; is given (for backwards compatibility)
11321 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11323 (cdr (assoc ext apps))
11324 (cdr (assoc t apps))))))
11325 (when (eq cmd 'system)
11326 (setq cmd (cdr (assoc 'system apps))))
11327 (when (eq cmd 'default)
11328 (setq cmd (cdr (assoc t apps))))
11329 (when (eq cmd 'mailcap)
11331 (mailcap-parse-mailcaps)
11332 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11333 (command (mailcap-mime-info mime-type)))
11334 (if (stringp command)
11336 (setq cmd 'emacs))))
11337 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11338 (not (file-exists-p file))
11339 (not org-open-non-existing-files))
11340 (user-error "No such file: %s" file))
11342 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11343 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11344 (while (string-match "['\"]%s['\"]" cmd)
11345 (setq cmd (replace-match "%s" t t cmd)))
11346 (while (string-match "%s" cmd)
11347 (setq cmd (replace-match
11349 (shell-quote-argument
11350 (convert-standard-filename file)))
11353 ;; Replace "%1", "%2" etc. in command with group matches from regex
11355 (let ((match-index 1)
11356 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11357 (set-match-data link-match-data)
11358 (while (<= match-index number-of-groups)
11359 (let ((regex (concat "%" (number-to-string match-index)))
11360 (replace-with (match-string match-index dlink)))
11361 (while (string-match regex cmd)
11362 (setq cmd (replace-match replace-with t t cmd))))
11363 (setq match-index (+ match-index 1)))))
11365 (save-window-excursion
11366 (message "Running %s...done" cmd)
11367 (start-process-shell-command cmd nil cmd)
11368 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11371 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11373 (if line (progn (org-goto-line line)
11374 (if (derived-mode-p 'org-mode)
11376 (if search (org-link-search search))))
11378 (let ((file (convert-standard-filename file)))
11380 (set-match-data link-match-data)
11382 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11383 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11384 (or (not (equal old-buffer (current-buffer)))
11385 (not (equal old-pos (point))))
11386 (org-mark-ring-push old-pos old-buffer))))
11388 (defun org-file-apps-entry-match-against-dlink-p (entry)
11389 "This function returns non-nil if `entry' uses a regular
11390 expression which should be matched against the whole link by
11393 It assumes that is the case when the entry uses a regular
11394 expression which has at least one grouping construct and the
11395 action is either a lisp form or a command string containing
11396 '%1', i.e. using at least one subexpression match as a
11398 (let ((selector (car entry))
11399 (action (cdr entry)))
11400 (if (stringp selector)
11401 (and (> (regexp-opt-depth selector) 0)
11402 (or (and (stringp action)
11403 (string-match "%[0-9]" action))
11407 (defun org-default-apps ()
11408 "Return the default applications for this operating system."
11410 ((eq system-type 'darwin)
11411 org-file-apps-defaults-macosx)
11412 ((eq system-type 'windows-nt)
11413 org-file-apps-defaults-windowsnt)
11414 (t org-file-apps-defaults-gnu)))
11416 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11417 "Convert extensions to regular expressions in the cars of LIST.
11418 Also, weed out any non-string entries, because the return value is used
11419 only for regexp matching.
11420 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11421 point to the symbol `emacs', indicating that the file should
11422 be opened in Emacs."
11425 (mapcar (lambda (x)
11426 (if (not (stringp (car x)))
11428 (if (string-match "\\W" (car x))
11430 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11433 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11435 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11436 (defun org-file-remote-p (file)
11437 "Test whether FILE specifies a location on a remote system.
11438 Return non-nil if the location is indeed remote.
11440 For example, the filename \"/user@host:/foo\" specifies a location
11441 on the system \"/user@host:\"."
11442 (cond ((fboundp 'file-remote-p)
11443 (file-remote-p file))
11444 ((fboundp 'tramp-handle-file-remote-p)
11445 (tramp-handle-file-remote-p file))
11446 ((and (boundp 'ange-ftp-name-format)
11447 (string-match (car ange-ftp-name-format) file))
11453 (defun org-get-org-file ()
11454 "Read a filename, with default directory `org-directory'."
11455 (let ((default (or org-default-notes-file remember-data-file)))
11456 (read-file-name (format "File name [%s]: " default)
11457 (file-name-as-directory org-directory)
11460 (defun org-notes-order-reversed-p ()
11461 "Check if the current file should receive notes in reversed order."
11463 ((not org-reverse-note-order) nil)
11464 ((eq t org-reverse-note-order) t)
11465 ((not (listp org-reverse-note-order)) nil)
11467 (let ((all org-reverse-note-order)
11469 (while (setq entry (pop all))
11470 (if (string-match (car entry) buffer-file-name)
11471 (throw 'exit (cdr entry))))
11474 (defvar org-refile-target-table nil
11475 "The list of refile targets, created by `org-refile'.")
11477 (defvar org-agenda-new-buffers nil
11478 "Buffers created to visit agenda files.")
11480 (defvar org-refile-cache nil
11481 "Cache for refile targets.")
11483 (defvar org-refile-markers nil
11484 "All the markers used for caching refile locations.")
11486 (defun org-refile-marker (pos)
11487 "Get a new refile marker, but only if caching is in use."
11488 (if (not org-refile-use-cache)
11490 (let ((m (make-marker)))
11491 (move-marker m pos)
11492 (push m org-refile-markers)
11495 (defun org-refile-cache-clear ()
11496 "Clear the refile cache and disable all the markers."
11497 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11498 (setq org-refile-markers nil)
11499 (setq org-refile-cache nil)
11500 (message "Refile cache has been cleared"))
11502 (defun org-refile-cache-check-set (set)
11503 "Check if all the markers in the cache still have live buffers."
11506 (while (and set (setq marker (nth 3 (pop set))))
11507 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11508 (when (and marker (null (marker-buffer marker)))
11509 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11511 (throw 'exit nil)))
11514 (defun org-refile-cache-put (set &rest identifiers)
11515 "Push the refile targets SET into the cache, under IDENTIFIERS."
11516 (let* ((key (sha1 (prin1-to-string identifiers)))
11517 (entry (assoc key org-refile-cache)))
11520 (push (cons key set) org-refile-cache))))
11522 (defun org-refile-cache-get (&rest identifiers)
11523 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11525 ((not org-refile-cache) nil)
11526 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11528 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11529 org-refile-cache))))
11530 (and set (org-refile-cache-check-set set) set)))))
11532 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11533 "Produce a table with refile targets."
11534 (let ((case-fold-search nil)
11535 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11536 (entries (or org-refile-targets '((nil . (:level . 1)))))
11537 targets tgs txt re files f desc descre fast-path-p level pos0)
11538 (message "Getting targets...")
11539 (with-current-buffer (or default-buffer (current-buffer))
11540 (while (setq entry (pop entries))
11541 (setq files (car entry) desc (cdr entry))
11542 (setq fast-path-p nil)
11544 ((null files) (setq files (list (current-buffer))))
11545 ((eq files 'org-agenda-files)
11546 (setq files (org-agenda-files 'unrestricted)))
11547 ((and (symbolp files) (fboundp files))
11548 (setq files (funcall files)))
11549 ((and (symbolp files) (boundp files))
11550 (setq files (symbol-value files))))
11551 (if (stringp files) (setq files (list files)))
11553 ((eq (car desc) :tag)
11554 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11555 ((eq (car desc) :todo)
11556 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11557 ((eq (car desc) :regexp)
11558 (setq descre (cdr desc)))
11559 ((eq (car desc) :level)
11560 (setq descre (concat "^\\*\\{" (number-to-string
11561 (if org-odd-levels-only
11562 (1- (* 2 (cdr desc)))
11565 ((eq (car desc) :maxlevel)
11566 (setq fast-path-p t)
11567 (setq descre (concat "^\\*\\{1," (number-to-string
11568 (if org-odd-levels-only
11569 (1- (* 2 (cdr desc)))
11572 (t (error "Bad refiling target description %s" desc)))
11573 (while (setq f (pop files))
11574 (with-current-buffer
11575 (if (bufferp f) f (org-get-agenda-file-buffer f))
11577 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11579 (if (bufferp f) (setq f (buffer-file-name
11580 (buffer-base-buffer f))))
11581 (setq f (and f (expand-file-name f)))
11582 (if (eq org-refile-use-outline-path 'file)
11583 (push (list (file-name-nondirectory f) f nil nil) tgs))
11587 (goto-char (point-min))
11588 (while (re-search-forward descre nil t)
11589 (goto-char (setq pos0 (point-at-bol)))
11591 (when org-refile-target-verify-function
11593 (or (funcall org-refile-target-verify-function)
11595 (when (and (looking-at org-complex-heading-regexp)
11596 (not (member (match-string 4) excluded-entries))
11598 (setq level (org-reduced-level
11599 (- (match-end 1) (match-beginning 1)))
11600 txt (org-link-display-format (match-string 4))
11601 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11602 re (format org-complex-heading-regexp-format
11603 (regexp-quote (match-string 4))))
11604 (when org-refile-use-outline-path
11605 (setq txt (mapconcat
11608 (if (eq org-refile-use-outline-path
11610 (list (file-name-nondirectory
11612 (buffer-base-buffer))))
11613 (if (eq org-refile-use-outline-path
11615 (list (buffer-file-name
11616 (buffer-base-buffer)))))
11617 (org-get-outline-path fast-path-p
11621 (push (list txt f re (org-refile-marker (point)))
11623 (when (= (point) pos0)
11624 ;; verification function has not moved point
11625 (goto-char (point-at-eol))))))))
11626 (when org-refile-use-cache
11627 (org-refile-cache-put tgs (buffer-file-name) descre))
11628 (setq targets (append tgs targets))))))
11629 (message "Getting targets...done")
11630 (nreverse targets)))
11632 (defun org-protect-slash (s)
11633 (while (string-match "/" s)
11634 (setq s (replace-match "\\" t t s)))
11637 (defvar org-olpa (make-vector 20 nil))
11639 (defun org-get-outline-path (&optional fastp level heading)
11640 "Return the outline path to the current entry, as a list.
11642 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11643 routine which makes outline path derivations for an entire file,
11644 avoiding backtracing. Refile target collection makes use of that."
11648 (error "Outline path failure, more than 19 levels"))
11649 (loop for i from level upto 19 do
11650 (aset org-olpa i nil))
11652 (delq nil (append org-olpa nil))
11653 (aset org-olpa level heading)))
11654 (let (rtn case-fold-search)
11658 (while (org-up-heading-safe)
11659 (when (looking-at org-complex-heading-regexp)
11661 (replace-regexp-in-string
11662 ;; Remove statistical/checkboxes cookies
11663 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11664 (org-match-string-no-properties 4)))
11668 (defun org-format-outline-path (path &optional width prefix separator)
11669 "Format the outline path PATH for display.
11670 WIDTH is the maximum number of characters that is available.
11671 PREFIX is a prefix to be included in the returned string,
11672 such as the file name.
11673 SEPARATOR is inserted between the different parts of the path,
11674 the default is \"/\"."
11675 (setq width (or width 79))
11676 (if prefix (setq width (- width (length prefix))))
11679 (let* ((nsteps (length path))
11680 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11681 (maxwidth (if (<= total-width width)
11682 10000 ;; everything fits
11683 ;; we need to shorten the level headings
11684 (/ (- width nsteps) nsteps)))
11685 (org-odd-levels-only nil)
11687 (total (1+ (length prefix))))
11688 (setq maxwidth (max maxwidth 10))
11690 (if prefix (or separator "/"))
11694 (if (and (= n nsteps) (< maxwidth 10000))
11695 (setq maxwidth (- total-width total)))
11696 (if (< (length h) maxwidth)
11697 (progn (setq total (+ total (length h) 1)) h)
11698 (setq h (substring h 0 (- maxwidth 2))
11699 total (+ total maxwidth 1))
11700 (if (string-match "[ \t]+\\'" h)
11701 (setq h (substring h 0 (match-beginning 0))))
11702 (setq h (concat h "..")))
11703 (org-add-props h nil 'face
11704 (nth (% (1- n) org-n-level-faces)
11707 path (or separator "/"))))))
11709 (defun org-display-outline-path (&optional file current separator just-return-string)
11710 "Display the current outline path in the echo area.
11712 If FILE is non-nil, prepend the output with the file name.
11713 If CURRENT is non-nil, append the current heading to the output.
11714 SEPARATOR is passed through to `org-format-outline-path'. It separates
11715 the different parts of the path and defaults to \"/\".
11716 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11718 (let* (case-fold-search
11719 (bfn (buffer-file-name (buffer-base-buffer)))
11720 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11722 (if current (setq path (append path
11724 (org-back-to-heading t)
11725 (if (looking-at org-complex-heading-regexp)
11726 (list (match-string 4)))))))
11728 (org-format-outline-path
11731 (and file bfn (concat (file-name-nondirectory bfn) separator))
11733 (if just-return-string
11734 (org-no-properties res)
11735 (org-unlogged-message "%s" res))))
11737 (defvar org-refile-history nil
11738 "History for refiling operations.")
11740 (defvar org-after-refile-insert-hook nil
11741 "Hook run after `org-refile' has inserted its stuff at the new location.
11742 Note that this is still *before* the stuff will be removed from
11743 the *old* location.")
11745 (defvar org-capture-last-stored-marker)
11746 (defvar org-refile-keep nil
11747 "Non-nil means `org-refile' will copy instead of refile.")
11750 "Like `org-refile', but copy."
11752 (let ((org-refile-keep t))
11753 (funcall 'org-refile nil nil nil "Copy")))
11755 (defun org-refile (&optional arg default-buffer rfloc msg)
11756 "Move the entry or entries at point to another heading.
11757 The list of target headings is compiled using the information in
11758 `org-refile-targets', which see.
11760 At the target location, the entry is filed as a subitem of the
11761 target heading. Depending on `org-reverse-note-order', the new
11762 subitem will either be the first or the last subitem.
11764 If there is an active region, all entries in that region will be
11765 refiled. However, the region must fulfill the requirement that
11766 the first heading sets the top-level of the moved text.
11768 With prefix arg ARG, the command will only visit the target
11769 location and not actually move anything.
11771 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11772 refiling operation has put the subtree.
11774 With a numeric prefix argument of `2', refile to the running clock.
11776 With a numeric prefix argument of `3', emulate `org-refile-keep'
11777 being set to `t' and copy to the target location, don't move it.
11778 Beware that keeping refiled entries may result in duplicated ID
11781 RFLOC can be a refile location obtained in a different way.
11783 MSG is a string to replace \"Refile\" in the default prompt with
11784 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11786 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11788 If you are using target caching (see `org-refile-use-cache'), you
11789 have to clear the target cache in order to find new targets.
11790 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11791 prefix argument (`C-u C-u C-u C-c C-w')."
11793 (if (member arg '(0 (64)))
11794 (org-refile-cache-clear)
11795 (let* ((actionmsg (cond (msg msg)
11796 ((equal arg 3) "Refile (and keep)")
11798 (cbuf (current-buffer))
11799 (regionp (org-region-active-p))
11800 (region-start (and regionp (region-beginning)))
11801 (region-end (and regionp (region-end)))
11802 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11803 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11804 pos it nbuf file re level reversed)
11805 (setq last-command nil)
11807 (goto-char region-start)
11808 (or (bolp) (goto-char (point-at-bol)))
11809 (setq region-start (point))
11810 (unless (or (org-kill-is-subtree-p
11811 (buffer-substring region-start region-end))
11812 (prog1 org-refile-active-region-within-subtree
11813 (let ((s (point-at-eol)))
11814 (org-toggle-heading)
11815 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11816 (user-error "The region is not a (sequence of) subtree(s)")))
11817 (if (equal arg '(16))
11818 (org-refile-goto-last-stored)
11821 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11823 (setq it (list (or org-clock-heading "running clock")
11825 (marker-buffer org-clock-hd-marker))
11827 (marker-position org-clock-hd-marker)))
11830 (let (heading-text)
11832 (unless (and arg (listp arg))
11833 (org-back-to-heading t)
11835 (replace-regexp-in-string
11836 org-bracket-link-regexp
11838 (nth 4 (org-heading-components)))))
11839 (org-refile-get-location
11840 (cond ((and arg (listp arg)) "Goto")
11841 (regionp (concat actionmsg " region to"))
11842 (t (concat actionmsg " subtree \""
11843 heading-text "\" to")))
11845 (and (not (equal '(4) arg))
11846 org-refile-allow-creating-parent-nodes)
11848 (setq file (nth 1 it)
11853 (equal (buffer-file-name) file)
11855 (and (>= pos region-start)
11856 (<= pos region-end))
11857 (and (>= pos (point))
11858 (< pos (save-excursion
11859 (org-end-of-subtree t t))))))
11860 (error "Cannot refile to position inside the tree or region"))
11861 (setq nbuf (or (find-buffer-visiting file)
11862 (find-file-noselect file)))
11863 (if (and arg (not (equal arg 3)))
11865 (org-pop-to-buffer-same-window nbuf)
11867 (org-show-context 'org-goto))
11870 (org-kill-new (buffer-substring region-start region-end))
11871 (org-save-markers-in-region region-start region-end))
11872 (org-copy-subtree 1 nil t))
11873 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11874 (find-file-noselect file)))
11875 (setq reversed (org-notes-order-reversed-p))
11882 (looking-at org-outline-regexp)
11883 (setq level (org-get-valid-level (funcall outline-level) 1))
11886 (or (outline-next-heading) (point-max))
11887 (or (save-excursion (org-get-next-sibling))
11888 (org-end-of-subtree t t)
11892 (goto-char (point-max))
11893 (goto-char (point-min))
11894 (or (outline-next-heading) (goto-char (point-max)))))
11895 (if (not (bolp)) (newline))
11896 (org-paste-subtree level nil nil t)
11897 (when org-log-refile
11898 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11899 (unless (eq org-log-refile 'note)
11900 (save-excursion (org-add-log-note))))
11901 (and org-auto-align-tags
11902 (let ((org-loop-over-headlines-in-active-region nil))
11903 (org-set-tags nil t)))
11904 (let ((bookmark-name (plist-get org-bookmark-names-plist
11906 (when bookmark-name
11907 (with-demoted-errors
11908 (bookmark-set bookmark-name))))
11909 ;; If we are refiling for capture, make sure that the
11910 ;; last-capture pointers point here
11911 (when (org-bound-and-true-p org-refile-for-capture)
11912 (let ((bookmark-name (plist-get org-bookmark-names-plist
11913 :last-capture-marker)))
11914 (when bookmark-name
11915 (with-demoted-errors
11916 (bookmark-set bookmark-name))))
11917 (move-marker org-capture-last-stored-marker (point)))
11918 (if (fboundp 'deactivate-mark) (deactivate-mark))
11919 (run-hooks 'org-after-refile-insert-hook))))
11920 (unless org-refile-keep
11922 (delete-region (point) (+ (point) (- region-end region-start)))
11924 (and (org-back-to-heading t) (point))
11925 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11926 (when (featurep 'org-inlinetask)
11927 (org-inlinetask-remove-END-maybe))
11928 (setq org-markers-to-move nil)
11929 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11931 (defun org-refile-goto-last-stored ()
11932 "Go to the location where the last refile was stored."
11934 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11935 (message "This is the location of the last refile"))
11937 (defun org-refile--get-location (refloc tbl)
11938 "When user refile to REFLOC, find the associated target in TBL.
11939 Also check `org-refile-target-table'."
11943 (lambda (r) (or (assoc r tbl)
11944 (assoc r org-refile-target-table)))
11945 (list (replace-regexp-in-string "/$" "" refloc)
11946 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11948 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11950 "Prompt the user for a refile location, using PROMPT.
11951 PROMPT should not be suffixed with a colon and a space, because
11952 this function appends the default value from
11953 `org-refile-history' automatically, if that is not empty.
11954 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11955 this is used for the GOTO interface."
11956 (let ((org-refile-targets org-refile-targets)
11957 (org-refile-use-outline-path org-refile-use-outline-path)
11959 (when (and (derived-mode-p 'org-mode)
11960 (not org-refile-use-cache)
11964 (setq excluded-entries
11965 (append excluded-entries (list (org-get-heading t t)))))))
11966 (setq org-refile-target-table
11967 (org-refile-get-targets default-buffer excluded-entries)))
11968 (unless org-refile-target-table
11969 (user-error "No refile targets"))
11970 (let* ((cbuf (current-buffer))
11971 (partial-completion-mode nil)
11972 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11973 (cfunc (if (and org-refile-use-outline-path
11974 org-outline-path-complete-in-steps)
11975 'org-olpath-completing-read
11976 'org-icompleting-read))
11977 (extra (if org-refile-use-outline-path "/" ""))
11978 (cbnex (concat (buffer-name) extra))
11979 (filename (and cfn (expand-file-name cfn)))
11982 (if (and (not (member org-refile-use-outline-path
11983 '(file full-file-path)))
11984 (not (equal filename (nth 1 x))))
11985 (cons (concat (car x) extra " ("
11986 (file-name-nondirectory (nth 1 x)) ")")
11988 (cons (concat (car x) extra) (cdr x))))
11989 org-refile-target-table))
11990 (completion-ignore-case t)
11992 (prompt (concat prompt
11993 (or (and (car org-refile-history)
11994 (concat " (default " (car org-refile-history) ")"))
11995 (and (assoc cbnex tbl) (setq cdef cbnex)
11996 (concat " (default " cbnex ")"))) ": "))
11997 pa answ parent-target child parent old-hist)
11998 (setq old-hist org-refile-history)
11999 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12000 nil 'org-refile-history (or cdef (car org-refile-history))))
12001 (if (setq pa (org-refile--get-location answ tbl))
12003 (org-refile-check-position pa)
12004 (when (or (not org-refile-history)
12005 (not (eq old-hist org-refile-history))
12006 (not (equal (car pa) (car org-refile-history))))
12007 (setq org-refile-history
12008 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12010 (cdr org-refile-history))))
12011 (if (equal (car org-refile-history) (nth 1 org-refile-history))
12012 (pop org-refile-history)))
12014 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12016 (setq parent (match-string 1 answ)
12017 child (match-string 2 answ))
12018 (setq parent-target (org-refile--get-location parent tbl))
12019 (when (and parent-target
12020 (or (eq new-nodes t)
12021 (and (eq new-nodes 'confirm)
12022 (y-or-n-p (format "Create new node \"%s\"? "
12024 (org-refile-new-child parent-target child)))
12025 (user-error "Invalid target location")))))
12027 (declare-function org-string-nw-p "org-macs" (s))
12028 (defun org-refile-check-position (refile-pointer)
12029 "Check if the refile pointer matches the headline to which it points."
12030 (let* ((file (nth 1 refile-pointer))
12031 (re (nth 2 refile-pointer))
12032 (pos (nth 3 refile-pointer))
12034 (if (and (not (markerp pos)) (not file))
12035 (user-error "Please indicate a target file in the refile path")
12036 (when (org-string-nw-p re)
12037 (setq buffer (if (markerp pos)
12038 (marker-buffer pos)
12039 (or (find-buffer-visiting file)
12040 (find-file-noselect file))))
12041 (with-current-buffer buffer
12046 (beginning-of-line 1)
12047 (unless (org-looking-at-p re)
12048 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12050 (defun org-refile-new-child (parent-target child)
12051 "Use refile target PARENT-TARGET to add new CHILD below it."
12052 (unless parent-target
12053 (error "Cannot find parent for new node"))
12054 (let ((file (nth 1 parent-target))
12055 (pos (nth 3 parent-target))
12057 (with-current-buffer (or (find-buffer-visiting file)
12058 (find-file-noselect file))
12064 (goto-char (point-max))
12065 (if (not (bolp)) (newline)))
12066 (when (looking-at org-outline-regexp)
12067 (setq level (funcall outline-level))
12068 (org-end-of-subtree t t))
12069 (org-back-over-empty-lines)
12070 (insert "\n" (make-string
12071 (if pos (org-get-valid-level level 1) 1) ?*)
12073 (beginning-of-line 0)
12074 (list (concat (car parent-target) "/" child) file "" (point)))))))
12076 (defun org-olpath-completing-read (prompt collection &rest args)
12077 "Read an outline path like a file name."
12078 (let ((thetable collection)
12079 (org-completion-use-ido nil) ; does not work with ido.
12080 (org-completion-use-iswitchb nil)) ; or iswitchb
12082 'org-icompleting-read prompt
12083 (lambda (string predicate &optional flag)
12084 (let (rtn r f (l (length string)))
12088 (try-completion string thetable))
12091 (setq rtn (all-completions string thetable predicate))
12094 (setq r (substring x l))
12095 (if (string-match " ([^)]*)$" x)
12096 (setq f (match-string 0 x))
12098 (if (string-match "/" r)
12099 (concat string (substring r 0 (match-end 0)) f)
12104 (assoc string thetable)))))
12107 ;;;; Dynamic blocks
12109 (defun org-find-dblock (name)
12110 "Find the first dynamic block with name NAME in the buffer.
12111 If not found, stay at current position and return nil."
12112 (let ((case-fold-search t) pos)
12114 (goto-char (point-min))
12115 (setq pos (and (re-search-forward
12116 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12117 (match-beginning 0))))
12118 (if pos (goto-char pos))
12121 (defun org-create-dblock (plist)
12122 "Create a dynamic block section, with parameters taken from PLIST.
12123 PLIST must contain a :name entry which is used as the name of the block."
12124 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12127 (let ((col (current-column))
12128 (name (plist-get plist :name)))
12129 (insert "#+BEGIN: " name)
12131 (if (eq (car plist) :name)
12132 (setq plist (cddr plist))
12133 (insert " " (prin1-to-string (pop plist)))))
12134 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12135 (beginning-of-line -2)))
12137 (defun org-prepare-dblock ()
12138 "Prepare dynamic block for refresh.
12139 This empties the block, puts the cursor at the insert position and returns
12140 the property list including an extra property :name with the block name."
12141 (unless (looking-at org-dblock-start-re)
12142 (user-error "Not at a dynamic block"))
12143 (let* ((begdel (1+ (match-end 0)))
12144 (name (org-no-properties (match-string 1)))
12145 (params (append (list :name name)
12146 (read (concat "(" (match-string 3) ")")))))
12148 (beginning-of-line 1)
12149 (skip-chars-forward " \t")
12150 (setq params (plist-put params :indentation-column (current-column))))
12151 (unless (re-search-forward org-dblock-end-re nil t)
12152 (error "Dynamic block not terminated"))
12155 (list :content (buffer-substring
12156 begdel (match-beginning 0)))))
12157 (delete-region begdel (match-beginning 0))
12162 (defun org-map-dblocks (&optional command)
12163 "Apply COMMAND to all dynamic blocks in the current buffer.
12164 If COMMAND is not given, use `org-update-dblock'."
12165 (let ((cmd (or command 'org-update-dblock)))
12167 (goto-char (point-min))
12168 (while (re-search-forward org-dblock-start-re nil t)
12169 (goto-char (match-beginning 0))
12171 (condition-case nil
12173 (error (message "Error during update of dynamic block"))))
12174 (unless (re-search-forward org-dblock-end-re nil t)
12175 (error "Dynamic block not terminated"))))))
12177 (defun org-dblock-update (&optional arg)
12178 "User command for updating dynamic blocks.
12179 Update the dynamic block at point. With prefix ARG, update all dynamic
12180 blocks in the buffer."
12183 (org-update-all-dblocks)
12184 (or (looking-at org-dblock-start-re)
12185 (org-beginning-of-dblock))
12186 (org-update-dblock)))
12188 (defun org-update-dblock ()
12189 "Update the dynamic block at point.
12190 This means to empty the block, parse for parameters and then call
12191 the correct writing function."
12194 (let* ((win (selected-window))
12196 (line (org-current-line))
12197 (params (org-prepare-dblock))
12198 (name (plist-get params :name))
12199 (indent (plist-get params :indentation-column))
12200 (cmd (intern (concat "org-dblock-write:" name))))
12201 (message "Updating dynamic block `%s' at line %d..." name line)
12202 (funcall cmd params)
12203 (message "Updating dynamic block `%s' at line %d...done" name line)
12205 (when (and indent (> indent 0))
12206 (setq indent (make-string indent ?\ ))
12208 (select-window win)
12209 (org-beginning-of-dblock)
12211 (while (not (looking-at org-dblock-end-re))
12213 (beginning-of-line 2))
12214 (when (looking-at org-dblock-end-re)
12215 (and (looking-at "[ \t]+")
12216 (replace-match ""))
12217 (insert indent)))))))
12219 (defun org-beginning-of-dblock ()
12220 "Find the beginning of the dynamic block at point.
12221 Error if there is no such block at point."
12222 (let ((pos (point))
12225 (if (and (re-search-backward org-dblock-start-re nil t)
12226 (setq beg (match-beginning 0))
12227 (re-search-forward org-dblock-end-re nil t)
12228 (> (match-end 0) pos))
12231 (error "Not in a dynamic block"))))
12233 (defun org-update-all-dblocks ()
12234 "Update all dynamic blocks in the buffer.
12235 This function can be used in a hook."
12237 (when (derived-mode-p 'org-mode)
12238 (org-map-dblocks 'org-update-dblock)))
12243 (declare-function org-export-backend-name "org-export" (cl-x))
12244 (declare-function org-export-backend-options "org-export" (cl-x))
12245 (defun org-get-export-keywords ()
12246 "Return a list of all currently understood export keywords.
12247 Export keywords include options, block names, attributes and
12248 keywords relative to each registered export back-end."
12251 (org-bound-and-true-p org-export--registered-backends)
12252 (delq nil keywords))
12253 ;; Back-end name (for keywords, like #+LATEX:)
12254 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12255 (dolist (option-entry (org-export-backend-options backend))
12256 ;; Back-end options.
12257 (push (nth 1 option-entry) keywords)))))
12259 (defconst org-options-keywords
12260 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12261 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12262 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12263 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12264 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12266 (defcustom org-structure-template-alist
12267 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12268 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12269 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12270 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12271 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12272 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12273 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX")
12275 ("h" "#+BEGIN_HTML\n?\n#+END_HTML")
12277 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
12280 ("I" "#+INCLUDE: %file ?"))
12281 "Structure completion elements.
12282 This is a list of abbreviation keys and values. The value gets inserted
12283 if you type `<' followed by the key and then press the completion key,
12284 usually `TAB'. %file will be replaced by a file name after prompting
12285 for the file using completion. The cursor will be placed at the position
12286 of the `?` in the template.
12287 There are two templates for each key, the first uses the original Org syntax,
12288 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12289 the default when the /org-mtags.el/ module has been loaded. See also the
12290 variable `org-mtags-prefer-muse-templates'."
12291 :group 'org-completion
12294 (string :tag "Key")
12295 (string :tag "Template")))
12297 :package-version '(Org . "8.3"))
12299 (defun org-try-structure-completion ()
12300 "Try to complete a structure template before point.
12301 This looks for strings like \"<e\" on an otherwise empty line and
12303 (let ((l (buffer-substring (point-at-bol) (point)))
12305 (when (and (looking-at "[ \t]*$")
12306 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12307 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12308 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12309 (match-beginning 1)) a)
12312 (defun org-complete-expand-structure-template (start cell)
12313 "Expand a structure template."
12314 (let ((rpl (nth 1 cell))
12316 (delete-region start (point))
12317 (when (string-match "\\`[ \t]*#\\+" rpl)
12320 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12321 (setq ind (buffer-substring (point-at-bol) (point))))
12323 (setq start (point))
12324 (if (string-match "%file" rpl)
12325 (setq rpl (replace-match
12329 (abbreviate-file-name (read-file-name "Include file: ")))
12332 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12333 (concat "\n" ind)))
12335 (if (re-search-backward "\\?" start t) (delete-char 1))))
12337 ;;;; TODO, DEADLINE, Comments
12339 (defun org-toggle-comment ()
12340 "Change the COMMENT state of an entry."
12343 (org-back-to-heading)
12344 (looking-at org-complex-heading-regexp)
12345 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12346 (skip-chars-forward " \t")
12347 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12348 (if (org-in-commented-heading-p t)
12349 (delete-region (point)
12350 (progn (search-forward " " (line-end-position) 'move)
12351 (skip-chars-forward " \t")
12353 (insert org-comment-string)
12354 (unless (eolp) (insert " ")))))
12356 (defvar org-last-todo-state-is-todo nil
12357 "This is non-nil when the last TODO state change led to a TODO state.
12358 If the last change removed the TODO tag or switched to DONE, then
12361 (defvar org-setting-tags nil) ; dynamically skipped
12363 (defvar org-todo-setup-filter-hook nil
12364 "Hook for functions that pre-filter todo specs.
12365 Each function takes a todo spec and returns either nil or the spec
12366 transformed into canonical form." )
12368 (defvar org-todo-get-default-hook nil
12369 "Hook for functions that get a default item for todo.
12370 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12371 nil or a string to be used for the todo mark." )
12373 (defvar org-agenda-headline-snapshot-before-repeat)
12375 (defun org-current-effective-time ()
12376 "Return current time adjusted for `org-extend-today-until' variable."
12377 (let* ((ct (org-current-time))
12378 (dct (decode-time ct))
12381 (org-use-last-clock-out-time-as-effective-time
12382 (or (org-clock-get-last-clock-out-time) ct))
12383 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12384 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12388 (defun org-todo-yesterday (&optional arg)
12389 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12391 (if (eq major-mode 'org-agenda-mode)
12392 (apply 'org-agenda-todo-yesterday arg)
12393 (let* ((hour (third (decode-time
12394 (org-current-time))))
12395 (org-extend-today-until (1+ hour)))
12398 (defvar org-block-entry-blocking ""
12399 "First entry preventing the TODO state change.")
12401 (defun org-cancel-repeater ()
12402 "Cancel a repeater by setting its numeric value to zero."
12405 (org-back-to-heading t)
12406 (let ((bound1 (point))
12407 (bound0 (save-excursion (outline-next-heading) (point))))
12408 (when (re-search-forward
12409 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12410 org-deadline-time-regexp "\\)\\|\\("
12411 org-ts-regexp "\\)")
12413 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12414 (replace-match "0" t nil nil 1))))))
12416 (defun org-todo (&optional arg)
12417 "Change the TODO state of an item.
12418 The state of an item is given by a keyword at the start of the heading,
12420 *** TODO Write paper
12423 The different keywords are specified in the variable `org-todo-keywords'.
12424 By default the available states are \"TODO\" and \"DONE\".
12425 So for this example: when the item starts with TODO, it is changed to DONE.
12426 When it starts with DONE, the DONE is removed. And when neither TODO nor
12427 DONE are present, add TODO at the beginning of the heading.
12429 With \\[universal-argument] prefix arg, use completion to determine the new \
12431 With numeric prefix arg, switch to that state.
12432 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12433 keywords (nextset).
12434 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12435 With a numeric prefix arg of 0, inhibit note taking for the change.
12436 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12438 When called through ELisp, arg is also interpreted in the following way:
12439 'none -> empty state
12440 \"\"(empty string) -> switch to empty state
12441 'done -> switch to DONE
12442 'nextset -> switch to the next set of keywords
12443 'previousset -> switch to the previous set of keywords
12444 \"WAITING\" -> switch to the specified keyword, but only if it
12445 really is a member of `org-todo-keywords'."
12447 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12448 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12449 'region-start-level 'region))
12450 org-loop-over-headlines-in-active-region)
12453 org-loop-over-headlines-in-active-region
12454 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12455 (if (equal arg '(16)) (setq arg 'nextset))
12456 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12457 (let ((org-blocker-hook org-blocker-hook)
12460 (when (equal arg '(64))
12461 (setq arg nil org-blocker-hook nil))
12462 (when (and org-blocker-hook
12463 (or org-inhibit-blocking
12464 (org-entry-get nil "NOBLOCKING")))
12465 (setq org-blocker-hook nil))
12468 (org-back-to-heading t)
12469 (when (org-in-commented-heading-p t)
12470 (org-toggle-comment)
12472 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12473 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12474 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12475 (let* ((match-data (match-data))
12476 (startpos (point-at-bol))
12477 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12478 (org-log-done org-log-done)
12479 (org-log-repeat org-log-repeat)
12480 (org-todo-log-states org-todo-log-states)
12481 (org-inhibit-logging
12483 (progn (setq arg nil) 'note) org-inhibit-logging))
12484 (this (match-string 1))
12485 (hl-pos (match-beginning 0))
12486 (head (org-get-todo-sequence-head this))
12487 (ass (assoc head org-todo-kwd-alist))
12488 (interpret (nth 1 ass))
12489 (done-word (nth 3 ass))
12490 (final-done-word (nth 4 ass))
12491 (org-last-state (or this ""))
12492 (completion-ignore-case t)
12493 (member (member this org-todo-keywords-1))
12494 (tail (cdr member))
12496 ((and org-todo-key-trigger
12497 (or (and (equal arg '(4))
12498 (eq org-use-fast-todo-selection 'prefix))
12499 (and (not arg) org-use-fast-todo-selection
12500 (not (eq org-use-fast-todo-selection
12502 ;; Use fast selection
12503 (org-fast-todo-selection))
12504 ((and (equal arg '(4))
12505 (or (not org-use-fast-todo-selection)
12506 (not org-todo-key-trigger)))
12507 ;; Read a state with completion
12508 (org-icompleting-read
12509 "State: " (mapcar 'list org-todo-keywords-1)
12513 (if tail (car tail) nil)
12514 (car org-todo-keywords-1)))
12516 (if (equal member org-todo-keywords-1)
12519 (nth (- (length org-todo-keywords-1)
12521 org-todo-keywords-1)
12522 (org-last org-todo-keywords-1))))
12523 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12524 (setq arg nil))) ; hack to fall back to cycling
12526 ;; user or caller requests a specific state
12528 ((equal arg "") nil)
12529 ((eq arg 'none) nil)
12530 ((eq arg 'done) (or done-word (car org-done-keywords)))
12532 (or (car (cdr (member head org-todo-heads)))
12533 (car org-todo-heads)))
12534 ((eq arg 'previousset)
12535 (let ((org-todo-heads (reverse org-todo-heads)))
12536 (or (car (cdr (member head org-todo-heads)))
12537 (car org-todo-heads))))
12538 ((car (member arg org-todo-keywords-1)))
12540 (user-error "State `%s' not valid in this file" arg))
12541 ((nth (1- (prefix-numeric-value arg))
12542 org-todo-keywords-1))))
12543 ((null member) (or head (car org-todo-keywords-1)))
12544 ((equal this final-done-word) nil) ;; -> make empty
12545 ((null tail) nil) ;; -> first entry
12546 ((memq interpret '(type priority))
12547 (if (eq this-command last-command)
12549 (if (> (length tail) 0)
12550 (or done-word (car org-done-keywords))
12555 (run-hook-with-args-until-success
12556 'org-todo-get-default-hook org-state org-last-state)
12558 (next (if org-state (concat " " org-state " ") " "))
12559 (change-plist (list :type 'todo-state-change :from this :to org-state
12560 :position startpos))
12562 (when org-blocker-hook
12563 (setq org-last-todo-state-is-todo
12564 (not (member this org-done-keywords)))
12565 (unless (save-excursion
12567 (org-with-wide-buffer
12568 (run-hook-with-args-until-failure
12569 'org-blocker-hook change-plist))))
12570 (if (org-called-interactively-p 'interactive)
12571 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12572 this org-state org-block-entry-blocking)
12574 (message "TODO state change from %s to %s blocked (by \"%s\")"
12575 this org-state org-block-entry-blocking)
12576 (throw 'exit nil))))
12577 (store-match-data match-data)
12578 (replace-match next t t)
12579 (cond ((equal this org-state)
12580 (message "TODO state was already %s" (org-trim next)))
12581 ((pos-visible-in-window-p hl-pos)
12582 (message "TODO state changed to %s" (org-trim next))))
12584 (setq head (org-get-todo-sequence-head org-state)
12585 ass (assoc head org-todo-kwd-alist)
12586 interpret (nth 1 ass)
12587 done-word (nth 3 ass)
12588 final-done-word (nth 4 ass)))
12589 (when (memq arg '(nextset previousset))
12590 (message "Keyword-Set %d/%d: %s"
12591 (- (length org-todo-sets) -1
12592 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12593 (length org-todo-sets)
12594 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12595 (setq org-last-todo-state-is-todo
12596 (not (member org-state org-done-keywords)))
12597 (setq now-done-p (and (member org-state org-done-keywords)
12598 (not (member this org-done-keywords))))
12599 (and logging (org-local-logging logging))
12600 (when (and (or org-todo-log-states org-log-done)
12601 (not (eq org-inhibit-logging t))
12602 (not (memq arg '(nextset previousset))))
12603 ;; we need to look at recording a time and note
12604 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12605 (nth 2 (assoc this org-todo-log-states))))
12606 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12607 (setq dolog 'time))
12608 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12610 (member org-state org-not-done-keywords)
12611 (not (member this org-not-done-keywords))))
12612 ;; This is now a todo state and was not one before
12613 ;; If there was a CLOSED time stamp, get rid of it.
12614 (org-add-planning-info nil nil 'closed))
12615 (when (and now-done-p org-log-done)
12616 ;; It is now done, and it was not done before
12617 (org-add-planning-info 'closed (org-current-effective-time))
12618 (if (and (not dolog) (eq 'note org-log-done))
12619 (org-add-log-setup 'done org-state this 'findpos 'note)))
12620 (when (and org-state dolog)
12621 ;; This is a non-nil state, and we need to log it
12622 (org-add-log-setup 'state org-state this 'findpos dolog)))
12623 ;; Fixup tag positioning
12624 (org-todo-trigger-tag-changes org-state)
12625 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12626 (when org-provide-todo-statistics
12627 (org-update-parent-todo-statistics))
12628 (run-hooks 'org-after-todo-state-change-hook)
12629 (if (and arg (not (member org-state org-done-keywords)))
12630 (setq head (org-get-todo-sequence-head org-state)))
12631 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12632 ;; Do we need to trigger a repeat?
12634 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12635 ;; This is for the agenda, take a snapshot of the headline.
12637 (setq org-agenda-headline-snapshot-before-repeat
12638 (org-get-heading))))
12639 (org-auto-repeat-maybe org-state))
12640 ;; Fixup cursor location if close to the keyword
12641 (if (and (outline-on-heading-p)
12643 (save-excursion (beginning-of-line 1)
12644 (looking-at org-todo-line-regexp))
12645 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12647 (goto-char (or (match-end 2) (match-end 1)))
12648 (and (looking-at " ") (just-one-space))))
12649 (when org-trigger-hook
12651 (run-hook-with-args 'org-trigger-hook change-plist)))
12652 (when commentp (org-toggle-comment))))))))
12654 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12655 "Block turning an entry into a TODO, using the hierarchy.
12656 This checks whether the current task should be blocked from state
12657 changes. Such blocking occurs when:
12659 1. The task has children which are not all in a completed state.
12661 2. A task has a parent with the property :ORDERED:, and there
12662 are siblings prior to the current task with incomplete
12665 3. The parent of the task is blocked because it has siblings that should
12666 be done first, or is child of a block grandparent TODO entry."
12668 (if (not org-enforce-todo-dependencies)
12669 t ; if locally turned off don't block
12671 ;; If this is not a todo state change, or if this entry is already DONE,
12673 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12674 (member (plist-get change-plist :from)
12675 (cons 'done org-done-keywords))
12676 (member (plist-get change-plist :to)
12677 (cons 'todo org-not-done-keywords))
12678 (not (plist-get change-plist :to)))
12679 (throw 'dont-block t))
12680 ;; If this task has children, and any are undone, it's blocked
12682 (org-back-to-heading t)
12683 (let ((this-level (funcall outline-level)))
12684 (outline-next-heading)
12685 (let ((child-level (funcall outline-level)))
12686 (while (and (not (eobp))
12687 (> child-level this-level))
12688 ;; this todo has children, check whether they are all
12690 (if (and (not (org-entry-is-done-p))
12691 (org-entry-is-todo-p))
12692 (progn (setq org-block-entry-blocking (org-get-heading))
12693 (throw 'dont-block nil)))
12694 (outline-next-heading)
12695 (setq child-level (funcall outline-level))))))
12696 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12697 ;; any previous siblings are undone, it's blocked
12699 (org-back-to-heading t)
12700 (let* ((pos (point))
12701 (parent-pos (and (org-up-heading-safe) (point))))
12702 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12703 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12705 (re-search-forward org-not-done-heading-regexp pos t))
12706 (setq org-block-entry-blocking (match-string 0))
12707 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12708 ;; Search further up the hierarchy, to see if an ancestor is blocked
12710 (goto-char parent-pos)
12711 (if (not (looking-at org-not-done-heading-regexp))
12712 (throw 'dont-block t)) ; do not block, parent is not a TODO
12714 (setq parent-pos (and (org-up-heading-safe) (point)))
12715 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12716 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12718 (re-search-forward org-not-done-heading-regexp pos t)
12719 (setq org-block-entry-blocking (org-get-heading)))
12720 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12722 (defcustom org-track-ordered-property-with-tag nil
12723 "Should the ORDERED property also be shown as a tag?
12724 The ORDERED property decides if an entry should require subtasks to be
12725 completed in sequence. Since a property is not very visible, setting
12726 this option means that toggling the ORDERED property with the command
12727 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12728 not relevant for the behavior, but it makes things more visible.
12730 Note that toggling the tag with tags commands will not change the property
12731 and therefore not influence behavior!
12733 This can be t, meaning the tag ORDERED should be used, It can also be a
12734 string to select a different tag for this task."
12737 (const :tag "No tracking" nil)
12738 (const :tag "Track with ORDERED tag" t)
12739 (string :tag "Use other tag")))
12741 (defun org-toggle-ordered-property ()
12742 "Toggle the ORDERED property of the current entry.
12743 For better visibility, you can track the value of this property with a tag.
12744 See variable `org-track-ordered-property-with-tag'."
12746 (let* ((t1 org-track-ordered-property-with-tag)
12747 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12749 (org-back-to-heading)
12750 (if (org-entry-get nil "ORDERED")
12752 (org-delete-property "ORDERED")
12753 (and tag (org-toggle-tag tag 'off))
12754 (message "Subtasks can be completed in arbitrary order"))
12755 (org-entry-put nil "ORDERED" "t")
12756 (and tag (org-toggle-tag tag 'on))
12757 (message "Subtasks must be completed in sequence")))))
12759 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12760 (defun org-block-todo-from-checkboxes (change-plist)
12761 "Block turning an entry into a TODO, using checkboxes.
12762 This checks whether the current task should be blocked from state
12763 changes because there are unchecked boxes in this entry."
12764 (if (not org-enforce-todo-checkbox-dependencies)
12765 t ; if locally turned off don't block
12767 ;; If this is not a todo state change, or if this entry is already DONE,
12769 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12770 (member (plist-get change-plist :from)
12771 (cons 'done org-done-keywords))
12772 (member (plist-get change-plist :to)
12773 (cons 'todo org-not-done-keywords))
12774 (not (plist-get change-plist :to)))
12775 (throw 'dont-block t))
12776 ;; If this task has checkboxes that are not checked, it's blocked
12778 (org-back-to-heading t)
12779 (let ((beg (point)) end)
12780 (outline-next-heading)
12783 (if (org-list-search-forward
12784 (concat (org-item-beginning-re)
12785 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12789 (if (boundp 'org-blocked-by-checkboxes)
12790 (setq org-blocked-by-checkboxes t))
12791 (throw 'dont-block nil)))))
12792 t))) ; do not block
12794 (defun org-entry-blocked-p ()
12795 "Is the current entry blocked?"
12796 (org-with-silent-modifications
12797 (if (org-entry-get nil "NOBLOCKING")
12798 nil ;; Never block this entry
12799 (not (run-hook-with-args-until-failure
12801 (list :type 'todo-state-change
12806 (defun org-update-statistics-cookies (all)
12807 "Update the statistics cookie, either from TODO or from checkboxes.
12808 This should be called with the cursor in a line with a statistics cookie."
12812 (org-update-checkbox-count 'all)
12813 (org-map-entries 'org-update-parent-todo-statistics))
12814 (if (not (org-at-heading-p))
12815 (org-update-checkbox-count)
12816 (let ((pos (point-marker))
12818 (ignore-errors (org-back-to-heading t))
12819 (if (not (org-at-heading-p))
12820 (org-update-checkbox-count)
12821 (setq l1 (org-outline-level))
12822 (setq end (save-excursion
12823 (outline-next-heading)
12824 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12826 (if (and (save-excursion
12828 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12829 (not (save-excursion (re-search-forward
12830 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12831 (org-update-checkbox-count)
12832 (if (and l2 (> l2 l1))
12835 (org-update-parent-todo-statistics))
12837 (beginning-of-line 1)
12838 (while (re-search-forward
12839 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12841 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12843 (move-marker pos nil)))))
12845 (defvar org-entry-property-inherited-from) ;; defined below
12846 (defun org-update-parent-todo-statistics ()
12847 "Update any statistics cookie in the parent of the current headline.
12848 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12849 the entire subtree and this will travel up the hierarchy and update
12850 statistics everywhere."
12851 (let* ((prop (save-excursion (org-up-heading-safe)
12852 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12853 (recursive (or (not org-hierarchical-todo-statistics)
12854 (and prop (string-match "\\<recursive\\>" prop))))
12855 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12858 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12859 level ltoggle l1 new ndel
12860 (cnt-all 0) (cnt-done 0) is-percent kwd
12861 checkbox-beg ov ovs ove cookie-present)
12864 (beginning-of-line 1)
12865 (setq ltoggle (funcall outline-level))
12866 ;; Three situations are to consider:
12868 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12869 ;; to the top-level ancestor on the headline;
12871 ;; 2. If parent has "recursive" property, repeat up to the
12872 ;; headline setting that property, taking inheritance into
12875 ;; 3. Else, move up to direct parent and proceed only once.
12876 (while (and (setq level (org-up-heading-safe))
12877 (or recursive first)
12879 (setq first nil cookie-present nil)
12883 (downcase (or (org-entry-get nil "COOKIE_DATA")
12886 (while (re-search-forward box-re (point-at-eol) t)
12887 (setq cnt-all 0 cnt-done 0 cookie-present t)
12888 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12890 (unless (outline-next-heading) (throw 'exit nil))
12891 (while (and (looking-at org-complex-heading-regexp)
12892 (> (setq l1 (length (match-string 1))) level))
12893 (setq kwd (and (or recursive (= l1 ltoggle))
12895 (if (or (eq org-provide-todo-statistics 'all-headlines)
12896 (and (eq org-provide-todo-statistics t)
12897 (or (member kwd org-done-keywords)))
12898 (and (listp org-provide-todo-statistics)
12899 (stringp (car org-provide-todo-statistics))
12900 (or (member kwd org-provide-todo-statistics)
12901 (member kwd org-done-keywords)))
12902 (and (listp org-provide-todo-statistics)
12903 (listp (car org-provide-todo-statistics))
12904 (or (member kwd (car org-provide-todo-statistics))
12905 (and (member kwd org-done-keywords)
12906 (member kwd (cadr org-provide-todo-statistics))))))
12907 (setq cnt-all (1+ cnt-all))
12908 (if (eq org-provide-todo-statistics t)
12909 (and kwd (setq cnt-all (1+ cnt-all)))))
12910 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12911 (member kwd org-done-keywords))
12912 (and (listp org-provide-todo-statistics)
12913 (listp (car org-provide-todo-statistics))
12914 (member kwd org-done-keywords)
12915 (member kwd (cadr org-provide-todo-statistics)))
12916 (and (listp org-provide-todo-statistics)
12917 (stringp (car org-provide-todo-statistics))
12918 (member kwd org-done-keywords)))
12919 (setq cnt-done (1+ cnt-done)))
12920 (outline-next-heading)))
12923 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12924 (format "[%d/%d]" cnt-done cnt-all))
12925 ndel (- (match-end 0) checkbox-beg))
12926 ;; handle overlays when updating cookie from column view
12927 (when (setq ov (car (overlays-at checkbox-beg)))
12928 (setq ovs (overlay-start ov) ove (overlay-end ov))
12929 (delete-overlay ov))
12930 (goto-char checkbox-beg)
12932 (delete-region (point) (+ (point) ndel))
12933 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12934 (when ov (move-overlay ov ovs ove)))
12935 (when cookie-present
12936 (run-hook-with-args 'org-after-todo-statistics-hook
12937 cnt-done (- cnt-all cnt-done))))))
12938 (run-hooks 'org-todo-statistics-hook)))
12940 (defvar org-after-todo-statistics-hook nil
12941 "Hook that is called after a TODO statistics cookie has been updated.
12942 Each function is called with two arguments: the number of not-done entries
12943 and the number of done entries.
12945 For example, the following function, when added to this hook, will switch
12946 an entry to DONE when all children are done, and back to TODO when new
12947 entries are set to a TODO status. Note that this hook is only called
12948 when there is a statistics cookie in the headline!
12950 (defun org-summary-todo (n-done n-not-done)
12951 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12952 (let (org-log-done org-log-states) ; turn off logging
12953 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12956 (defvar org-todo-statistics-hook nil
12957 "Hook that is run whenever Org thinks TODO statistics should be updated.
12958 This hook runs even if there is no statistics cookie present, in which case
12959 `org-after-todo-statistics-hook' would not run.")
12961 (defun org-todo-trigger-tag-changes (state)
12962 "Apply the changes defined in `org-todo-state-tags-triggers'."
12963 (let ((l org-todo-state-tags-triggers)
12965 (when (or (not state) (equal state ""))
12966 (setq changes (append changes (cdr (assoc "" l)))))
12967 (when (and (stringp state) (> (length state) 0))
12968 (setq changes (append changes (cdr (assoc state l)))))
12969 (when (member state org-not-done-keywords)
12970 (setq changes (append changes (cdr (assoc 'todo l)))))
12971 (when (member state org-done-keywords)
12972 (setq changes (append changes (cdr (assoc 'done l)))))
12973 (dolist (c changes)
12974 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12976 (defun org-local-logging (value)
12977 "Get logging settings from a property VALUE."
12979 ;; directly set the variables, they are already local.
12980 (setq org-log-done nil
12982 org-todo-log-states nil)
12983 (setq words (org-split-string value))
12984 (while (setq w (pop words))
12986 ((setq a (assoc w org-startup-options))
12987 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12988 (set (nth 1 a) (nth 2 a))))
12989 ((setq a (org-extract-log-state-settings w))
12990 (and (member (car a) org-todo-keywords-1)
12991 (push a org-todo-log-states)))))))
12993 (defun org-get-todo-sequence-head (kwd)
12994 "Return the head of the TODO sequence to which KWD belongs.
12995 If KWD is not set, check if there is a text property remembering the
13000 (or (get-text-property (point-at-bol) 'org-todo-head)
13002 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13003 nil (point-at-eol)))
13004 (get-text-property p 'org-todo-head))))
13005 ((not (member kwd org-todo-keywords-1))
13006 (car org-todo-keywords-1))
13007 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13009 (defun org-fast-todo-selection ()
13010 "Fast TODO keyword selection with single keys.
13011 Returns the new TODO keyword, or nil if no state change should occur."
13012 (let* ((fulltable org-todo-key-alist)
13013 (done-keywords org-done-keywords) ;; needed for the faces.
13014 (maxlen (apply 'max (mapcar
13016 (if (stringp (car x)) (string-width (car x)) 0))
13019 (fwidth (+ maxlen 3 1 3))
13020 (ncol (/ (- (window-width) 4) fwidth))
13024 (save-window-excursion
13026 (set-buffer (get-buffer-create " *Org todo*"))
13027 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13029 (org-set-local 'org-done-keywords done-keywords)
13030 (setq tbl fulltable cnt 0)
13031 (while (setq e (pop tbl))
13033 ((equal e '(:startgroup))
13034 (push '() groups) (setq ingroup t)
13035 (when (not (= cnt 0))
13039 ((equal e '(:endgroup))
13040 (setq ingroup nil cnt 0)
13042 ((equal e '(:newline))
13043 (when (not (= cnt 0))
13047 (while (equal (car tbl) '(:newline))
13049 (setq tbl (cdr tbl)))))
13051 (setq tg (car e) c (cdr e))
13052 (if ingroup (push tg (car groups)))
13053 (setq tg (org-add-props tg nil 'face
13054 (org-get-todo-face tg)))
13055 (if (and (= cnt 0) (not ingroup)) (insert " "))
13056 (insert "[" c "] " tg (make-string
13057 (- fwidth 4 (length tg)) ?\ ))
13058 (when (= (setq cnt (1+ cnt)) ncol)
13060 (if ingroup (insert " "))
13063 (goto-char (point-min))
13064 (if (not expert) (org-fit-window-to-buffer))
13065 (message "[a-z..]:Set [SPC]:clear")
13066 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13069 (and (= c ?q) (not (rassoc c fulltable))))
13070 (setq quit-flag t))
13072 ((setq e (rassoc c fulltable) tg (car e))
13074 (t (setq quit-flag t)))))))
13076 (defun org-entry-is-todo-p ()
13077 (member (org-get-todo-state) org-not-done-keywords))
13079 (defun org-entry-is-done-p ()
13080 (member (org-get-todo-state) org-done-keywords))
13082 (defun org-get-todo-state ()
13083 "Return the TODO keyword of the current subtree."
13085 (org-back-to-heading t)
13086 (and (looking-at org-todo-line-regexp)
13088 (match-string 2))))
13090 (defun org-at-date-range-p (&optional inactive-ok)
13091 "Is the cursor inside a date range?"
13095 (let ((pos (point)))
13096 (skip-chars-backward "^[<\r\n")
13097 (skip-chars-backward "<[")
13098 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13099 (>= (match-end 0) pos)
13101 (skip-chars-backward "^<[\r\n")
13102 (skip-chars-backward "<[")
13103 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13104 (>= (match-end 0) pos)
13108 (defun org-get-repeat (&optional tagline)
13109 "Check if there is a deadline/schedule with repeater in this entry."
13112 (org-back-to-heading t)
13113 (and (re-search-forward (if tagline
13114 (concat tagline "\\s-*" org-repeat-re)
13116 (org-entry-end-position) t)
13117 (match-string-no-properties 1)))))
13119 (defvar org-last-changed-timestamp)
13120 (defvar org-last-inserted-timestamp)
13121 (defvar org-log-post-message)
13122 (defvar org-log-note-purpose)
13123 (defvar org-log-note-how nil)
13124 (defvar org-log-note-extra)
13125 (defun org-auto-repeat-maybe (done-word)
13126 "Check if the current headline contains a repeated deadline/schedule.
13127 If yes, set TODO state back to what it was and change the base date
13128 of repeating deadline/scheduled time stamps to new date.
13129 This function is run automatically after each state change to a DONE state."
13130 ;; last-state is dynamically scoped into this function
13131 (let* ((repeat (org-get-repeat))
13132 (aa (assoc org-last-state org-todo-kwd-alist))
13133 (interpret (nth 1 aa))
13135 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13136 (msg "Entry repeats: ")
13138 (org-todo-log-states nil)
13139 re type n what ts time to-state)
13140 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13141 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
13142 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
13143 org-todo-repeat-to-state))
13144 (unless (and to-state (member to-state org-todo-keywords-1))
13145 (setq to-state (if (eq interpret 'type) org-last-state head)))
13146 (org-todo to-state)
13147 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13148 (org-entry-put nil "LAST_REPEAT" (format-time-string
13149 (org-time-stamp-format t t))))
13150 (when org-log-repeat
13151 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13152 (memq 'org-add-log-note post-command-hook))
13153 ;; OK, we are already setup for some record
13154 (if (eq org-log-repeat 'note)
13155 ;; make sure we take a note, not only a time stamp
13156 (setq org-log-note-how 'note))
13157 ;; Set up for taking a record
13158 (org-add-log-setup 'state (or done-word (car org-done-keywords))
13160 'findpos org-log-repeat)))
13161 (org-back-to-heading t)
13162 (org-add-planning-info nil nil 'closed)
13163 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13164 org-deadline-time-regexp "\\)\\|\\("
13165 org-ts-regexp "\\)"))
13166 (while (re-search-forward
13167 re (save-excursion (outline-next-heading) (point)) t)
13168 (setq type (if (match-end 1) org-scheduled-string
13169 (if (match-end 3) org-deadline-string "Plain:"))
13170 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13171 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
13172 (setq n (string-to-number (match-string 2 ts))
13173 what (match-string 3 ts))
13174 (if (equal what "w") (setq n (* n 7) what "d"))
13175 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13176 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13177 ;; Preparation, see if we need to modify the start date for the change
13178 (when (match-end 1)
13179 (setq time (save-match-data (org-time-string-to-time ts)))
13181 ((equal (match-string 1 ts) ".")
13182 ;; Shift starting date to today
13183 (org-timestamp-change
13184 (- (org-today) (time-to-days time))
13186 ((equal (match-string 1 ts) "+")
13187 (let ((nshiftmax 10) (nshift 0))
13188 (while (or (= nshift 0)
13189 (<= (time-to-days time)
13190 (time-to-days (current-time))))
13191 (when (= (incf nshift) nshiftmax)
13192 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13193 (user-error "Abort")))
13194 (org-timestamp-change n (cdr (assoc what whata)))
13195 (org-at-timestamp-p t)
13196 (setq ts (match-string 1))
13197 (setq time (save-match-data (org-time-string-to-time ts)))))
13198 (org-timestamp-change (- n) (cdr (assoc what whata)))
13199 ;; rematch, so that we have everything in place for the real shift
13200 (org-at-timestamp-p t)
13201 (setq ts (match-string 1))
13202 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13203 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13204 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13205 (setq org-log-post-message msg)
13206 (message "%s" msg))))
13208 (defun org-show-todo-tree (arg)
13209 "Make a compact tree which shows all headlines marked with TODO.
13210 The tree will show the lines where the regexp matches, and all higher
13211 headlines above the match.
13212 With a \\[universal-argument] prefix, prompt for a regexp to match.
13213 With a numeric prefix N, construct a sparse tree for the Nth element
13214 of `org-todo-keywords-1'."
13216 (let ((case-fold-search nil)
13218 (cond ((null arg) org-not-done-regexp)
13220 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13221 (mapcar 'list org-todo-keywords-1))))
13223 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13225 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13226 (regexp-quote (nth (1- (prefix-numeric-value arg))
13227 org-todo-keywords-1)))
13228 (t (user-error "Invalid prefix argument: %s" arg)))))
13229 (message "%d TODO entries found"
13230 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13232 (defun org-deadline (arg &optional time)
13233 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13234 With one universal prefix argument, remove any deadline from the item.
13235 With two universal prefix arguments, prompt for a warning delay.
13236 With argument TIME, set the deadline at the corresponding date. TIME
13237 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13239 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13240 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13241 'region-start-level 'region))
13242 org-loop-over-headlines-in-active-region)
13244 `(org-deadline ',arg ,time)
13245 org-loop-over-headlines-in-active-region
13246 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13247 (let* ((old-date (org-entry-get nil "DEADLINE"))
13248 (old-date-time (if old-date (org-time-string-to-time old-date)))
13249 (repeater (and old-date
13251 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13253 (match-string 1 old-date))))
13256 (when (and old-date org-log-redeadline)
13257 (org-add-log-setup 'deldeadline nil old-date 'findpos
13258 org-log-redeadline))
13259 (org-remove-timestamp-with-keyword org-deadline-string)
13260 (message "Item no longer has a deadline."))
13263 (org-back-to-heading t)
13264 (if (re-search-forward
13265 org-deadline-time-regexp
13266 (save-excursion (outline-next-heading) (point)) t)
13267 (let* ((rpl0 (match-string 1))
13268 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13270 (concat org-deadline-string
13276 (org-read-date nil t nil "Warn starting from" old-date-time)))
13277 (time-to-days old-date-time))))
13279 (user-error "No deadline information to update"))))
13281 (org-add-planning-info 'deadline time 'closed)
13282 (when (and old-date org-log-redeadline
13283 (not (equal old-date
13284 (substring org-last-inserted-timestamp 1 -1))))
13285 (org-add-log-setup 'redeadline nil old-date 'findpos
13286 org-log-redeadline))
13289 (org-back-to-heading t)
13290 (when (re-search-forward (concat org-deadline-string " "
13291 org-last-inserted-timestamp)
13293 (outline-next-heading) (point)) t)
13294 (goto-char (1- (match-end 0)))
13295 (insert " " repeater)
13296 (setq org-last-inserted-timestamp
13297 (concat (substring org-last-inserted-timestamp 0 -1)
13299 (substring org-last-inserted-timestamp -1))))))
13300 (message "Deadline on %s" org-last-inserted-timestamp))))))
13302 (defun org-schedule (arg &optional time)
13303 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13304 With one universal prefix argument, remove any scheduling date from the item.
13305 With two universal prefix arguments, prompt for a delay cookie.
13306 With argument TIME, scheduled at the corresponding date. TIME can
13307 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13309 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13310 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13311 'region-start-level 'region))
13312 org-loop-over-headlines-in-active-region)
13314 `(org-schedule ',arg ,time)
13315 org-loop-over-headlines-in-active-region
13316 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13317 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13318 (old-date-time (if old-date (org-time-string-to-time old-date)))
13319 (repeater (and old-date
13321 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13323 (match-string 1 old-date))))
13327 (when (and old-date org-log-reschedule)
13328 (org-add-log-setup 'delschedule nil old-date 'findpos
13329 org-log-reschedule))
13330 (org-remove-timestamp-with-keyword org-scheduled-string)
13331 (message "Item is no longer scheduled.")))
13334 (org-back-to-heading t)
13335 (if (re-search-forward
13336 org-scheduled-time-regexp
13337 (save-excursion (outline-next-heading) (point)) t)
13338 (let* ((rpl0 (match-string 1))
13339 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13341 (concat org-scheduled-string
13347 (org-read-date nil t nil "Delay until" old-date-time)))
13348 (time-to-days old-date-time))))
13350 (user-error "No scheduled information to update"))))
13352 (org-add-planning-info 'scheduled time 'closed)
13353 (when (and old-date org-log-reschedule
13354 (not (equal old-date
13355 (substring org-last-inserted-timestamp 1 -1))))
13356 (org-add-log-setup 'reschedule nil old-date 'findpos
13357 org-log-reschedule))
13360 (org-back-to-heading t)
13361 (when (re-search-forward (concat org-scheduled-string " "
13362 org-last-inserted-timestamp)
13364 (outline-next-heading) (point)) t)
13365 (goto-char (1- (match-end 0)))
13366 (insert " " repeater)
13367 (setq org-last-inserted-timestamp
13368 (concat (substring org-last-inserted-timestamp 0 -1)
13370 (substring org-last-inserted-timestamp -1))))))
13371 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13373 (defun org-get-scheduled-time (pom &optional inherit)
13374 "Get the scheduled time as a time tuple, of a format suitable
13375 for calling org-schedule with, or if there is no scheduling,
13377 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13379 (apply 'encode-time (org-parse-time-string time)))))
13381 (defun org-get-deadline-time (pom &optional inherit)
13382 "Get the deadline as a time tuple, of a format suitable for
13383 calling org-deadline with, or if there is no scheduling, returns
13385 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13387 (apply 'encode-time (org-parse-time-string time)))))
13389 (defun org-remove-timestamp-with-keyword (keyword)
13390 "Remove all time stamps with KEYWORD in the current entry."
13391 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13394 (org-back-to-heading t)
13396 (outline-next-heading)
13397 (while (re-search-backward re beg t)
13399 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13400 (equal (char-before) ?\ ))
13401 (backward-delete-char 1)
13402 (if (string-match "^[ \t]*$" (buffer-substring
13403 (point-at-bol) (point-at-eol)))
13404 (delete-region (point-at-bol)
13405 (min (point-max) (1+ (point-at-eol))))))))))
13407 (defvar org-time-was-given) ; dynamically scoped parameter
13408 (defvar org-end-time-was-given) ; dynamically scoped parameter
13410 (defun org-add-planning-info (what &optional time &rest remove)
13411 "Insert new timestamp with keyword in the line directly after the headline.
13412 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13413 If non is given, the user is prompted for a date.
13414 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13417 (let (org-time-was-given org-end-time-was-given ts
13418 end default-time default-input)
13421 (when (and (memq what '(scheduled deadline))
13423 (and (stringp time)
13424 (string-match "^[-+]+[0-9]" time))))
13425 ;; Try to get a default date/time from existing timestamp
13427 (org-back-to-heading t)
13428 (setq end (save-excursion (outline-next-heading) (point)))
13429 (when (re-search-forward (if (eq what 'scheduled)
13430 org-scheduled-time-regexp
13431 org-deadline-time-regexp)
13433 (setq ts (match-string 1)
13435 (apply 'encode-time (org-parse-time-string ts))
13436 default-input (and ts (org-get-compact-tod ts))))))
13440 ;; This is a string (relative or absolute), set proper date
13441 (apply 'encode-time
13442 (org-read-date-analyze
13443 time default-time (decode-time default-time)))
13444 ;; If necessary, get the time from the user
13445 (or time (org-read-date nil 'to-time nil nil
13446 default-time default-input)))))
13448 (when (and org-insert-labeled-timestamps-at-point
13449 (member what '(scheduled deadline)))
13451 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13452 (org-insert-time-stamp time org-time-was-given
13453 nil nil nil (list org-end-time-was-given))
13457 (let (col list elt ts buffer-invisibility-spec)
13458 (org-back-to-heading t)
13459 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13460 (goto-char (match-end 1))
13461 (setq col (current-column))
13462 (goto-char (match-end 0))
13463 (if (eobp) (insert "\n") (forward-char 1))
13464 (when (and (not what)
13467 org-keyword-time-not-clock-regexp))))
13468 ;; Nothing to add, nothing to remove...... :-)
13470 (if (and (not (looking-at org-outline-regexp))
13471 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13473 (not (equal (match-string 1) org-clock-string)))
13474 (narrow-to-region (match-beginning 0) (match-end 0))
13475 (insert-before-markers "\n")
13477 (narrow-to-region (point) (point))
13478 (and org-adapt-indentation (org-indent-to-column col)))
13479 ;; Check if we have to remove something.
13480 (setq list (cons what remove))
13482 (setq elt (pop list))
13483 (when (or (and (eq elt 'scheduled)
13484 (re-search-forward org-scheduled-time-regexp nil t))
13485 (and (eq elt 'deadline)
13486 (re-search-forward org-deadline-time-regexp nil t))
13487 (and (eq elt 'closed)
13488 (re-search-forward org-closed-time-regexp nil t)))
13490 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13491 (and (looking-at "[ \t]+") (replace-match ""))
13492 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13495 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13496 (cond ((eq what 'scheduled) org-scheduled-string)
13497 ((eq what 'deadline) org-deadline-string)
13498 ((eq what 'closed) org-closed-string))
13500 (setq ts (org-insert-time-stamp
13502 (or org-time-was-given
13503 (and (eq what 'closed) org-log-done-with-time))
13505 nil nil (list org-end-time-was-given)))
13507 (if (not (or (bolp) (eq (char-before) ?\ )
13508 (memq (char-after) '(32 10))
13511 (goto-char (point-min))
13513 (if (and (looking-at "[ \t]*\n")
13514 (equal (char-before) ?\n))
13515 (delete-region (1- (point)) (point-at-eol)))
13518 (defvar org-log-note-marker (make-marker))
13519 (defvar org-log-note-purpose nil)
13520 (defvar org-log-note-state nil)
13521 (defvar org-log-note-previous-state nil)
13522 (defvar org-log-note-extra nil)
13523 (defvar org-log-note-window-configuration nil)
13524 (defvar org-log-note-return-to (make-marker))
13525 (defvar org-log-note-effective-time nil
13526 "Remembered current time so that dynamically scoped
13527 `org-extend-today-until' affects tha timestamps in state change
13530 (defvar org-log-post-message nil
13531 "Message to be displayed after a log note has been stored.
13532 The auto-repeater uses this.")
13534 (defun org-add-note ()
13535 "Add a note to the current entry.
13536 This is done in the same way as adding a state change note."
13538 (org-add-log-setup 'note nil nil 'findpos nil))
13540 (defvar org-property-end-re)
13541 (defun org-add-log-setup (&optional purpose state prev-state
13543 "Set up the post command hook to take a note.
13544 If this is about to TODO state change, the new state is expected in STATE.
13545 When FINDPOS is non-nil, find the correct position for the note in
13546 the current entry. If not, assume that it can be inserted at point.
13547 HOW is an indicator what kind of note should be created.
13548 EXTRA is additional text that will be inserted into the notes buffer."
13549 (let* ((org-log-into-drawer (org-log-into-drawer))
13550 (drawer (cond ((stringp org-log-into-drawer)
13551 org-log-into-drawer)
13552 (org-log-into-drawer "LOGBOOK"))))
13556 (org-back-to-heading t)
13557 (narrow-to-region (point) (save-excursion
13558 (outline-next-heading) (point)))
13559 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13560 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13562 (goto-char (match-end 0))
13565 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13568 (goto-char (match-end 0))
13569 (or org-log-states-order-reversed
13570 (and (re-search-forward org-property-end-re nil t)
13571 (goto-char (1- (match-beginning 0))))))
13572 (insert "\n:" drawer ":\n:END:")
13573 (beginning-of-line 0)
13575 (beginning-of-line 2)
13578 ((and org-log-state-notes-insert-after-drawers
13580 (forward-line) (looking-at org-drawer-regexp)))
13582 (while (looking-at org-drawer-regexp)
13583 (goto-char (match-end 0))
13584 (re-search-forward org-property-end-re (point-max) t)
13586 (forward-line -1)))
13587 (unless org-log-states-order-reversed
13588 (and (= (char-after) ?\n) (forward-char 1))
13589 (org-skip-over-state-notes)
13590 (skip-chars-backward " \t\n\r")))
13591 (move-marker org-log-note-marker (point))
13592 (setq org-log-note-purpose purpose
13593 org-log-note-state state
13594 org-log-note-previous-state prev-state
13595 org-log-note-how how
13596 org-log-note-extra extra
13597 org-log-note-effective-time (org-current-effective-time))
13598 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13600 (defun org-skip-over-state-notes ()
13601 "Skip past the list of State notes in an entry."
13602 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13603 (when (ignore-errors (goto-char (org-in-item-p)))
13604 (let* ((struct (org-list-struct))
13605 (prevs (org-list-prevs-alist struct)))
13606 (while (looking-at "[ \t]*- State")
13607 (goto-char (or (org-list-get-next-item (point) struct prevs)
13608 (org-list-get-item-end (point) struct)))))))
13610 (defun org-add-log-note (&optional purpose)
13611 "Pop up a window for taking a note, and add this note later at point."
13612 (remove-hook 'post-command-hook 'org-add-log-note)
13613 (setq org-log-note-window-configuration (current-window-configuration))
13614 (delete-other-windows)
13615 (move-marker org-log-note-return-to (point))
13616 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13617 (goto-char org-log-note-marker)
13618 (org-switch-to-buffer-other-window "*Org Note*")
13620 (if (memq org-log-note-how '(time state))
13621 (let (current-prefix-arg) (org-store-log-note))
13622 (let ((org-inhibit-startup t)) (org-mode))
13623 (insert (format "# Insert note for %s.
13624 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13626 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13627 ((eq org-log-note-purpose 'done) "closed todo item")
13628 ((eq org-log-note-purpose 'state)
13629 (format "state change from \"%s\" to \"%s\""
13630 (or org-log-note-previous-state "")
13631 (or org-log-note-state "")))
13632 ((eq org-log-note-purpose 'reschedule)
13634 ((eq org-log-note-purpose 'delschedule)
13635 "no longer scheduled")
13636 ((eq org-log-note-purpose 'redeadline)
13637 "changing deadline")
13638 ((eq org-log-note-purpose 'deldeadline)
13639 "removing deadline")
13640 ((eq org-log-note-purpose 'refile)
13642 ((eq org-log-note-purpose 'note)
13644 (t (error "This should not happen")))))
13645 (if org-log-note-extra (insert org-log-note-extra))
13646 (org-set-local 'org-finish-function 'org-store-log-note)
13647 (run-hooks 'org-log-buffer-setup-hook)))
13649 (defvar org-note-abort nil) ; dynamically scoped
13650 (defun org-store-log-note ()
13651 "Finish taking a log note, and insert it to where it belongs."
13652 (let ((txt (buffer-string)))
13653 (kill-buffer (current-buffer))
13654 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13656 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13657 (setq txt (replace-match "" t t txt)))
13658 (if (string-match "\\s-+\\'" txt)
13659 (setq txt (replace-match "" t t txt)))
13660 (setq lines (org-split-string txt "\n"))
13661 (when (and note (string-match "\\S-" note))
13663 (org-replace-escapes
13665 (list (cons "%u" (user-login-name))
13666 (cons "%U" user-full-name)
13667 (cons "%t" (format-time-string
13668 (org-time-stamp-format 'long 'inactive)
13669 org-log-note-effective-time))
13670 (cons "%T" (format-time-string
13671 (org-time-stamp-format 'long nil)
13672 org-log-note-effective-time))
13673 (cons "%d" (format-time-string
13674 (org-time-stamp-format nil 'inactive)
13675 org-log-note-effective-time))
13676 (cons "%D" (format-time-string
13677 (org-time-stamp-format nil nil)
13678 org-log-note-effective-time))
13679 (cons "%s" (if org-log-note-state
13680 (concat "\"" org-log-note-state "\"")
13682 (cons "%S" (if org-log-note-previous-state
13683 (concat "\"" org-log-note-previous-state "\"")
13685 (if lines (setq note (concat note " \\\\")))
13687 (when (or current-prefix-arg org-note-abort)
13688 (when org-log-into-drawer
13689 (org-remove-empty-drawer-at org-log-note-marker))
13692 (with-current-buffer (marker-buffer org-log-note-marker)
13694 (goto-char org-log-note-marker)
13695 (move-marker org-log-note-marker nil)
13697 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13698 (setq ind (save-excursion
13699 (if (ignore-errors (goto-char (org-in-item-p)))
13700 (let ((struct (org-list-struct)))
13702 (org-list-get-top-point struct) struct))
13703 (skip-chars-backward " \r\t\n")
13705 ((and (org-at-heading-p)
13706 org-adapt-indentation)
13707 (1+ (org-current-level)))
13708 ((org-at-heading-p) 0)
13709 (t (org-get-indentation))))))
13710 (setq bul (org-list-bullet-string "-"))
13711 (org-indent-line-to ind)
13712 (insert bul (pop lines))
13713 (let ((ind-body (+ (length bul) ind)))
13716 (org-indent-line-to ind-body)
13717 (insert (pop lines))))
13718 (message "Note stored")
13719 (org-back-to-heading t)
13720 (org-cycle-hide-drawers 'children))
13721 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13722 ;; from within `org-add-log-note' because `buffer-undo-list'
13723 ;; is then modified outside of `org-with-remote-undo'.
13724 (when (eq this-command 'org-agenda-todo)
13725 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13726 ;; Don't add undo information when called from `org-agenda-todo'
13727 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13728 (set-window-configuration org-log-note-window-configuration)
13729 (with-current-buffer (marker-buffer org-log-note-return-to)
13730 (goto-char org-log-note-return-to))
13731 (move-marker org-log-note-return-to nil)
13732 (and org-log-post-message (message "%s" org-log-post-message))))
13734 (defun org-remove-empty-drawer-at (pos)
13735 "Remove an empty drawer at position POS.
13736 POS may also be a marker."
13737 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13738 (org-with-wide-buffer
13740 (let ((drawer (org-element-at-point)))
13741 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13742 (not (org-element-property :contents-begin drawer)))
13743 (delete-region (org-element-property :begin drawer)
13744 (progn (goto-char (org-element-property :end drawer))
13745 (skip-chars-backward " \r\t\n")
13749 (defvar org-ts-type nil)
13750 (defun org-sparse-tree (&optional arg type)
13751 "Create a sparse tree, prompt for the details.
13752 This command can create sparse trees. You first need to select the type
13753 of match used to create the tree:
13755 t Show all TODO entries.
13756 T Show entries with a specific TODO keyword.
13757 m Show entries selected by a tags/property match.
13758 p Enter a property name and its value (both with completion on existing
13759 names/values) and show entries with that property.
13760 r Show entries matching a regular expression (`/' can be used as well).
13761 b Show deadlines and scheduled items before a date.
13762 a Show deadlines and scheduled items after a date.
13763 d Show deadlines due within `org-deadline-warning-days'.
13764 D Show deadlines and scheduled items between a date range."
13766 (setq type (or type org-sparse-tree-default-date-type))
13767 (setq org-ts-type type)
13768 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13769 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13770 [c]ycle through date types: %s"
13772 (all "all timestamps")
13773 (scheduled "only scheduled")
13774 (deadline "only deadline")
13775 (active "only active timestamps")
13776 (inactive "only inactive timestamps")
13777 (scheduled-or-deadline "scheduled/deadline")
13778 (closed "with a closed time-stamp")
13779 (otherwise "scheduled/deadline")))
13780 (let ((answer (read-char-exclusive)))
13785 (cadr (memq type '(scheduled-or-deadline all scheduled deadline active
13786 inactive closed)))))
13787 (?d (call-interactively 'org-check-deadlines))
13788 (?b (call-interactively 'org-check-before-date))
13789 (?a (call-interactively 'org-check-after-date))
13790 (?D (call-interactively 'org-check-dates-range))
13791 (?t (call-interactively 'org-show-todo-tree))
13792 (?T (org-show-todo-tree '(4)))
13793 (?m (call-interactively 'org-match-sparse-tree))
13795 (let* ((kwd (org-icompleting-read
13796 "Property: " (mapcar 'list (org-buffer-property-keys))))
13797 (value (org-icompleting-read
13798 "Value: " (mapcar 'list (org-property-values kwd)))))
13799 (unless (string-match "\\`{.*}\\'" value)
13800 (setq value (concat "\"" value "\"")))
13801 (org-match-sparse-tree arg (concat kwd "=" value))))
13802 ((?r ?R ?/) (call-interactively 'org-occur))
13803 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13805 (defvar org-occur-highlights nil
13806 "List of overlays used for occur matches.")
13807 (make-variable-buffer-local 'org-occur-highlights)
13808 (defvar org-occur-parameters nil
13809 "Parameters of the active org-occur calls.
13810 This is a list, each call to org-occur pushes as cons cell,
13811 containing the regular expression and the callback, onto the list.
13812 The list can contain several entries if `org-occur' has been called
13813 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13814 will only contain one set of parameters. When the highlights are
13815 removed (for example with `C-c C-c', or with the next edit (depending
13816 on `org-remove-highlights-with-change'), this variable is emptied
13818 (make-variable-buffer-local 'org-occur-parameters)
13820 (defun org-occur (regexp &optional keep-previous callback)
13821 "Make a compact tree which shows all matches of REGEXP.
13822 The tree will show the lines where the regexp matches, and all higher
13823 headlines above the match. It will also show the heading after the match,
13824 to make sure editing the matching entry is easy.
13825 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13826 call to `org-occur' will be kept, to allow stacking of calls to this
13828 If CALLBACK is non-nil, it is a function which is called to confirm
13829 that the match should indeed be shown."
13830 (interactive "sRegexp: \nP")
13831 (when (equal regexp "")
13832 (user-error "Regexp cannot be empty"))
13833 (unless keep-previous
13834 (org-remove-occur-highlights nil nil t))
13835 (push (cons regexp callback) org-occur-parameters)
13838 (goto-char (point-min))
13839 (if (or (not keep-previous) ; do not want to keep
13840 (not org-occur-highlights)) ; no previous matches
13843 (while (re-search-forward regexp nil t)
13844 (when (or (not callback)
13845 (save-match-data (funcall callback)))
13846 (setq cnt (1+ cnt))
13847 (when org-highlight-sparse-tree-matches
13848 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13849 (org-show-context 'occur-tree))))
13850 (when org-remove-highlights-with-change
13851 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13853 (unless org-sparse-tree-open-archived-trees
13854 (org-hide-archived-subtrees (point-min) (point-max)))
13855 (run-hooks 'org-occur-hook)
13856 (if (org-called-interactively-p 'interactive)
13857 (message "%d match(es) for regexp %s" cnt regexp))
13860 (defun org-occur-next-match (&optional n reset)
13861 "Function for `next-error-function' to find sparse tree matches.
13862 N is the number of matches to move, when negative move backwards.
13863 RESET is entirely ignored - this function always goes back to the
13864 starting point when no match is found."
13865 (let* ((limit (if (< n 0) (point-min) (point-max)))
13866 (search-func (if (< n 0)
13867 'previous-single-char-property-change
13868 'next-single-char-property-change))
13873 (while (setq p1 (funcall search-func (point) 'org-type))
13874 (when (equal p1 limit)
13876 (user-error "No more matches"))
13877 (when (equal (get-char-property p1 'org-type) 'org-occur)
13881 (throw 'exit (point))))
13884 (user-error "No more matches"))))
13886 (defun org-show-context (&optional key)
13887 "Make sure point and context are visible.
13888 How much context is shown depends upon the variables
13889 `org-show-hierarchy-above', `org-show-following-heading',
13890 `org-show-entry-below' and `org-show-siblings'."
13891 (let ((heading-p (org-at-heading-p t))
13892 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13893 (following-p (org-get-alist-option org-show-following-heading key))
13894 (entry-p (org-get-alist-option org-show-entry-below key))
13895 (siblings-p (org-get-alist-option org-show-siblings key)))
13896 ;; Show heading or entry text
13897 (if (and heading-p (not entry-p))
13898 (org-flag-heading nil) ; only show the heading
13899 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13900 (org-show-hidden-entry))) ; show entire entry
13902 ;; Show next sibling, or heading below text
13904 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13905 (org-flag-heading nil))))
13906 (when siblings-p (org-show-siblings))
13908 ;; show all higher headings, possibly with siblings
13910 (while (and (ignore-errors (progn (org-up-heading-all 1) t))
13912 (org-flag-heading nil)
13913 (when siblings-p (org-show-siblings)))))))
13915 (defvar org-reveal-start-hook nil
13916 "Hook run before revealing a location.")
13918 (defun org-reveal (&optional siblings)
13919 "Show current entry, hierarchy above it, and the following headline.
13920 This can be used to show a consistent set of context around locations
13921 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13922 not t for the search context.
13924 With optional argument SIBLINGS, on each level of the hierarchy all
13925 siblings are shown. This repairs the tree structure to what it would
13926 look like when opened with hierarchical calls to `org-cycle'.
13927 With double optional argument \\[universal-argument] \\[universal-argument], \
13928 go to the parent and show the
13931 (run-hooks 'org-reveal-start-hook)
13932 (let ((org-show-hierarchy-above t)
13933 (org-show-following-heading t)
13934 (org-show-siblings (if siblings t org-show-siblings)))
13935 (org-show-context nil))
13936 (when (equal siblings '(16))
13938 (when (org-up-heading-safe)
13940 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13942 (defun org-highlight-new-match (beg end)
13943 "Highlight from BEG to END and mark the highlight is an occur headline."
13944 (let ((ov (make-overlay beg end)))
13945 (overlay-put ov 'face 'secondary-selection)
13946 (overlay-put ov 'org-type 'org-occur)
13947 (push ov org-occur-highlights)))
13949 (defun org-remove-occur-highlights (&optional beg end noremove)
13950 "Remove the occur highlights from the buffer.
13951 BEG and END are ignored. If NOREMOVE is nil, remove this function
13952 from the `before-change-functions' in the current buffer."
13954 (unless org-inhibit-highlight-removal
13955 (mapc 'delete-overlay org-occur-highlights)
13956 (setq org-occur-highlights nil)
13957 (setq org-occur-parameters nil)
13959 (remove-hook 'before-change-functions
13960 'org-remove-occur-highlights 'local))))
13964 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13965 "Regular expression matching the priority indicator.")
13967 (defvar org-remove-priority-next-time nil)
13969 (defun org-priority-up ()
13970 "Increase the priority of the current item."
13972 (org-priority 'up))
13974 (defun org-priority-down ()
13975 "Decrease the priority of the current item."
13977 (org-priority 'down))
13979 (defun org-priority (&optional action show)
13980 "Change the priority of an item.
13981 ACTION can be `set', `up', `down', or a character."
13983 (if (equal action '(4))
13984 (org-show-priority)
13985 (unless org-enable-priority-commands
13986 (user-error "Priority commands are disabled"))
13987 (setq action (or action 'set))
13988 (let (current new news have remove)
13990 (org-back-to-heading t)
13991 (if (looking-at org-priority-regexp)
13992 (setq current (string-to-char (match-string 2))
13995 ((eq action 'remove)
13996 (setq remove t new ?\ ))
13997 ((or (eq action 'set)
13998 (if (featurep 'xemacs) (characterp action) (integerp action)))
13999 (if (not (eq action 'set))
14001 (message "Priority %c-%c, SPC to remove: "
14002 org-highest-priority org-lowest-priority)
14004 (setq new (read-char-exclusive))))
14005 (if (and (= (upcase org-highest-priority) org-highest-priority)
14006 (= (upcase org-lowest-priority) org-lowest-priority))
14007 (setq new (upcase new)))
14008 (cond ((equal new ?\ ) (setq remove t))
14009 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14010 (user-error "Priority must be between `%c' and `%c'"
14011 org-highest-priority org-lowest-priority))))
14014 (1- current) ; normal cycling
14015 ;; last priority was empty
14016 (if (eq last-command this-command)
14017 org-lowest-priority ; wrap around empty to lowest
14019 (if org-priority-start-cycle-with-default
14020 org-default-priority
14021 (1- org-default-priority))))))
14024 (1+ current) ; normal cycling
14025 ;; last priority was empty
14026 (if (eq last-command this-command)
14027 org-highest-priority ; wrap around empty to highest
14029 (if org-priority-start-cycle-with-default
14030 org-default-priority
14031 (1+ org-default-priority))))))
14032 (t (user-error "Invalid action")))
14033 (if (or (< (upcase new) org-highest-priority)
14034 (> (upcase new) org-lowest-priority))
14035 (if (and (memq action '(up down))
14036 (not have) (not (eq last-command this-command)))
14037 ;; `new' is from default priority
14039 "The default can not be set, see `org-default-priority' why")
14040 ;; normal cycling: `new' is beyond highest/lowest priority
14041 ;; and is wrapped around to the empty priority
14043 (setq news (format "%c" new))
14046 (replace-match "" t t nil 1)
14047 (replace-match news t t nil 2))
14049 (user-error "No priority cookie found in line")
14050 (let ((case-fold-search nil))
14051 (looking-at org-todo-line-regexp))
14054 (goto-char (match-end 2))
14055 (insert " [#" news "]"))
14056 (goto-char (match-beginning 3))
14057 (insert "[#" news "] "))))
14058 (org-set-tags nil 'align))
14060 (message "Priority removed")
14061 (message "Priority of current item set to %s" news)))))
14063 (defun org-show-priority ()
14064 "Show the priority of the current item.
14065 This priority is composed of the main priority given with the [#A] cookies,
14066 and by additional input from the age of a schedules or deadline entry."
14068 (let ((pri (if (eq major-mode 'org-agenda-mode)
14069 (org-get-at-bol 'priority)
14072 (beginning-of-line)
14073 (and (looking-at org-heading-regexp)
14074 (org-get-priority (match-string 0))))))))
14075 (message "Priority is %d" (if pri pri -1000))))
14077 (defun org-get-priority (s)
14078 "Find priority cookie and return priority."
14080 (if (functionp org-get-priority-function)
14081 (funcall org-get-priority-function)
14082 (if (not (string-match org-priority-regexp s))
14083 (* 1000 (- org-lowest-priority org-default-priority))
14084 (* 1000 (- org-lowest-priority
14085 (string-to-char (match-string 2 s))))))))
14089 (defvar org-agenda-archives-mode)
14090 (defvar org-map-continue-from nil
14091 "Position from where mapping should continue.
14092 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14094 (defvar org-scanner-tags nil
14095 "The current tag list while the tags scanner is running.")
14096 (defvar org-trust-scanner-tags nil
14097 "Should `org-get-tags-at' use the tags for the scanner.
14098 This is for internal dynamical scoping only.
14099 When this is non-nil, the function `org-get-tags-at' will return the value
14100 of `org-scanner-tags' instead of building the list by itself. This
14101 can lead to large speed-ups when the tags scanner is used in a file with
14102 many entries, and when the list of tags is retrieved, for example to
14103 obtain a list of properties. Building the tags list for each entry in such
14104 a file becomes an N^2 operation - but with this variable set, it scales
14107 (defun org-scan-tags (action matcher todo-only &optional start-level)
14108 "Scan headline tags with inheritance and produce output ACTION.
14110 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14111 or `agenda' to produce an entry list for an agenda view. It can also be
14112 a Lisp form or a function that should be called at each matched headline, in
14113 this case the return value is a list of all return values from these calls.
14115 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
14116 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
14117 only lines with a not-done TODO keyword are included in the output.
14118 This should be the same variable that was scoped into
14119 and set by `org-make-tags-matcher' when it constructed MATCHER.
14121 START-LEVEL can be a string with asterisks, reducing the scope to
14122 headlines matching this string."
14123 (require 'org-agenda)
14124 (let* ((re (concat "^"
14126 ;; Get the correct level to match
14127 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14128 org-outline-regexp)
14130 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14131 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14132 (props (list 'face 'default
14133 'done-face 'org-agenda-done
14134 'undone-face 'default
14135 'mouse-face 'highlight
14136 'org-not-done-regexp org-not-done-regexp
14137 'org-todo-regexp org-todo-regexp
14138 'org-complex-heading-regexp org-complex-heading-regexp
14140 (format "mouse-2 or RET jump to org file %s"
14141 (abbreviate-file-name
14142 (or (buffer-file-name (buffer-base-buffer))
14143 (buffer-name (buffer-base-buffer)))))))
14144 (org-map-continue-from nil)
14145 lspos tags tags-list
14146 (tags-alist (list (cons 0 org-file-tags)))
14147 (llast 0) rtn rtn1 level category i txt
14148 todo marker entry priority)
14149 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
14150 (setq action (list 'lambda nil action)))
14152 (goto-char (point-min))
14153 (when (eq action 'sparse-tree)
14155 (org-remove-occur-highlights))
14156 (while (let (case-fold-search)
14157 (re-search-forward re nil t))
14158 (setq org-map-continue-from nil)
14160 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
14161 tags (if (match-end 4) (org-match-string-no-properties 4)))
14162 (goto-char (setq lspos (match-beginning 0)))
14163 (setq level (org-reduced-level (org-outline-level))
14164 category (org-get-category))
14165 (setq i llast llast level)
14166 ;; remove tag lists from same and sublevels
14167 (while (>= i level)
14168 (when (setq entry (assoc i tags-alist))
14169 (setq tags-alist (delete entry tags-alist)))
14171 ;; add the next tags
14173 (setq tags (org-split-string tags ":")
14175 (cons (cons level tags) tags-alist)))
14176 ;; compile tags for current headline
14178 (if org-use-tag-inheritance
14179 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14181 org-scanner-tags tags-list)
14182 (when org-use-tag-inheritance
14183 (setcdr (car tags-alist)
14184 (mapcar (lambda (x)
14185 (setq x (copy-sequence x))
14186 (org-add-prop-inherited x))
14187 (cdar tags-alist))))
14188 (when (and tags org-use-tag-inheritance
14189 (or (not (eq t org-use-tag-inheritance))
14190 org-tags-exclude-from-inheritance))
14191 ;; selective inheritance, remove uninherited ones
14192 (setcdr (car tags-alist)
14193 (org-remove-uninherited-tags (cdar tags-alist))))
14196 ;; eval matcher only when the todo condition is OK
14197 (and (or (not todo-only) (member todo org-not-done-keywords))
14198 (let ((case-fold-search t) (org-trust-scanner-tags t))
14201 ;; Call the skipper, but return t if it does not skip,
14202 ;; so that the `and' form continues evaluating
14204 (unless (eq action 'sparse-tree) (org-agenda-skip))
14207 ;; Check if timestamps are deselecting this entry
14208 (or (not todo-only)
14209 (and (member todo org-not-done-keywords)
14210 (or (not org-agenda-tags-todo-honor-ignore-options)
14211 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14213 ;; select this headline
14215 ((eq action 'sparse-tree)
14216 (and org-highlight-sparse-tree-matches
14217 (org-get-heading) (match-end 0)
14218 (org-highlight-new-match
14219 (match-beginning 1) (match-end 1)))
14220 (org-show-context 'tags-tree))
14221 ((eq action 'agenda)
14222 (setq txt (org-agenda-format-item
14225 (if (eq org-tags-match-list-sublevels 'indented)
14226 (make-string (1- level) ?.) "")
14230 priority (org-get-priority txt))
14232 (setq marker (org-agenda-new-marker))
14233 (org-add-props txt props
14234 'org-marker marker 'org-hd-marker marker 'org-category category
14236 'priority priority 'type "tagsmatch")
14238 ((functionp action)
14239 (setq org-map-continue-from nil)
14241 (setq rtn1 (funcall action))
14243 (t (user-error "Invalid action")))
14245 ;; if we are to skip sublevels, jump to end of subtree
14246 (unless org-tags-match-list-sublevels
14247 (org-end-of-subtree t)
14248 (backward-char 1))))
14249 ;; Get the correct position from where to continue
14250 (if org-map-continue-from
14251 (goto-char org-map-continue-from)
14252 (and (= (point) lspos) (end-of-line 1)))))
14253 (when (and (eq action 'sparse-tree)
14254 (not org-sparse-tree-open-archived-trees))
14255 (org-hide-archived-subtrees (point-min) (point-max)))
14258 (defun org-remove-uninherited-tags (tags)
14259 "Remove all tags that are not inherited from the list TAGS."
14261 ((eq org-use-tag-inheritance t)
14262 (if org-tags-exclude-from-inheritance
14263 (org-delete-all org-tags-exclude-from-inheritance tags)
14265 ((not org-use-tag-inheritance) nil)
14266 ((stringp org-use-tag-inheritance)
14269 (if (and (string-match org-use-tag-inheritance x)
14270 (not (member x org-tags-exclude-from-inheritance)))
14273 ((listp org-use-tag-inheritance)
14276 (if (member x org-use-tag-inheritance) x nil))
14279 (defun org-match-sparse-tree (&optional todo-only match)
14280 "Create a sparse tree according to tags string MATCH.
14281 MATCH can contain positive and negative selection of tags, like
14282 \"+WORK+URGENT-WITHBOSS\".
14283 If optional argument TODO-ONLY is non-nil, only select lines that are
14286 (org-agenda-prepare-buffers (list (current-buffer)))
14287 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14289 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14291 (defvar org-cached-props nil)
14292 (defun org-cached-entry-get (pom property)
14293 (if (or (eq t org-use-property-inheritance)
14294 (and (stringp org-use-property-inheritance)
14295 (string-match org-use-property-inheritance property))
14296 (and (listp org-use-property-inheritance)
14297 (member property org-use-property-inheritance)))
14298 ;; Caching is not possible, check it directly
14299 (org-entry-get pom property 'inherit)
14300 ;; Get all properties, so that we can do complicated checks easily
14301 (cdr (assoc property (or org-cached-props
14302 (setq org-cached-props
14303 (org-entry-properties pom)))))))
14305 (defun org-global-tags-completion-table (&optional files)
14306 "Return the list of all tags in all agenda buffer/files.
14307 Optional FILES argument is a list of files which can be used
14308 instead of the agenda files."
14315 (set-buffer (find-file-noselect file))
14316 (append (org-get-buffer-tags)
14317 (mapcar (lambda (x) (if (stringp (car-safe x))
14318 (list (car-safe x)) nil))
14320 (if (and files (car files))
14322 (org-agenda-files))))))))
14324 (defun org-make-tags-matcher (match)
14325 "Create the TAGS/TODO matcher form for the selection string MATCH.
14327 The variable `todo-only' is scoped dynamically into this function.
14328 It will be set to t if the matcher restricts matching to TODO entries,
14329 otherwise will not be touched.
14331 Returns a cons of the selection string MATCH and the constructed
14332 lisp form implementing the matcher. The matcher is to be evaluated
14333 at an Org entry, with point on the headline, and returns t if the
14334 entry matches the selection string MATCH. The returned lisp form
14335 references two variables with information about the entry, which
14336 must be bound around the form's evaluation: todo, the TODO keyword
14337 at the entry (or nil of none); and tags-list, the list of all tags
14338 at the entry including inherited ones. Additionally, the category
14339 of the entry (if any) must be specified as the text property
14340 'org-category on the headline.
14342 See also `org-scan-tags'.
14344 (declare (special todo-only))
14345 (unless (boundp 'todo-only)
14346 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14348 ;; Get a new match request, with completion against the global
14349 ;; tags table and the local tags in current buffer
14350 (let ((org-last-tags-completion-table
14352 (delq nil (append (org-get-buffer-tags)
14353 (org-global-tags-completion-table))))))
14354 (setq match (org-completing-read-no-i
14355 "Match: " 'org-tags-completion-function nil nil nil
14356 'org-tags-history))))
14358 ;; Parse the string and create a lisp form
14359 (let ((match0 match)
14360 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14362 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14363 orterms term orlist re-p str-p level-p level-op time-p
14364 prop-p pn pv po gv rest (start 0) (ss 0))
14365 ;; Expand group tags
14366 (setq match (org-tags-expand match))
14368 ;; Check if there is a TODO part of this match, which would be the
14369 ;; part after a "/". TO make sure that this slash is not part of
14370 ;; a property value to be matched against, we also check that there
14371 ;; is no " after that slash.
14372 ;; First, find the last slash
14373 (while (string-match "/+" match ss)
14374 (setq start (match-beginning 0) ss (match-end 0)))
14375 (if (and (string-match "/+" match start)
14376 (not (save-match-data (string-match "\"" match start))))
14377 ;; match contains also a todo-matching request
14379 (setq tagsmatch (substring match 0 (match-beginning 0))
14380 todomatch (substring match (match-end 0)))
14381 (if (string-match "^!" todomatch)
14382 (setq todo-only t todomatch (substring todomatch 1)))
14383 (if (string-match "^\\s-*$" todomatch)
14384 (setq todomatch nil)))
14385 ;; only matching tags
14386 (setq tagsmatch match todomatch nil))
14388 ;; Make the tags matcher
14389 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14390 (setq tagsmatcher t)
14391 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14392 (while (setq term (pop orterms))
14393 (while (and (equal (substring term -1) "\\") orterms)
14394 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14395 (while (string-match re term)
14396 (setq rest (substring term (match-end 0))
14397 minus (and (match-end 1)
14398 (equal (match-string 1 term) "-"))
14399 tag (save-match-data (replace-regexp-in-string
14401 (match-string 2 term)))
14402 re-p (equal (string-to-char tag) ?{)
14403 level-p (match-end 4)
14404 prop-p (match-end 5)
14406 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14408 (setq level-op (org-op-to-function (match-string 3 term)))
14409 `(,level-op level ,(string-to-number
14410 (match-string 4 term))))
14412 (setq pn (match-string 5 term)
14413 po (match-string 6 term)
14414 pv (match-string 7 term)
14415 re-p (equal (string-to-char pv) ?{)
14416 str-p (equal (string-to-char pv) ?\")
14417 time-p (save-match-data
14418 (string-match "^\"[[<].*[]>]\"$" pv))
14419 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14420 (if time-p (setq pv (org-matcher-time pv)))
14421 (setq po (org-op-to-function po (if time-p 'time str-p)))
14423 ((equal pn "CATEGORY")
14424 (setq gv '(get-text-property (point) 'org-category)))
14428 (setq gv `(org-cached-entry-get nil ,pn))))
14431 `(not (string-match ,pv (or ,gv "")))
14432 `(string-match ,pv (or ,gv "")))
14434 `(,po (or ,gv "") ,pv)
14435 `(,po (string-to-number (or ,gv ""))
14436 ,(string-to-number pv) ))))
14437 (t `(member ,tag tags-list)))
14438 mm (if minus (list 'not mm) mm)
14440 (push mm tagsmatcher))
14441 (push (if (> (length tagsmatcher) 1)
14442 (cons 'and tagsmatcher)
14445 (setq tagsmatcher nil))
14446 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14448 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14449 ;; Make the todo matcher
14450 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14451 (setq todomatcher t)
14452 (setq orterms (org-split-string todomatch "|") orlist nil)
14453 (while (setq term (pop orterms))
14454 (while (string-match re term)
14455 (setq minus (and (match-end 1)
14456 (equal (match-string 1 term) "-"))
14457 kwd (match-string 2 term)
14458 re-p (equal (string-to-char kwd) ?{)
14459 term (substring term (match-end 0))
14461 `(string-match ,(substring kwd 1 -1) todo)
14462 (list 'equal 'todo kwd))
14463 mm (if minus (list 'not mm) mm))
14464 (push mm todomatcher))
14465 (push (if (> (length todomatcher) 1)
14466 (cons 'and todomatcher)
14469 (setq todomatcher nil))
14470 (setq todomatcher (if (> (length orlist) 1)
14471 (cons 'or orlist) (car orlist))))
14473 ;; Return the string and lisp forms of the matcher
14474 (setq matcher (if todomatcher
14475 (list 'and tagsmatcher todomatcher)
14478 (setq matcher (list 'and '(member todo org-not-done-keywords)
14480 (cons match0 matcher)))
14482 (defun org-tags-expand (match &optional single-as-list downcased)
14483 "Expand group tags in MATCH.
14485 This replaces every group tag in MATCH with a regexp tag search.
14486 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14487 will be replaced like this:
14489 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14490 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14491 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14493 Replacing by a regexp preserves the structure of the match.
14494 E.g., this expansion
14496 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14498 will match anything tagged with \"Lab\" and \"Home\", or tagged
14499 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14501 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14502 assumed to be a single group tag, and the function will return
14503 the list of tags in this group.
14505 When DOWNCASE is non-nil, expand downcased TAGS."
14507 (let* ((case-fold-search t)
14508 (stable org-mode-syntax-table)
14509 (tal (or org-tag-groups-alist-for-agenda
14510 org-tag-groups-alist))
14512 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14513 (tml (mapcar 'car tal))
14514 (rtnmatch match) rpl)
14515 ;; @ and _ are allowed as word-components in tags
14516 (modify-syntax-entry ?@ "w" stable)
14517 (modify-syntax-entry ?_ "w" stable)
14519 (with-syntax-table stable
14521 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14522 (regexp-opt tml) "\\>\\)") rtnmatch)))
14523 (let* ((dir (match-string 1 rtnmatch))
14524 (tag (match-string 2 rtnmatch))
14525 (tag (if downcased (downcase tag) tag)))
14526 (setq tml (delete tag tml))
14527 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14528 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14529 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14530 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14531 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14533 (or (reverse rpl) (list rtnmatch))
14535 (if single-as-list (list (if downcased (downcase match) match))
14538 (defun org-op-to-function (op &optional stringp)
14539 "Turn an operator into the appropriate function."
14542 ((equal op "<" ) '(< string< org-time<))
14543 ((equal op ">" ) '(> org-string> org-time>))
14544 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14545 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14546 ((member op '("=" "==")) '(= string= org-time=))
14547 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14548 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14550 (defun org<> (a b) (not (= a b)))
14551 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14552 (defun org-string>= (a b) (not (string< a b)))
14553 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14554 (defun org-string<> (a b) (not (string= a b)))
14555 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14556 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14557 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14558 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14559 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14560 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14562 "Convert S to a floating point time.
14563 If S is already a number, just return it. If it is a string, parse
14564 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14568 (condition-case nil
14569 (float-time (apply 'encode-time (org-parse-time-string s)))
14573 (defun org-time-today ()
14574 "Time in seconds today at 0:00.
14575 Returns the float number of seconds since the beginning of the
14576 epoch to the beginning of today (00:00)."
14577 (float-time (apply 'encode-time
14578 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14580 (defun org-matcher-time (s)
14581 "Interpret a time comparison value."
14584 ((string= s "<now>") (float-time))
14585 ((string= s "<today>") (org-time-today))
14586 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14587 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14588 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14589 (+ (org-time-today)
14590 (* (string-to-number (match-string 1 s))
14591 (cdr (assoc (match-string 2 s)
14592 '(("d" . 86400.0) ("w" . 604800.0)
14593 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14596 (defun org-match-any-p (re list)
14597 "Does re match any element of list?"
14598 (setq list (mapcar (lambda (x) (string-match re x)) list))
14601 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14602 (defvar org-tags-overlay (make-overlay 1 1))
14603 (org-detach-overlay org-tags-overlay)
14605 (defun org-get-local-tags-at (&optional pos)
14606 "Get a list of tags defined in the current headline."
14607 (org-get-tags-at pos 'local))
14609 (defun org-get-local-tags ()
14610 "Get a list of tags defined in the current headline."
14611 (org-get-tags-at nil 'local))
14613 (defun org-get-tags-at (&optional pos local)
14614 "Get a list of all headline tags applicable at POS.
14615 POS defaults to point. If tags are inherited, the list contains
14616 the targets in the same sequence as the headlines appear, i.e.
14617 the tags of the current headline come last.
14618 When LOCAL is non-nil, only return tags from the current headline,
14619 ignore inherited ones."
14621 (if (and org-trust-scanner-tags
14622 (or (not pos) (equal pos (point)))
14625 (let (tags ltags lastpos parent)
14629 (goto-char (or pos (point)))
14632 (condition-case nil
14634 (org-back-to-heading t)
14635 (while (not (equal lastpos (point)))
14636 (setq lastpos (point))
14638 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14639 (setq ltags (org-split-string
14640 (org-match-string-no-properties 1) ":"))
14642 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14645 (org-remove-uninherited-tags ltags)
14648 (or org-use-tag-inheritance (throw 'done t))
14649 (if local (throw 'done t))
14650 (or (org-up-heading-safe) (error nil))
14655 (reverse (delete-dups
14657 (org-remove-uninherited-tags
14658 org-file-tags) tags)))))))))
14660 (defun org-add-prop-inherited (s)
14661 (add-text-properties 0 (length s) '(inherited t) s)
14664 (defun org-toggle-tag (tag &optional onoff)
14665 "Toggle the tag TAG for the current line.
14666 If ONOFF is `on' or `off', don't toggle but set to this state."
14669 (org-back-to-heading t)
14670 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14673 (setq current (match-string 1))
14674 (replace-match ""))
14676 (setq current (nreverse (org-split-string current ":")))
14680 (or (member tag current) (push tag current)))
14682 (or (not (member tag current)) (setq current (delete tag current))))
14683 (t (if (member tag current)
14684 (setq current (delete tag current))
14686 (push tag current))))
14690 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14691 (org-set-tags nil t))
14692 (delete-horizontal-space))
14693 (run-hooks 'org-after-tags-change-hook))
14696 (defun org-align-tags-here (to-col)
14697 ;; Assumes that this is a headline
14698 "Align tags on the current headline to TO-COL."
14699 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14700 (beginning-of-line 1)
14701 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14702 (< pos (match-beginning 2)))
14704 (setq tags-l (- (match-end 2) (match-beginning 2)))
14705 (goto-char (match-beginning 1))
14707 (delete-region (point) (1+ (match-beginning 2)))
14708 (setq ncol (max (current-column)
14712 (- (abs to-col) tags-l))))
14714 (insert (make-string (- ncol (current-column)) ?\ ))
14715 (setq ncol (current-column))
14716 (when indent-tabs-mode (tabify p (point-at-eol)))
14717 (org-move-to-column (min ncol col)))
14720 (defun org-set-tags-command (&optional arg just-align)
14721 "Call the set-tags command for the current entry."
14723 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14724 (org-set-tags arg just-align)
14726 (unless (and (org-region-active-p)
14727 org-loop-over-headlines-in-active-region)
14728 (org-back-to-heading t))
14729 (org-set-tags arg just-align))))
14731 (defun org-set-tags-to (data)
14732 "Set the tags of the current entry to DATA, replacing the current tags.
14733 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14734 If DATA is nil or the empty string, any tags will be removed."
14735 (interactive "sTags: ")
14739 ((equal data "") "")
14741 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14744 (concat ":" (mapconcat 'identity data ":") ":"))))
14747 (org-back-to-heading t)
14748 (when (looking-at org-complex-heading-regexp)
14751 (goto-char (match-beginning 5))
14753 (delete-region (point) (point-at-eol))
14754 (org-set-tags nil 'align))
14755 (goto-char (point-at-eol))
14757 (org-set-tags nil 'align)))
14758 (beginning-of-line 1)
14759 (if (looking-at ".*?\\([ \t]+\\)$")
14760 (delete-region (match-beginning 1) (match-end 1))))))
14762 (defun org-align-all-tags ()
14763 "Align the tags i all headings."
14766 (or (ignore-errors (org-back-to-heading t))
14767 (outline-next-heading))
14768 (if (org-at-heading-p)
14770 (message "No headings"))))
14772 (defvar org-indent-indentation-per-level)
14773 (defun org-set-tags (&optional arg just-align)
14774 "Set the tags for the current headline.
14775 With prefix ARG, realign all tags in headings in the current buffer.
14776 When JUST-ALIGN is non-nil, only align tags."
14778 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14779 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14780 'region-start-level 'region))
14781 org-loop-over-headlines-in-active-region)
14783 ;; We don't use ARG and JUST-ALIGN here because these args
14784 ;; are not useful when looping over headlines.
14786 org-loop-over-headlines-in-active-region
14787 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14788 (let* ((re org-outline-regexp-bol)
14789 (current (unless arg (org-get-tags-string)))
14790 (col (current-column))
14791 (org-setting-tags t)
14792 table current-tags inherited-tags ; computed below when needed
14793 tags p0 c0 c1 rpl di tc level)
14796 (goto-char (point-min))
14797 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14798 (while (re-search-forward re nil t)
14799 (org-set-tags nil t)
14801 (message "All tags realigned to column %d" org-tags-column))
14803 (setq tags current)
14804 ;; Get a new set of tags from the user
14806 (setq table (append org-tag-persistent-alist
14807 (or org-tag-alist (org-get-buffer-tags))
14809 org-complete-tags-always-offer-all-agenda-tags
14810 (org-global-tags-completion-table
14811 (org-agenda-files))))
14812 org-last-tags-completion-table table
14813 current-tags (org-split-string current ":")
14814 inherited-tags (nreverse
14815 (nthcdr (length current-tags)
14816 (nreverse (org-get-tags-at))))
14818 (if (or (eq t org-use-fast-tag-selection)
14819 (and org-use-fast-tag-selection
14820 (delq nil (mapcar 'cdr table))))
14821 (org-fast-tag-selection
14822 current-tags inherited-tags table
14823 (if org-fast-tag-selection-include-todo
14824 org-todo-key-alist))
14825 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14827 (org-icompleting-read "Tags: "
14828 'org-tags-completion-function
14829 nil nil current 'org-tags-history))))))
14830 (while (string-match "[-+&]+" tags)
14831 ;; No boolean logic, just a list
14832 (setq tags (replace-match ":" t t tags))))
14834 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14836 (if org-tags-sort-function
14837 (setq tags (mapconcat 'identity
14838 (sort (org-split-string
14839 tags (org-re "[^[:alnum:]_@#%]+"))
14840 org-tags-sort-function) ":")))
14842 (if (string-match "\\`[\t ]*\\'" tags)
14844 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14845 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14847 ;; Insert new tags at the correct column
14848 (beginning-of-line 1)
14849 (setq level (or (and (looking-at org-outline-regexp)
14850 (- (match-end 0) (point) 1))
14853 ((and (equal current "") (equal tags "")))
14854 ((re-search-forward
14855 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14857 (if (equal tags "")
14859 (goto-char (match-beginning 0))
14860 (setq c0 (current-column)
14861 ;; compute offset for the case of org-indent-mode active
14862 di (if (org-bound-and-true-p org-indent-mode)
14863 (* (1- org-indent-indentation-per-level) (1- level))
14865 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14866 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14867 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14868 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14869 (replace-match rpl t t)
14870 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14872 (t (error "Tags alignment failed")))
14873 (org-move-to-column col)
14875 (run-hooks 'org-after-tags-change-hook))))))
14877 (defun org-change-tag-in-region (beg end tag off)
14878 "Add or remove TAG for each entry in the region.
14879 This works in the agenda, and also in an org-mode buffer."
14881 (list (region-beginning) (region-end)
14882 (let ((org-last-tags-completion-table
14883 (if (derived-mode-p 'org-mode)
14885 (delq nil (append (org-get-buffer-tags)
14886 (org-global-tags-completion-table))))
14887 (org-global-tags-completion-table))))
14888 (org-icompleting-read
14889 "Tag: " 'org-tags-completion-function nil nil nil
14890 'org-tags-history))
14892 (message "[s]et or
[r]emove? ")
14893 (equal (read-char-exclusive) ?r))))
14894 (if (fboundp 'deactivate-mark) (deactivate-mark))
14895 (let ((agendap (equal major-mode 'org-agenda-mode))
14896 l1 l2 m buf pos newhead (cnt 0))
14898 (setq l2 (1- (org-current-line)))
14900 (setq l1 (org-current-line))
14901 (loop for l from l1 to l2 do
14903 (setq m (get-text-property (point) 'org-hd-marker))
14904 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14906 (setq buf (if agendap (marker-buffer m) (current-buffer))
14907 pos (if agendap m (point)))
14908 (with-current-buffer buf
14912 (setq cnt (1+ cnt))
14913 (org-toggle-tag tag (if off 'off 'on))
14914 (setq newhead (org-get-heading)))))
14915 (and agendap (org-agenda-change-all-lines newhead m))))
14916 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14918 (defun org-tags-completion-function (string predicate &optional flag)
14919 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14920 (confirm (lambda (x) (stringp (car x)))))
14921 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14922 (setq s1 (match-string 1 string)
14923 s2 (match-string 2 string))
14924 (setq s1 "" s2 string))
14928 (setq rtn (try-completion s2 ctable confirm))
14931 (concat s1 s2 (substring rtn (length s2))
14932 (if (and org-add-colon-after-tag-completion
14933 (assoc rtn ctable))
14938 (all-completions s2 ctable confirm))
14941 (assoc s2 ctable)))))
14943 (defun org-fast-tag-insert (kwd tags face &optional end)
14944 "Insert KDW, and the TAGS, the latter with face FACE.
14946 (insert (format "%-12s" (concat kwd ":"))
14947 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14950 (defun org-fast-tag-show-exit (flag)
14953 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14954 (replace-match ""))
14957 (org-move-to-column (- (window-width) 19) t)
14958 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14960 (defun org-set-current-tags-overlay (current prefix)
14961 "Add an overlay to CURRENT tag with PREFIX."
14962 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14963 (if (featurep 'xemacs)
14964 (org-overlay-display org-tags-overlay (concat prefix s)
14965 'secondary-selection)
14966 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14967 (org-overlay-display org-tags-overlay (concat prefix s)))))
14969 (defvar org-last-tag-selection-key nil)
14970 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14971 "Fast tag selection with single keys.
14972 CURRENT is the current list of tags in the headline, INHERITED is the
14973 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14974 possibly with grouping information. TODO-TABLE is a similar table with
14975 TODO keywords, should these have keys assigned to them.
14976 If the keys are nil, a-z are automatically assigned.
14977 Returns the new tags string, or nil to not change the current settings."
14978 (let* ((fulltable (append table todo-table))
14979 (maxlen (apply 'max (mapcar
14981 (if (stringp (car x)) (string-width (car x)) 0))
14983 (buf (current-buffer))
14984 (expert (eq org-fast-tag-selection-single-key 'expert))
14986 (fwidth (+ maxlen 3 1 3))
14987 (ncol (/ (- (window-width) 4) fwidth))
14990 tg cnt e c char c1 c2 ntable tbl rtn
14991 ov-start ov-end ov-prefix
14992 (exit-after-next org-fast-tag-selection-single-key)
14993 (done-keywords org-done-keywords)
14996 (beginning-of-line 1)
14998 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14999 (setq ov-start (match-beginning 1)
15000 ov-end (match-end 1)
15002 (setq ov-start (1- (point-at-eol))
15003 ov-end (1+ ov-start))
15004 (skip-chars-forward "^\n\r")
15007 (buffer-substring (1- (point)) (point))
15008 (if (> (current-column) org-tags-column)
15010 (make-string (- org-tags-column (current-column)) ?\ ))))))
15011 (move-overlay org-tags-overlay ov-start ov-end)
15012 (save-window-excursion
15014 (set-buffer (get-buffer-create " *Org tags*"))
15015 (delete-other-windows)
15016 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15017 (org-switch-to-buffer-other-window " *Org tags*"))
15019 (org-set-local 'org-done-keywords done-keywords)
15020 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15021 (org-fast-tag-insert "Current" current c-face "\n\n")
15022 (org-fast-tag-show-exit exit-after-next)
15023 (org-set-current-tags-overlay current ov-prefix)
15024 (setq tbl fulltable char ?a cnt 0)
15025 (while (setq e (pop tbl))
15027 ((equal (car e) :startgroup)
15028 (push '() groups) (setq ingroup t)
15029 (when (not (= cnt 0))
15032 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15033 ((equal (car e) :endgroup)
15034 (setq ingroup nil cnt 0)
15035 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15036 ((equal e '(:newline))
15037 (when (not (= cnt 0))
15041 (while (equal (car tbl) '(:newline))
15043 (setq tbl (cdr tbl)))))
15044 ((equal e '(:grouptags)) nil)
15046 (setq tg (copy-sequence (car e)) c2 nil)
15049 ;; automatically assign a character.
15050 (setq c1 (string-to-char
15051 (downcase (substring
15052 tg (if (= (string-to-char tg) ?@) 1 0)))))
15053 (if (or (rassoc c1 ntable) (rassoc c1 table))
15054 (while (or (rassoc char ntable) (rassoc char table))
15055 (setq char (1+ char)))
15057 (setq c (or c2 char)))
15058 (if ingroup (push tg (car groups)))
15059 (setq tg (org-add-props tg nil 'face
15061 ((not (assoc tg table))
15062 (org-get-todo-face tg))
15063 ((member tg current) c-face)
15064 ((member tg inherited) i-face))))
15065 (if (equal (caar tbl) :grouptags)
15066 (org-add-props tg nil 'face 'org-tag-group))
15067 (if (and (= cnt 0) (not ingroup)) (insert " "))
15068 (insert "[" c "] " tg (make-string
15069 (- fwidth 4 (length tg)) ?\ ))
15070 (push (cons tg c) ntable)
15071 (when (= (setq cnt (1+ cnt)) ncol)
15073 (if ingroup (insert " "))
15075 (setq ntable (nreverse ntable))
15077 (goto-char (point-min))
15078 (if (not expert) (org-fit-window-to-buffer))
15082 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15083 (if (not groups) "no " "")
15084 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15085 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15086 (setq org-last-tag-selection-key c)
15088 ((= c ?\r) (throw 'exit t))
15090 (setq groups (not groups))
15091 (goto-char (point-min))
15092 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15095 (org-fast-tag-show-exit
15096 (setq exit-after-next (not exit-after-next)))
15098 (delete-other-windows)
15099 (set-window-buffer (split-window-vertically) " *Org tags*")
15100 (org-switch-to-buffer-other-window " *Org tags*")
15101 (org-fit-window-to-buffer)))
15103 (and (= c ?q) (not (rassoc c ntable))))
15104 (org-detach-overlay org-tags-overlay)
15105 (setq quit-flag t))
15108 (if exit-after-next (setq exit-after-next 'now)))
15110 (condition-case nil
15111 (setq tg (org-icompleting-read
15114 (with-current-buffer buf
15115 (org-get-buffer-tags)))))
15116 (quit (setq tg "")))
15117 (when (string-match "\\S-" tg)
15118 (add-to-list 'buffer-tags (list tg))
15119 (if (member tg current)
15120 (setq current (delete tg current))
15121 (push tg current)))
15122 (if exit-after-next (setq exit-after-next 'now)))
15123 ((setq e (rassoc c todo-table) tg (car e))
15124 (with-current-buffer buf
15125 (save-excursion (org-todo tg)))
15126 (if exit-after-next (setq exit-after-next 'now)))
15127 ((setq e (rassoc c ntable) tg (car e))
15128 (if (member tg current)
15129 (setq current (delete tg current))
15130 (loop for g in groups do
15133 (setq current (delete x current)))
15136 (if exit-after-next (setq exit-after-next 'now))))
15138 ;; Create a sorted list
15142 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15143 (if (eq exit-after-next 'now) (throw 'exit t))
15144 (goto-char (point-min))
15145 (beginning-of-line 2)
15146 (delete-region (point) (point-at-eol))
15147 (org-fast-tag-insert "Current" current c-face)
15148 (org-set-current-tags-overlay current ov-prefix)
15149 (while (re-search-forward
15150 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15151 (setq tg (match-string 1))
15152 (add-text-properties
15153 (match-beginning 1) (match-end 1)
15156 ((member tg current) c-face)
15157 ((member tg inherited) i-face)
15158 (t (get-text-property (match-beginning 1) 'face))))))
15159 (goto-char (point-min)))))
15160 (org-detach-overlay org-tags-overlay)
15162 (mapconcat 'identity current ":")
15165 (defun org-get-tags-string ()
15166 "Get the TAGS string in the current headline."
15167 (unless (org-at-heading-p t)
15168 (user-error "Not on a heading"))
15170 (beginning-of-line 1)
15171 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15172 (org-match-string-no-properties 1)
15175 (defun org-get-tags ()
15176 "Get the list of tags specified in the current headline."
15177 (org-split-string (org-get-tags-string) ":"))
15179 (defun org-get-buffer-tags ()
15180 "Get a table of all tags used in the buffer, for completion."
15183 (goto-char (point-min))
15184 (while (re-search-forward
15185 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
15186 (when (equal (char-after (point-at-bol 0)) ?*)
15187 (mapc (lambda (x) (add-to-list 'tags x))
15188 (org-split-string (org-match-string-no-properties 1) ":")))))
15189 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
15190 (mapcar 'list tags)))
15192 ;;;; The mapping API
15194 (defun org-map-entries (func &optional match scope &rest skip)
15195 "Call FUNC at each headline selected by MATCH in SCOPE.
15197 FUNC is a function or a lisp form. The function will be called without
15198 arguments, with the cursor positioned at the beginning of the headline.
15199 The return values of all calls to the function will be collected and
15200 returned as a list.
15202 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15203 does not need to preserve point. After evaluation, the cursor will be
15204 moved to the end of the line (presumably of the headline of the
15205 processed entry) and search continues from there. Under some
15206 circumstances, this may not produce the wanted results. For example,
15207 if you have removed (e.g. archived) the current (sub)tree it could
15208 mean that the next entry will be skipped entirely. In such cases, you
15209 can specify the position from where search should continue by making
15210 FUNC set the variable `org-map-continue-from' to the desired buffer
15213 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15214 Only headlines that are matched by this query will be considered during
15215 the iteration. When MATCH is nil or t, all headlines will be
15216 visited by the iteration.
15218 SCOPE determines the scope of this command. It can be any of:
15220 nil The current buffer, respecting the restriction if any
15221 tree The subtree started with the entry at point
15222 region The entries within the active region, if any
15224 The entries within the active region, but only those at
15225 the same level than the first one.
15226 file The current buffer, without restriction
15228 The current buffer, and any archives associated with it
15229 agenda All agenda files
15230 agenda-with-archives
15231 All agenda files with any archive files associated with them
15233 If this is a list, all files in the list will be scanned
15235 The remaining args are treated as settings for the skipping facilities of
15236 the scanner. The following items can be given here:
15238 archive skip trees with the archive tag
15239 comment skip trees with the COMMENT keyword
15240 function or Emacs Lisp form:
15241 will be used as value for `org-agenda-skip-function', so
15242 whenever the function returns a position, FUNC will not be
15243 called for that entry and search will continue from the
15246 If your function needs to retrieve the tags including inherited tags
15247 at the *current* entry, you can use the value of the variable
15248 `org-scanner-tags' which will be much faster than getting the value
15249 with `org-get-tags-at'. If your function gets properties with
15250 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15251 to t around the call to `org-entry-properties' to get the same speedup.
15252 Note that if your function moves around to retrieve tags and properties at
15253 a *different* entry, you cannot use these techniques."
15254 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15255 (not (org-region-active-p)))
15256 (let* ((org-agenda-archives-mode nil) ; just to make sure
15257 (org-agenda-skip-archived-trees (memq 'archive skip))
15258 (org-agenda-skip-comment-trees (memq 'comment skip))
15259 (org-agenda-skip-function
15260 (car (org-delete-all '(comment archive) skip)))
15261 (org-tags-match-list-sublevels t)
15262 (start-level (eq scope 'region-start-level))
15264 org-todo-keywords-for-agenda
15265 org-done-keywords-for-agenda
15266 org-todo-keyword-alist-for-agenda
15267 org-tag-alist-for-agenda
15271 ((eq match t) (setq matcher t))
15272 ((eq match nil) (setq matcher t))
15273 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15277 (cond ((eq scope 'tree)
15278 (org-back-to-heading t)
15279 (org-narrow-to-subtree)
15281 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15282 (org-region-active-p))
15283 ;; If needed, set start-level to a string like "2"
15286 (goto-char (region-beginning))
15287 (unless (org-at-heading-p) (outline-next-heading))
15288 (setq start-level (org-current-level))))
15289 (narrow-to-region (region-beginning)
15291 (goto-char (region-end))
15292 (unless (and (bolp) (org-at-heading-p))
15293 (outline-next-heading))
15299 (org-agenda-prepare-buffers
15300 (list (buffer-file-name (current-buffer))))
15301 (setq res (org-scan-tags func matcher todo-only start-level)))
15302 ;; Get the right scope
15304 ((and scope (listp scope) (symbolp (car scope)))
15305 (setq scope (eval scope)))
15306 ((eq scope 'agenda)
15307 (setq scope (org-agenda-files t)))
15308 ((eq scope 'agenda-with-archives)
15309 (setq scope (org-agenda-files t))
15310 (setq scope (org-add-archive-files scope)))
15312 (setq scope (list (buffer-file-name))))
15313 ((eq scope 'file-with-archives)
15314 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15315 (org-agenda-prepare-buffers scope)
15316 (while (setq file (pop scope))
15317 (with-current-buffer (org-find-base-buffer-visiting file)
15321 (goto-char (point-min))
15322 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15327 ;;; Setting and retrieving properties
15329 (defconst org-special-properties
15330 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15331 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15332 "The special properties valid in Org-mode.
15334 These are properties that are not defined in the property drawer,
15335 but in some other way.")
15337 (defconst org-default-properties
15338 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15339 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15340 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15341 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15342 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15343 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15344 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15345 "Some properties that are used by Org-mode for various purposes.
15346 Being in this list makes sure that they are offered for completion.")
15348 (defun org-property-action ()
15349 "Do an action on properties."
15352 (org-at-property-p)
15353 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15354 (setq c (read-char-exclusive))
15357 (call-interactively 'org-set-property))
15359 (call-interactively 'org-delete-property))
15361 (call-interactively 'org-delete-property-globally))
15363 (call-interactively 'org-compute-property-at-point))
15364 (t (user-error "No such property action %c" c)))))
15366 (defun org-inc-effort ()
15367 "Increment the value of the effort property in the current entry."
15369 (org-set-effort nil t))
15371 (defvar org-clock-effort) ;; Defined in org-clock.el
15372 (defvar org-clock-current-task) ;; Defined in org-clock.el
15373 (defun org-set-effort (&optional value increment)
15374 "Set the effort property of the current entry.
15375 With numerical prefix arg, use the nth allowed value, 0 stands for the
15376 10th allowed value.
15378 When INCREMENT is non-nil, set the property to the next allowed value."
15380 (if (equal value 0) (setq value 10))
15381 (let* ((completion-ignore-case t)
15382 (prop org-effort-property)
15383 (cur (org-entry-get nil prop))
15384 (allowed (org-property-get-allowed-values nil prop 'table))
15385 (existing (mapcar 'list (org-property-values prop)))
15386 (heading (nth 4 (org-heading-components)))
15389 ((stringp value) value)
15390 ((and allowed (integerp value))
15391 (or (car (nth (1- value) allowed))
15392 (car (org-last allowed))))
15393 ((and allowed increment)
15394 (or (caadr (member (list cur) allowed))
15395 (user-error "Allowed effort values are not set")))
15397 (message "Select 1-9,0, [RET%s]: %s"
15398 (if cur (concat "=" cur) "")
15399 (mapconcat 'car allowed " "))
15400 (setq rpl (read-char-exclusive))
15401 (if (equal rpl ?\r)
15403 (setq rpl (- rpl ?0))
15404 (if (equal rpl 0) (setq rpl 10))
15405 (if (and (> rpl 0) (<= rpl (length allowed)))
15406 (car (nth (1- rpl) allowed))
15407 (org-completing-read "Effort: " allowed nil))))
15409 (let (org-completion-use-ido org-completion-use-iswitchb)
15410 (org-completing-read
15411 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15412 (concat "[" cur "]") "")
15414 existing nil nil "" nil cur))))))
15415 (unless (equal (org-entry-get nil prop) val)
15416 (org-entry-put nil prop val))
15417 (org-refresh-property
15418 '((effort . identity)
15419 (effort-minutes . org-duration-string-to-minutes))
15421 (when (string= heading org-clock-current-task)
15422 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15423 (org-clock-update-mode-line))
15424 (message "%s is now %s" prop val)))
15426 (defun org-at-property-p ()
15427 "Non-nil when point is inside a property drawer.
15428 See `org-property-re' for match data, if applicable."
15429 (when (eq (org-element-type (org-element-at-point)) 'node-property)
15431 (beginning-of-line)
15432 (looking-at org-property-re))))
15434 (defun org-get-property-block (&optional beg end force)
15435 "Return the (beg . end) range of the body of the property drawer.
15436 BEG and END are the beginning and end of the current subtree, or of
15437 the part before the first headline. If they are not given, they will
15438 be found. If the drawer does not exist and FORCE is non-nil, create
15442 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15443 (progn (org-back-to-heading t) (point))))
15444 (end (or end (and (not (outline-next-heading)) (point-max))
15447 (if (re-search-forward org-property-start-re end t)
15448 (setq beg (1+ (match-end 0)))
15451 (org-insert-property-drawer)
15452 (setq end (progn (outline-next-heading) (point))))
15455 (if (re-search-forward org-property-start-re end t)
15456 (setq beg (1+ (match-end 0)))))
15457 (if (re-search-forward org-property-end-re end t)
15458 (setq end (match-beginning 0))
15459 (or force (throw 'exit nil))
15463 (insert ":END:\n"))
15466 (defun org-entry-properties (&optional pom which specific)
15467 "Get all properties of the entry at point-or-marker POM.
15468 This includes the TODO keyword, the tags, time strings for deadline,
15469 scheduled, and clocking, and any additional properties defined in the
15470 entry. The return value is an alist, keys may occur multiple times
15471 if the property key was used several times.
15472 POM may also be nil, in which case the current entry is used.
15473 If WHICH is nil or `all', get all properties. If WHICH is
15474 `special' or `standard', only get that subclass. If WHICH
15475 is a string only get exactly this property. SPECIFIC can be a string, the
15476 specific property we are interested in. Specifying it can speed
15477 things up because then unnecessary parsing is avoided."
15478 (setq which (or which 'all))
15479 (org-with-wide-buffer
15480 (org-with-point-at pom
15481 (let ((clockstr (substring org-clock-string 0 -1))
15482 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15483 (case-fold-search nil)
15484 beg end range props sum-props key key1 value string clocksum clocksumt)
15485 (when (and (derived-mode-p 'org-mode)
15486 (ignore-errors (org-back-to-heading t)))
15488 (setq sum-props (get-text-property (point) 'org-summaries))
15489 (setq clocksum (get-text-property (point) :org-clock-minutes)
15490 clocksumt (get-text-property (point) :org-clock-minutes-today))
15491 (outline-next-heading)
15493 (when (memq which '(all special))
15494 ;; Get the special properties, like TODO and tags
15496 (when (and (or (not specific) (string= specific "TODO"))
15497 (looking-at org-todo-line-regexp) (match-end 2))
15498 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15499 (when (and (or (not specific) (string= specific "PRIORITY"))
15500 (looking-at org-priority-regexp))
15501 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15502 (when (or (not specific) (string= specific "FILE"))
15503 (push (cons "FILE" buffer-file-name) props))
15504 (when (and (or (not specific) (string= specific "TAGS"))
15505 (setq value (org-get-tags-string))
15506 (string-match "\\S-" value))
15507 (push (cons "TAGS" value) props))
15508 (when (and (or (not specific) (string= specific "ALLTAGS"))
15509 (setq value (org-get-tags-at)))
15510 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15513 (when (or (not specific) (string= specific "BLOCKED"))
15514 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15515 (when (or (not specific)
15517 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15518 "TIMESTAMP" "TIMESTAMP_IA")))
15520 (while (and (re-search-forward org-maybe-keyword-time-regexp end t)
15521 (not (text-property-any 0 (length (match-string 0))
15522 'face 'font-lock-comment-face
15523 (match-string 0))))
15524 (setq key (if (match-end 1)
15525 (substring (org-match-string-no-properties 1)
15527 string (if (equal key clockstr)
15529 (buffer-substring-no-properties
15530 (match-beginning 3) (goto-char
15532 (substring (org-match-string-no-properties 3)
15534 ;; Get the correct property name from the key. This is
15535 ;; necessary if the user has configured time keywords.
15536 (setq key1 (concat key ":"))
15540 (if (= (char-after (match-beginning 3)) ?\[)
15541 "TIMESTAMP_IA" "TIMESTAMP")))
15542 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15543 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15544 ((equal key1 org-closed-string) (setq key "CLOSED"))
15545 ((equal key1 org-clock-string) (setq key "CLOCK")))
15546 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15548 (push (cons key string) props)
15549 ;; no need to search further if match is found
15551 (when (or (equal key "CLOCK") (not (assoc key props)))
15552 (push (cons key string) props)))))))
15554 (when (memq which '(all standard))
15555 ;; Get the standard properties, like :PROP: ...
15556 (setq range (org-get-property-block beg end))
15558 (goto-char (car range))
15559 (while (re-search-forward org-property-re
15561 (setq key (org-match-string-no-properties 2)
15562 value (org-trim (or (org-match-string-no-properties 3) "")))
15563 (unless (member key excluded)
15564 (push (cons key (or value "")) props)))))
15566 (push (cons "CLOCKSUM"
15567 (org-columns-number-to-string (/ (float clocksum) 60.)
15571 (push (cons "CLOCKSUM_T"
15572 (org-columns-number-to-string (/ (float clocksumt) 60.)
15575 (unless (assoc "CATEGORY" props)
15576 (push (cons "CATEGORY" (org-get-category)) props))
15577 (append sum-props (nreverse props)))))))
15579 (defun org-entry-get (pom property &optional inherit literal-nil)
15580 "Get value of PROPERTY for entry or content at point-or-marker POM.
15581 If INHERIT is non-nil and the entry does not have the property,
15582 then also check higher levels of the hierarchy.
15583 If INHERIT is the symbol `selective', use inheritance only if the setting
15584 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15585 If the property is present but empty, the return value is the empty string.
15586 If the property is not present at all, nil is returned.
15588 Return the value as a string.
15590 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15591 do not interpret it as the list atom nil. This is used for inheritance
15592 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15593 (org-with-point-at pom
15594 (if (and inherit (if (eq inherit 'selective)
15595 (org-property-inherit-p property)
15597 (org-entry-get-with-inheritance property literal-nil)
15598 (if (member property org-special-properties)
15599 ;; We need a special property. Use `org-entry-properties'
15600 ;; to retrieve it, but specify the wanted property
15601 (cdr (assoc property (org-entry-properties nil 'special property)))
15602 (org-with-wide-buffer
15603 (let ((range (org-get-property-block)))
15604 (when (and range (not (eq (car range) (cdr range)))
15606 (goto-char (car range))
15608 (concat (org-re-property property) "\\|"
15609 (org-re-property (concat property "+")))
15612 (list (or (assoc property org-file-properties)
15613 (assoc property org-global-properties)
15614 (assoc property org-global-properties-fixed))))
15616 (when (re-search-forward
15617 (org-re-property key) (cdr range) t)
15619 (org-update-property-plist
15622 (org-match-string-no-properties 3) "")
15625 (goto-char (car range))
15626 (funcall ap property)
15627 (goto-char (car range))
15628 (while (funcall ap (concat property "+")))
15629 (setq val (cdr (assoc property props)))
15630 (when val (if literal-nil val (org-not-nil val)))))))))))
15632 (defun org-property-or-variable-value (var &optional inherit)
15633 "Check if there is a property fixing the value of VAR.
15634 If yes, return this value. If not, return the current value of the variable."
15635 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15636 (if (and prop (stringp prop) (string-match "\\S-" prop))
15638 (symbol-value var))))
15640 (defun org-entry-delete (pom property)
15641 "Delete the property PROPERTY from entry at point-or-marker POM."
15642 (unless (member property org-special-properties)
15643 (org-with-point-at pom
15644 (let ((range (org-get-property-block)))
15646 (goto-char (car range))
15648 (org-re-property property nil t)
15651 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15652 (org-remove-empty-drawer-at (car range))
15656 ;; Multi-values properties are properties that contain multiple values
15657 ;; These values are assumed to be single words, separated by whitespace.
15658 (defun org-entry-add-to-multivalued-property (pom property value)
15659 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15660 (let* ((old (org-entry-get pom property))
15661 (values (and old (org-split-string old "[ \t]"))))
15662 (setq value (org-entry-protect-space value))
15663 (unless (member value values)
15664 (setq values (append values (list value)))
15665 (org-entry-put pom property
15666 (mapconcat 'identity values " ")))))
15668 (defun org-entry-remove-from-multivalued-property (pom property value)
15669 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15670 (let* ((old (org-entry-get pom property))
15671 (values (and old (org-split-string old "[ \t]"))))
15672 (setq value (org-entry-protect-space value))
15673 (when (member value values)
15674 (setq values (delete value values))
15675 (org-entry-put pom property
15676 (mapconcat 'identity values " ")))))
15678 (defun org-entry-member-in-multivalued-property (pom property value)
15679 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15680 (let* ((old (org-entry-get pom property))
15681 (values (and old (org-split-string old "[ \t]"))))
15682 (setq value (org-entry-protect-space value))
15683 (member value values)))
15685 (defun org-entry-get-multivalued-property (pom property)
15686 "Return a list of values in a multivalued property."
15687 (let* ((value (org-entry-get pom property))
15688 (values (and value (org-split-string value "[ \t]"))))
15689 (mapcar 'org-entry-restore-space values)))
15691 (defun org-entry-put-multivalued-property (pom property &rest values)
15692 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15693 VALUES should be a list of strings. Spaces will be protected."
15694 (org-entry-put pom property
15695 (mapconcat 'org-entry-protect-space values " "))
15696 (let* ((value (org-entry-get pom property))
15697 (values (and value (org-split-string value "[ \t]"))))
15698 (mapcar 'org-entry-restore-space values)))
15700 (defun org-entry-protect-space (s)
15701 "Protect spaces and newline in string S."
15702 (while (string-match " " s)
15703 (setq s (replace-match "%20" t t s)))
15704 (while (string-match "\n" s)
15705 (setq s (replace-match "%0A" t t s)))
15708 (defun org-entry-restore-space (s)
15709 "Restore spaces and newline in string S."
15710 (while (string-match "%20" s)
15711 (setq s (replace-match " " t t s)))
15712 (while (string-match "%0A" s)
15713 (setq s (replace-match "\n" t t s)))
15716 (defvar org-entry-property-inherited-from (make-marker)
15717 "Marker pointing to the entry from where a property was inherited.
15718 Each call to `org-entry-get-with-inheritance' will set this marker to the
15719 location of the entry where the inheritance search matched. If there was
15720 no match, the marker will point nowhere.
15721 Note that also `org-entry-get' calls this function, if the INHERIT flag
15724 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15725 "Get PROPERTY of entry or content at point, search higher levels if needed.
15726 The search will stop at the first ancestor which has the property defined.
15727 If the value found is \"nil\", return nil to show that the property
15728 should be considered as undefined (this is the meaning of nil here).
15729 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15730 (move-marker org-entry-property-inherited-from nil)
15737 (when (setq tmp (org-entry-get nil property nil literal-nil))
15738 (or (ignore-errors (org-back-to-heading t))
15739 (goto-char (point-min)))
15740 (move-marker org-entry-property-inherited-from (point))
15742 (or (ignore-errors (org-up-heading-safe))
15743 (throw 'ex nil))))))
15745 (cdr (assoc property org-file-properties))
15746 (cdr (assoc property org-global-properties))
15747 (cdr (assoc property org-global-properties-fixed))))
15748 (if literal-nil tmp (org-not-nil tmp))))
15750 (defvar org-property-changed-functions nil
15751 "Hook called when the value of a property has changed.
15752 Each hook function should accept two arguments, the name of the property
15753 and the new value.")
15755 (defun org-entry-put (pom property value)
15756 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15757 If the value is `nil', it is converted to the empty string.
15758 If it is not a string, an error is raised."
15759 (cond ((null value) (setq value ""))
15760 ((not (stringp value))
15761 (error "Properties values should be strings.")))
15762 (org-with-point-at pom
15763 (org-back-to-heading t)
15764 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15767 ((equal property "TODO")
15768 (when (and (string-match "\\S-" value)
15769 (not (member value org-todo-keywords-1)))
15770 (user-error "\"%s\" is not a valid TODO state" value))
15771 (if (or (not value)
15772 (not (string-match "\\S-" value)))
15773 (setq value 'none))
15775 (org-set-tags nil 'align))
15776 ((equal property "PRIORITY")
15777 (org-priority (if (and value (string-match "\\S-" value))
15778 (string-to-char value) ?\ ))
15779 (org-set-tags nil 'align))
15780 ((equal property "CLOCKSUM")
15781 (if (not (re-search-forward
15782 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15783 (error "Cannot find a clock log")
15784 (goto-char (- (match-end 1) 2))
15786 ((eq value 'earlier) (org-timestamp-down))
15787 ((eq value 'later) (org-timestamp-up)))
15788 (org-clock-sum-current-item)))
15789 ((equal property "SCHEDULED")
15790 (if (re-search-forward org-scheduled-time-regexp end t)
15792 ((eq value 'earlier) (org-timestamp-change -1 'day))
15793 ((eq value 'later) (org-timestamp-change 1 'day))
15794 (t (call-interactively 'org-schedule)))
15795 (call-interactively 'org-schedule)))
15796 ((equal property "DEADLINE")
15797 (if (re-search-forward org-deadline-time-regexp end t)
15799 ((eq value 'earlier) (org-timestamp-change -1 'day))
15800 ((eq value 'later) (org-timestamp-change 1 'day))
15801 (t (call-interactively 'org-deadline)))
15802 (call-interactively 'org-deadline)))
15803 ((member property org-special-properties)
15804 (error "The %s property can not yet be set with `org-entry-put'"
15806 (t ; a non-special property
15807 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15808 (setq range (org-get-property-block beg end 'force))
15809 (goto-char (car range))
15810 (if (re-search-forward
15811 (org-re-property property nil t) (cdr range) t)
15813 (delete-region (match-beginning 0) (match-end 0))
15814 (goto-char (match-beginning 0)))
15815 (goto-char (cdr range))
15819 (insert ":" property ":")
15820 (and value (insert " " value))
15821 (org-indent-line)))))
15822 (run-hook-with-args 'org-property-changed-functions property value)))
15824 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15825 "Get all property keys in the current buffer.
15826 With INCLUDE-SPECIALS, also list the special properties that reflect things
15827 like tags and TODO state.
15828 With INCLUDE-DEFAULTS, also include properties that has special meaning
15829 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15831 With INCLUDE-COLUMNS, also include property names given in COLUMN
15832 formats in the current buffer."
15833 (let (rtn range cfmt s p)
15837 (goto-char (point-min))
15838 (while (re-search-forward org-property-start-re nil t)
15840 (setq range (or (org-get-property-block)
15842 (format "Malformed drawer at %d, repair?" (point)))
15843 (org-get-property-block nil nil t)
15844 (throw 'cont nil))))
15845 (goto-char (car range))
15846 (while (re-search-forward org-property-re
15848 (add-to-list 'rtn (org-match-string-no-properties 2)))
15849 (outline-next-heading)))))
15851 (when include-specials
15852 (setq rtn (append org-special-properties rtn)))
15854 (when include-defaults
15855 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15856 (add-to-list 'rtn org-effort-property))
15858 (when include-columns
15862 (goto-char (point-min))
15863 (while (re-search-forward
15864 "^[ \t]*\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15866 (setq cfmt (match-string 2) s 0)
15867 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15869 (setq s (match-end 0)
15870 p (match-string 1 cfmt))
15871 (unless (or (equal p "ITEM")
15872 (member p org-special-properties))
15873 (add-to-list 'rtn (match-string 1 cfmt))))))))
15875 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15877 (defun org-property-values (key)
15878 "Return a list of all values of property KEY in the current buffer."
15882 (goto-char (point-min))
15883 (let ((re (org-re-property key))
15885 (while (re-search-forward re nil t)
15886 (add-to-list 'values (org-trim (match-string 3))))
15887 (delete "" values)))))
15889 (defun org-insert-property-drawer ()
15890 "Insert a property drawer into the current entry."
15891 (org-back-to-heading t)
15892 (looking-at org-outline-regexp)
15893 (let ((indent (if org-adapt-indentation
15894 (- (match-end 0) (match-beginning 0))
15897 (re (concat "^[ \t]*" org-keyword-time-regexp))
15898 (org-clock-re (format "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|%s\\|:END:\\)"
15900 (org-skip-line-list (list org-clock-string ":END:"))
15902 (outline-next-heading)
15905 (while (re-search-forward re end t))
15906 (setq hiddenp (outline-invisible-p))
15908 (and (equal (char-after) ?\n) (forward-char 1))
15909 (while (looking-at org-clock-re)
15910 (if (member (match-string 1) org-skip-line-list)
15911 ;; just skip this line
15912 (beginning-of-line 2)
15913 ;; Drawer start, find the end
15914 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15915 (beginning-of-line 1)))
15916 (org-skip-over-state-notes)
15917 (skip-chars-backward " \t\n\r")
15918 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15920 (goto-char (point-at-eol))
15921 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15922 (beginning-of-line 0)
15923 (org-indent-to-column indent)
15924 (beginning-of-line 2)
15925 (org-indent-to-column indent)
15926 (beginning-of-line 0)
15929 (org-back-to-heading t)
15931 (org-flag-drawer t))))
15933 (defun org-insert-drawer (&optional arg drawer)
15934 "Insert a drawer at point.
15936 Optional argument DRAWER, when non-nil, is a string representing
15937 drawer's name. Otherwise, the user is prompted for a name.
15939 If a region is active, insert the drawer around that region
15942 Point is left between drawer's boundaries."
15944 (let* ((drawer (if arg "PROPERTIES"
15945 (or drawer (read-from-minibuffer "Drawer: ")))))
15947 ;; With C-u, fall back on `org-insert-property-drawer'
15948 (arg (org-insert-property-drawer))
15950 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15951 (user-error "Invalid drawer name"))
15952 ;; With an active region, insert a drawer at point.
15953 ((not (org-region-active-p))
15955 (unless (bolp) (insert "\n"))
15956 (insert (format ":%s:\n\n:END:\n" drawer))
15957 (forward-line -2)))
15958 ;; Otherwise, insert the drawer at point
15960 (let ((rbeg (region-beginning))
15961 (rend (copy-marker (region-end))))
15965 (beginning-of-line)
15966 (when (save-excursion
15967 (re-search-forward org-outline-regexp-bol rend t))
15968 (user-error "Drawers cannot contain headlines"))
15969 ;; Position point at the beginning of the first
15970 ;; non-blank line in region. Insert drawer's opening
15971 ;; there, then indent it.
15972 (org-skip-whitespace)
15973 (beginning-of-line)
15974 (insert ":" drawer ":\n")
15976 (indent-for-tab-command)
15977 ;; Move point to the beginning of the first blank line
15978 ;; after the last non-blank line in region. Insert
15979 ;; drawer's closing, then indent it.
15981 (skip-chars-backward " \r\t\n")
15983 (deactivate-mark t)
15984 (indent-for-tab-command)
15985 (unless (eolp) (insert "\n")))
15986 ;; Clear marker, whatever the outcome of insertion is.
15987 (set-marker rend nil)))))))
15989 (defvar org-property-set-functions-alist nil
15990 "Property set function alist.
15991 Each entry should have the following format:
15993 (PROPERTY . READ-FUNCTION)
15995 The read function will be called with the same argument as
15996 `org-completing-read'.")
15998 (defun org-set-property-function (property)
15999 "Get the function that should be used to set PROPERTY.
16000 This is computed according to `org-property-set-functions-alist'."
16001 (or (cdr (assoc property org-property-set-functions-alist))
16002 'org-completing-read))
16004 (defun org-read-property-value (property)
16005 "Read PROPERTY value from user."
16006 (let* ((completion-ignore-case t)
16007 (allowed (org-property-get-allowed-values nil property 'table))
16008 (cur (org-entry-get nil property))
16009 (prompt (concat property " value"
16010 (if (and cur (string-match "\\S-" cur))
16011 (concat " [" cur "]") "") ": "))
16012 (set-function (org-set-property-function property))
16014 (funcall set-function prompt allowed nil
16015 (not (get-text-property 0 'org-unrestricted
16017 (let (org-completion-use-ido org-completion-use-iswitchb)
16018 (funcall set-function prompt
16019 (mapcar 'list (org-property-values property))
16020 nil nil "" nil cur)))))
16023 (defvar org-last-set-property nil)
16024 (defvar org-last-set-property-value nil)
16025 (defun org-read-property-name ()
16026 "Read a property name."
16027 (let* ((completion-ignore-case t)
16028 (keys (org-buffer-property-keys nil t t))
16029 (default-prop (or (save-excursion
16031 (beginning-of-line)
16032 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
16033 (null (string= (match-string 1) "END"))
16034 (match-string 1))))
16035 org-last-set-property))
16036 (property (org-icompleting-read
16038 (if default-prop (concat " [" default-prop "]") "")
16040 (mapcar 'list keys)
16043 (if (member property keys)
16045 (or (cdr (assoc (downcase property)
16046 (mapcar (lambda (x) (cons (downcase x) x))
16050 (defun org-set-property-and-value (use-last)
16051 "Allow to set [PROPERTY]: [value] direction from prompt.
16052 When use-default, don't even ask, just use the last
16053 \"[PROPERTY]: [value]\" string from the history."
16055 (let* ((completion-ignore-case t)
16056 (pv (or (and use-last org-last-set-property-value)
16057 (org-completing-read
16058 "Enter a \"[Property]: [value]\" pair: "
16059 nil nil nil nil nil
16060 org-last-set-property-value)))
16062 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16063 (setq prop (match-string 1 pv)
16064 val (match-string 2 pv))
16065 (org-set-property prop val))))
16067 (defun org-set-property (property value)
16068 "In the current entry, set PROPERTY to VALUE.
16069 When called interactively, this will prompt for a property name, offering
16070 completion on existing and default properties. And then it will prompt
16071 for a value, offering completion either on allowed values (via an inherited
16072 xxx_ALL property) or on existing values in other instances of this property
16073 in the current file."
16074 (interactive (list nil nil))
16075 (let* ((property (or property (org-read-property-name)))
16076 (value (or value (org-read-property-value property)))
16077 (fn (cdr (assoc property org-properties-postprocess-alist))))
16078 (setq org-last-set-property property)
16079 (setq org-last-set-property-value (concat property ": " value))
16080 ;; Possibly postprocess the inserted value:
16081 (when fn (setq value (funcall fn value)))
16082 (unless (equal (org-entry-get nil property) value)
16083 (org-entry-put nil property value))))
16085 (defun org-delete-property (property)
16086 "In the current entry, delete PROPERTY."
16088 (let* ((completion-ignore-case t)
16089 (cat (org-entry-get (point) "CATEGORY"))
16090 (props0 (org-entry-properties nil 'standard))
16091 (props (if cat props0
16092 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16093 (prop (if (< 1 (length props))
16094 (org-icompleting-read "Property: " props nil t)
16098 (message "No property to delete in this entry")
16099 (org-entry-delete nil property)
16100 (message "Property \"%s\" deleted" property)))
16102 (defun org-delete-property-globally (property)
16103 "Remove PROPERTY globally, from all entries."
16105 (let* ((completion-ignore-case t)
16106 (prop (org-icompleting-read
16107 "Globally remove property: "
16108 (mapcar 'list (org-buffer-property-keys)))))
16113 (goto-char (point-min))
16115 (while (re-search-forward
16116 (org-re-property property)
16118 (setq cnt (1+ cnt))
16119 (delete-region (match-beginning 0) (1+ (point-at-eol))))
16120 (message "Property \"%s\" removed from %d entries" property cnt)))))
16122 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16124 (defun org-compute-property-at-point ()
16125 "Compute the property at point.
16126 This looks for an enclosing column format, extracts the operator and
16127 then applies it to the property in the column format's scope."
16129 (unless (org-at-property-p)
16130 (user-error "Not at a property"))
16131 (let ((prop (org-match-string-no-properties 2)))
16132 (org-columns-get-format-and-top-level)
16133 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16134 (user-error "No operator defined for property %s" prop))
16135 (org-columns-compute prop)))
16137 (defvar org-property-allowed-value-functions nil
16138 "Hook for functions supplying allowed values for a specific property.
16139 The functions must take a single argument, the name of the property, and
16140 return a flat list of allowed values. If \":ETC\" is one of
16141 the values, this means that these values are intended as defaults for
16142 completion, but that other values should be allowed too.
16143 The functions must return nil if they are not responsible for this
16146 (defun org-property-get-allowed-values (pom property &optional table)
16147 "Get allowed values for the property PROPERTY.
16148 When TABLE is non-nil, return an alist that can directly be used for
16152 ((equal property "TODO")
16153 (setq vals (org-with-point-at pom
16154 (append org-todo-keywords-1 '("")))))
16155 ((equal property "PRIORITY")
16156 (let ((n org-lowest-priority))
16157 (while (>= n org-highest-priority)
16158 (push (char-to-string n) vals)
16160 ((member property org-special-properties))
16161 ((setq vals (run-hook-with-args-until-success
16162 'org-property-allowed-value-functions property)))
16164 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16165 (when (and vals (string-match "\\S-" vals))
16166 (setq vals (car (read-from-string (concat "(" vals ")"))))
16167 (setq vals (mapcar (lambda (x)
16168 (cond ((stringp x) x)
16169 ((numberp x) (number-to-string x))
16170 ((symbolp x) (symbol-name x))
16173 (when (member ":ETC" vals)
16174 (setq vals (remove ":ETC" vals))
16175 (org-add-props (car vals) '(org-unrestricted t)))
16176 (if table (mapcar 'list vals) vals)))
16178 (defun org-property-previous-allowed-value (&optional previous)
16179 "Switch to the next allowed value for this property."
16181 (org-property-next-allowed-value t))
16183 (defun org-property-next-allowed-value (&optional previous)
16184 "Switch to the next allowed value for this property."
16186 (unless (org-at-property-p)
16187 (user-error "Not at a property"))
16188 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16189 (key (match-string 2))
16190 (value (match-string 3))
16191 (allowed (or (org-property-get-allowed-values (point) key)
16192 (and (member value '("[ ]" "[-]" "[X]"))
16194 (heading (save-match-data (nth 4 (org-heading-components))))
16197 (user-error "Allowed values for this property have not been defined"))
16198 (if previous (setq allowed (reverse allowed)))
16199 (if (member value allowed)
16200 (setq nval (car (cdr (member value allowed)))))
16201 (setq nval (or nval (car allowed)))
16202 (if (equal nval value)
16203 (user-error "Only one allowed value for this property"))
16204 (org-at-property-p)
16205 (replace-match (concat " :" key ": " nval) t t)
16207 (beginning-of-line 1)
16208 (skip-chars-forward " \t")
16209 (when (equal prop org-effort-property)
16210 (org-refresh-property
16211 '((effort . identity)
16212 (effort-minutes . org-duration-string-to-minutes))
16214 (when (string= org-clock-current-task heading)
16215 (setq org-clock-effort nval)
16216 (org-clock-update-mode-line)))
16217 (run-hook-with-args 'org-property-changed-functions key nval)))
16219 (defun org-find-olp (path &optional this-buffer)
16220 "Return a marker pointing to the entry at outline path OLP.
16221 If anything goes wrong, throw an error.
16222 You can wrap this call to catch the error like this:
16224 (condition-case msg
16225 (org-mobile-locate-entry (match-string 4))
16226 (error (nth 1 msg)))
16228 The return value will then be either a string with the error message,
16229 or a marker if everything is OK.
16231 If THIS-BUFFER is set, the outline path does not contain a file,
16233 (let* ((file (if this-buffer buffer-file-name (pop path)))
16234 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16238 limit re end found pos heading cnt flevel)
16239 (unless buffer (error "File not found :%s" file))
16240 (with-current-buffer buffer
16244 (setq limit (point-max))
16245 (goto-char (point-min))
16246 (while (setq heading (pop path))
16247 (setq re (format org-complex-heading-regexp-format
16248 (regexp-quote heading)))
16249 (setq cnt 0 pos (point))
16250 (while (re-search-forward re end t)
16251 (setq level (- (match-end 1) (match-beginning 1)))
16252 (if (and (>= level lmin) (<= level lmax))
16253 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16254 (when (= cnt 0) (error "Heading not found on level %d: %s"
16256 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16259 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16260 (setq end (save-excursion (org-end-of-subtree t t))))
16261 (when (org-at-heading-p)
16262 (point-marker)))))))
16264 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16265 "Find node HEADING in BUFFER.
16266 Return a marker to the heading if it was found, or nil if not.
16267 If POS-ONLY is set, return just the position instead of a marker.
16269 The heading text must match exact, but it may have a TODO keyword,
16270 a priority cookie and tags in the standard locations."
16271 (with-current-buffer (or buffer (current-buffer))
16275 (goto-char (point-min))
16276 (let (case-fold-search)
16277 (if (re-search-forward
16278 (format org-complex-heading-regexp-format
16279 (regexp-quote heading)) nil t)
16281 (match-beginning 0)
16282 (move-marker (make-marker) (match-beginning 0)))))))))
16284 (defun org-find-exact-heading-in-directory (heading &optional dir)
16285 "Find Org node headline HEADING in all .org files in directory DIR.
16286 When the target headline is found, return a marker to this location."
16287 (let ((files (directory-files (or dir default-directory)
16288 t "\\`[^.#].*\\.org\\'"))
16289 file visiting m buffer)
16291 (while (setq file (pop files))
16292 (message "trying %s" file)
16293 (setq visiting (org-find-base-buffer-visiting file))
16294 (setq buffer (or visiting (find-file-noselect file)))
16295 (setq m (org-find-exact-headline-in-buffer
16297 (when (and (not m) (not visiting)) (kill-buffer buffer))
16298 (and m (throw 'found m))))))
16300 (defun org-find-entry-with-id (ident)
16301 "Locate the entry that contains the ID property with exact value IDENT.
16302 IDENT can be a string, a symbol or a number, this function will search for
16303 the string representation of it.
16304 Return the position where this entry starts, or nil if there is no such entry."
16305 (interactive "sID: ")
16307 ((stringp ident) ident)
16308 ((symbol-name ident) (symbol-name ident))
16309 ((numberp ident) (number-to-string ident))
16310 (t (error "IDENT %s must be a string, symbol or number" ident))))
16311 (case-fold-search nil))
16315 (goto-char (point-min))
16316 (when (re-search-forward
16317 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16319 (org-back-to-heading t)
16324 (defvar org-last-changed-timestamp nil)
16325 (defvar org-last-inserted-timestamp nil
16326 "The last time stamp inserted with `org-insert-time-stamp'.")
16327 (defvar org-ts-what) ; dynamically scoped parameter
16329 (defun org-time-stamp (arg &optional inactive)
16330 "Prompt for a date/time and insert a time stamp.
16331 If the user specifies a time like HH:MM or if this command is
16332 called with at least one prefix argument, the time stamp contains
16333 the date and the time. Otherwise, only the date is be included.
16335 All parts of a date not specified by the user is filled in from
16336 the current date/time. So if you just press return without
16337 typing anything, the time stamp will represent the current
16340 If there is already a timestamp at the cursor, it will be
16343 With two universal prefix arguments, insert an active timestamp
16344 with the current time without prompting the user.
16346 When called from lisp, the timestamp is inactive if INACTIVE is
16351 ;; Default time is either today, or, when entering a range,
16352 ;; the range start.
16353 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16355 (re-search-backward
16356 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16357 (- (point) 20) t)))
16358 (apply 'encode-time (org-parse-time-string (match-string 1)))
16360 (default-input (and ts (org-get-compact-tod ts)))
16361 (repeater (save-excursion
16363 (beginning-of-line)
16364 (when (re-search-forward
16365 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16366 (save-excursion (progn (end-of-line) (point))) t)
16367 (match-string 0)))))
16368 org-time-was-given org-end-time-was-given time)
16370 ((and (org-at-timestamp-p t)
16371 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16372 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16374 (setq time (let ((this-command this-command))
16375 (org-read-date arg 'totime nil nil
16376 default-time default-input inactive)))
16377 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16378 ((org-at-timestamp-p t)
16379 (setq time (let ((this-command this-command))
16380 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16381 (when (org-at-timestamp-p t) ; just to get the match data
16382 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16384 (setq org-last-changed-timestamp
16385 (org-insert-time-stamp
16386 time (or org-time-was-given arg)
16387 inactive nil nil (list org-end-time-was-given)))
16388 (when repeater (goto-char (1- (point))) (insert " " repeater)
16389 (setq org-last-changed-timestamp
16390 (concat (substring org-last-inserted-timestamp 0 -1)
16391 " " repeater ">"))))
16392 (message "Timestamp updated"))
16394 (org-insert-time-stamp (current-time) t inactive))
16396 (setq time (let ((this-command this-command))
16397 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16398 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16399 nil nil (list org-end-time-was-given))))))
16401 ;; FIXME: can we use this for something else, like computing time differences?
16402 (defun org-get-compact-tod (s)
16403 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16404 (let* ((t1 (match-string 1 s))
16405 (h1 (string-to-number (match-string 2 s)))
16406 (m1 (string-to-number (match-string 3 s)))
16407 (t2 (and (match-end 4) (match-string 5 s)))
16408 (h2 (and t2 (string-to-number (match-string 6 s))))
16409 (m2 (and t2 (string-to-number (match-string 7 s))))
16413 (setq dh (- h2 h1) dm (- m2 m1))
16414 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16415 (concat t1 "+" (number-to-string dh)
16416 (and (/= 0 dm) (format ":%02d" dm)))))))
16418 (defun org-time-stamp-inactive (&optional arg)
16419 "Insert an inactive time stamp.
16420 An inactive time stamp is enclosed in square brackets instead of angle
16421 brackets. It is inactive in the sense that it does not trigger agenda entries,
16422 does not link to the calendar and cannot be changed with the S-cursor keys.
16423 So these are more for recording a certain time/date."
16425 (org-time-stamp arg 'inactive))
16427 (defvar org-date-ovl (make-overlay 1 1))
16428 (overlay-put org-date-ovl 'face 'org-date-selected)
16429 (org-detach-overlay org-date-ovl)
16431 (defvar org-ans1) ; dynamically scoped parameter
16432 (defvar org-ans2) ; dynamically scoped parameter
16434 (defvar org-plain-time-of-day-regexp) ; defined below
16436 (defvar org-overriding-default-time nil) ; dynamically scoped
16437 (defvar org-read-date-overlay nil)
16438 (defvar org-dcst nil) ; dynamically scoped
16439 (defvar org-read-date-history nil)
16440 (defvar org-read-date-final-answer nil)
16441 (defvar org-read-date-analyze-futurep nil)
16442 (defvar org-read-date-analyze-forced-year nil)
16443 (defvar org-read-date-inactive)
16445 (defvar org-read-date-minibuffer-local-map
16446 (let* ((org-replace-disputed-keys nil)
16447 (map (make-sparse-keymap)))
16448 (set-keymap-parent map minibuffer-local-map)
16449 (org-defkey map (kbd ".")
16450 (lambda () (interactive)
16451 ;; Are we at the beginning of the prompt?
16452 (if (looking-back "^[^:]+: ")
16453 (org-eval-in-calendar '(calendar-goto-today))
16455 (org-defkey map (kbd "C-.")
16456 (lambda () (interactive)
16457 (org-eval-in-calendar '(calendar-goto-today))))
16458 (org-defkey map [(meta shift left)]
16459 (lambda () (interactive)
16460 (org-eval-in-calendar '(calendar-backward-month 1))))
16461 (org-defkey map [(meta shift right)]
16462 (lambda () (interactive)
16463 (org-eval-in-calendar '(calendar-forward-month 1))))
16464 (org-defkey map [(meta shift up)]
16465 (lambda () (interactive)
16466 (org-eval-in-calendar '(calendar-backward-year 1))))
16467 (org-defkey map [(meta shift down)]
16468 (lambda () (interactive)
16469 (org-eval-in-calendar '(calendar-forward-year 1))))
16470 (org-defkey map [?\e (shift left)]
16471 (lambda () (interactive)
16472 (org-eval-in-calendar '(calendar-backward-month 1))))
16473 (org-defkey map [?\e (shift right)]
16474 (lambda () (interactive)
16475 (org-eval-in-calendar '(calendar-forward-month 1))))
16476 (org-defkey map [?\e (shift up)]
16477 (lambda () (interactive)
16478 (org-eval-in-calendar '(calendar-backward-year 1))))
16479 (org-defkey map [?\e (shift down)]
16480 (lambda () (interactive)
16481 (org-eval-in-calendar '(calendar-forward-year 1))))
16482 (org-defkey map [(shift up)]
16483 (lambda () (interactive)
16484 (org-eval-in-calendar '(calendar-backward-week 1))))
16485 (org-defkey map [(shift down)]
16486 (lambda () (interactive)
16487 (org-eval-in-calendar '(calendar-forward-week 1))))
16488 (org-defkey map [(shift left)]
16489 (lambda () (interactive)
16490 (org-eval-in-calendar '(calendar-backward-day 1))))
16491 (org-defkey map [(shift right)]
16492 (lambda () (interactive)
16493 (org-eval-in-calendar '(calendar-forward-day 1))))
16494 (org-defkey map "!"
16495 (lambda () (interactive)
16496 (org-eval-in-calendar '(diary-view-entries))
16498 (org-defkey map ">"
16499 (lambda () (interactive)
16500 (org-eval-in-calendar '(scroll-calendar-left 1))))
16501 (org-defkey map "<"
16502 (lambda () (interactive)
16503 (org-eval-in-calendar '(scroll-calendar-right 1))))
16504 (org-defkey map "\C-v"
16505 (lambda () (interactive)
16506 (org-eval-in-calendar
16507 '(calendar-scroll-left-three-months 1))))
16508 (org-defkey map "\M-v"
16509 (lambda () (interactive)
16510 (org-eval-in-calendar
16511 '(calendar-scroll-right-three-months 1))))
16513 "Keymap for minibuffer commands when using `org-read-date'.")
16516 (defvar org-defdecode)
16517 (defvar org-with-time)
16519 (defun org-read-date (&optional org-with-time to-time from-string prompt
16520 default-time default-input inactive)
16521 "Read a date, possibly a time, and make things smooth for the user.
16522 The prompt will suggest to enter an ISO date, but you can also enter anything
16523 which will at least partially be understood by `parse-time-string'.
16524 Unrecognized parts of the date will default to the current day, month, year,
16525 hour and minute. If this command is called to replace a timestamp at point,
16526 or to enter the second timestamp of a range, the default time is taken
16527 from the existing stamp. Furthermore, the command prefers the future,
16528 so if you are giving a date where the year is not given, and the day-month
16529 combination is already past in the current year, it will assume you
16530 mean next year. For details, see the manual. A few examples:
16532 3-2-5 --> 2003-02-05
16533 feb 15 --> currentyear-02-15
16534 2/15 --> currentyear-02-15
16535 sep 12 9 --> 2009-09-12
16536 12:45 --> today 12:45
16537 22 sept 0:34 --> currentyear-09-22 0:34
16538 12 --> currentyear-currentmonth-12
16539 Fri --> nearest Friday after today
16540 -Tue --> last Tuesday
16543 Furthermore you can specify a relative date by giving, as the *first* thing
16544 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16545 change in days weeks, months, years.
16546 With a single plus or minus, the date is relative to today. With a double
16547 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16548 +4d --> four days from today
16549 +4 --> same as above
16550 +2w --> two weeks from today
16551 ++5 --> five days from default date
16553 The function understands only English month and weekday abbreviations.
16555 While prompting, a calendar is popped up - you can also select the
16556 date with the mouse (button 1). The calendar shows a period of three
16557 months. To scroll it to other months, use the keys `>' and `<'.
16558 If you don't like the calendar, turn it off with
16559 \(setq org-read-date-popup-calendar nil)
16561 With optional argument TO-TIME, the date will immediately be converted
16562 to an internal time.
16563 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16564 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16565 still enter a time, and this function will inform the calling routine
16566 about this change. The calling routine may then choose to change the
16567 format used to insert the time stamp into the buffer to include the time.
16568 With optional argument FROM-STRING, read from this string instead from
16569 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16570 the time/date that is used for everything that is not specified by the
16572 (require 'parse-time)
16573 (let* ((org-time-stamp-rounding-minutes
16574 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16575 (org-dcst org-display-custom-times)
16576 (ct (org-current-time))
16577 (org-def (or org-overriding-default-time default-time ct))
16578 (org-defdecode (decode-time org-def))
16580 (when (< (nth 2 org-defdecode) org-extend-today-until)
16581 (setcar (nthcdr 2 org-defdecode) -1)
16582 (setcar (nthcdr 1 org-defdecode) 59)
16583 (setq org-def (apply 'encode-time org-defdecode)
16584 org-defdecode (decode-time org-def)))))
16585 (mouse-autoselect-window nil) ; Don't let the mouse jump
16586 (calendar-frame-setup nil)
16587 (calendar-setup nil)
16588 (calendar-move-hook nil)
16589 (calendar-view-diary-initially-flag nil)
16590 (calendar-view-holidays-initially-flag nil)
16591 (timestr (format-time-string
16592 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16593 (prompt (concat (if prompt (concat prompt " ") "")
16594 (format "Date+time [%s]: " timestr)))
16595 ans (org-ans0 "") org-ans1 org-ans2 final)
16598 (from-string (setq ans from-string))
16599 (org-read-date-popup-calendar
16601 (save-window-excursion
16603 (org-eval-in-calendar '(setq cursor-type nil) t)
16606 (calendar-forward-day (- (time-to-days org-def)
16607 (calendar-absolute-from-gregorian
16608 (calendar-current-date))))
16609 (org-eval-in-calendar nil t)
16610 (let* ((old-map (current-local-map))
16611 (map (copy-keymap calendar-mode-map))
16612 (minibuffer-local-map
16613 (copy-keymap org-read-date-minibuffer-local-map)))
16614 (org-defkey map (kbd "RET") 'org-calendar-select)
16615 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16616 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16619 (use-local-map map)
16620 (setq org-read-date-inactive inactive)
16621 (add-hook 'post-command-hook 'org-read-date-display)
16622 (setq org-ans0 (read-string prompt default-input
16623 'org-read-date-history nil))
16624 ;; org-ans0: from prompt
16625 ;; org-ans1: from mouse click
16626 ;; org-ans2: from calendar motion
16627 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16628 (remove-hook 'post-command-hook 'org-read-date-display)
16629 (use-local-map old-map)
16630 (when org-read-date-overlay
16631 (delete-overlay org-read-date-overlay)
16632 (setq org-read-date-overlay nil)))))
16633 (bury-buffer "*Calendar*")))))
16635 (t ; Naked prompt only
16637 (setq ans (read-string prompt default-input
16638 'org-read-date-history timestr))
16639 (when org-read-date-overlay
16640 (delete-overlay org-read-date-overlay)
16641 (setq org-read-date-overlay nil)))))
16643 (setq final (org-read-date-analyze ans org-def org-defdecode))
16645 (when org-read-date-analyze-forced-year
16646 (message "Year was forced into %s"
16647 (if org-read-date-force-compatible-dates
16648 "compatible range (1970-2037)"
16649 "range representable on this machine"))
16652 ;; One round trip to get rid of 34th of August and stuff like that....
16653 (setq final (decode-time (apply 'encode-time final)))
16655 (setq org-read-date-final-answer ans)
16658 (apply 'encode-time final)
16659 (if (and (boundp 'org-time-was-given) org-time-was-given)
16660 (format "%04d-%02d-%02d %02d:%02d"
16661 (nth 5 final) (nth 4 final) (nth 3 final)
16662 (nth 2 final) (nth 1 final))
16663 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16665 (defun org-read-date-display ()
16666 "Display the current date prompt interpretation in the minibuffer."
16667 (when org-read-date-display-live
16668 (when org-read-date-overlay
16669 (delete-overlay org-read-date-overlay))
16670 (when (minibufferp (current-buffer))
16673 (while (not (equal (buffer-substring
16674 (max (point-min) (- (point) 4)) (point))
16677 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16678 " " (or org-ans1 org-ans2)))
16679 (org-end-time-was-given nil)
16680 (f (org-read-date-analyze ans org-def org-defdecode))
16682 org-time-stamp-custom-formats
16683 org-time-stamp-formats))
16684 (fmt (if (or org-with-time
16685 (and (boundp 'org-time-was-given) org-time-was-given))
16688 (txt (format-time-string fmt (apply 'encode-time f)))
16689 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16690 (txt (concat "=> " txt)))
16691 (when (and org-end-time-was-given
16692 (string-match org-plain-time-of-day-regexp txt))
16693 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16694 org-end-time-was-given
16695 (substring txt (match-end 0)))))
16696 (when org-read-date-analyze-futurep
16697 (setq txt (concat txt " (=>F)")))
16698 (setq org-read-date-overlay
16699 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16700 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16702 (defun org-read-date-analyze (ans org-def org-defdecode)
16703 "Analyze the combined answer of the date prompt."
16704 ;; FIXME: cleanup and comment
16705 (let ((nowdecode (decode-time (current-time)))
16706 delta deltan deltaw deltadef year month day
16707 hour minute second wday pm h2 m2 tl wday1
16708 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16709 (setq org-read-date-analyze-futurep nil
16710 org-read-date-analyze-forced-year nil)
16711 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16714 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16715 (setq ans (replace-match "" t t ans)
16717 deltaw (nth 1 delta)
16718 deltadef (nth 2 delta)))
16720 ;; Check if there is an iso week date in there. If yes, store the
16721 ;; info and postpone interpreting it until the rest of the parsing
16723 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16724 (setq iso-year (if (match-end 1)
16725 (org-small-year-to-year
16726 (string-to-number (match-string 1 ans))))
16727 iso-weekday (if (match-end 3)
16728 (string-to-number (match-string 3 ans)))
16729 iso-week (string-to-number (match-string 2 ans)))
16730 (setq ans (replace-match "" t t ans)))
16732 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16733 (when (string-match
16734 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16735 (setq year (if (match-end 2)
16736 (string-to-number (match-string 2 ans))
16737 (progn (setq kill-year t)
16738 (string-to-number (format-time-string "%Y"))))
16739 month (string-to-number (match-string 3 ans))
16740 day (string-to-number (match-string 4 ans)))
16741 (if (< year 100) (setq year (+ 2000 year)))
16742 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16745 ;; Help matching dotted european dates
16746 (when (string-match
16747 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16748 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16750 (string-to-number (format-time-string "%Y")))
16751 day (string-to-number (match-string 1 ans))
16752 month (string-to-number (match-string 2 ans))
16753 ans (replace-match (format "%04d-%02d-%02d" year month day)
16756 ;; Help matching american dates, like 5/30 or 5/30/7
16757 (when (string-match
16758 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16759 (setq year (if (match-end 4)
16760 (string-to-number (match-string 4 ans))
16761 (progn (setq kill-year t)
16762 (string-to-number (format-time-string "%Y"))))
16763 month (string-to-number (match-string 1 ans))
16764 day (string-to-number (match-string 2 ans)))
16765 (if (< year 100) (setq year (+ 2000 year)))
16766 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16768 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16769 ;; If there is a time with am/pm, and *no* time without it, we convert
16770 ;; so that matching will be successful.
16771 (loop for i from 1 to 2 do ; twice, for end time as well
16772 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16773 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16774 (setq hour (string-to-number (match-string 1 ans))
16775 minute (if (match-end 3)
16776 (string-to-number (match-string 3 ans))
16779 (string-to-char (downcase (match-string 4 ans)))))
16780 (if (and (= hour 12) (not pm))
16782 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16783 (setq ans (replace-match (format "%02d:%02d" hour minute)
16786 ;; Check if a time range is given as a duration
16787 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16788 (setq hour (string-to-number (match-string 1 ans))
16789 h2 (+ hour (string-to-number (match-string 3 ans)))
16790 minute (string-to-number (match-string 2 ans))
16791 m2 (+ minute (if (match-end 5) (string-to-number
16792 (match-string 5 ans))0)))
16793 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16794 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16797 ;; Check if there is a time range
16798 (when (boundp 'org-end-time-was-given)
16799 (setq org-time-was-given nil)
16800 (when (and (string-match org-plain-time-of-day-regexp ans)
16802 (setq org-end-time-was-given (match-string 8 ans))
16803 (setq ans (concat (substring ans 0 (match-beginning 7))
16804 (substring ans (match-end 7))))))
16806 (setq tl (parse-time-string ans)
16807 day (or (nth 3 tl) (nth 3 org-defdecode))
16808 month (or (nth 4 tl)
16809 (if (and org-read-date-prefer-future
16810 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16811 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16812 (nth 4 org-defdecode)))
16813 year (or (and (not kill-year) (nth 5 tl))
16814 (if (and org-read-date-prefer-future
16815 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16816 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16817 (nth 5 org-defdecode)))
16818 hour (or (nth 2 tl) (nth 2 org-defdecode))
16819 minute (or (nth 1 tl) (nth 1 org-defdecode))
16820 second (or (nth 0 tl) 0)
16823 (when (and (eq org-read-date-prefer-future 'time)
16824 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16825 (equal day (nth 3 nowdecode))
16826 (equal month (nth 4 nowdecode))
16827 (equal year (nth 5 nowdecode))
16829 (or (< (nth 2 tl) (nth 2 nowdecode))
16830 (and (= (nth 2 tl) (nth 2 nowdecode))
16832 (< (nth 1 tl) (nth 1 nowdecode)))))
16836 ;; Special date definitions below
16839 ;; There was an iso week
16842 (setq year (or iso-year year)
16843 day (or iso-weekday wday 1)
16844 wday nil ; to make sure that the trigger below does not match
16845 iso-date (calendar-gregorian-from-absolute
16846 (calendar-absolute-from-iso
16847 (list iso-week day year))))
16848 ; FIXME: Should we also push ISO weeks into the future?
16849 ; (when (and org-read-date-prefer-future
16851 ; (< (calendar-absolute-from-gregorian iso-date)
16852 ; (time-to-days (current-time))))
16853 ; (setq year (1+ year)
16854 ; iso-date (calendar-gregorian-from-absolute
16855 ; (calendar-absolute-from-iso
16856 ; (list iso-week day year)))))
16857 (setq month (car iso-date)
16858 year (nth 2 iso-date)
16859 day (nth 1 iso-date)))
16863 (let ((now (decode-time (current-time))))
16864 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16865 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16866 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16867 ((equal deltaw "m") (setq month (+ month deltan)))
16868 ((equal deltaw "y") (setq year (+ year deltan)))))
16869 ((and wday (not (nth 3 tl)))
16870 ;; Weekday was given, but no day, so pick that day in the week
16871 ;; on or after the derived date.
16872 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16873 (unless (equal wday wday1)
16874 (setq day (+ day (% (- wday wday1 -7) 7))))))
16875 (if (and (boundp 'org-time-was-given)
16877 (setq org-time-was-given t))
16878 (if (< year 100) (setq year (+ 2000 year)))
16879 ;; Check of the date is representable
16880 (if org-read-date-force-compatible-dates
16883 (setq year 1970 org-read-date-analyze-forced-year t))
16885 (setq year 2037 org-read-date-analyze-forced-year t)))
16886 (condition-case nil
16887 (ignore (encode-time second minute hour day month year))
16889 (setq year (nth 5 org-defdecode))
16890 (setq org-read-date-analyze-forced-year t))))
16891 (setq org-read-date-analyze-futurep futurep)
16892 (list second minute hour day month year)))
16894 (defvar parse-time-weekdays)
16895 (defun org-read-date-get-relative (s today default)
16896 "Check string S for special relative date string.
16897 TODAY and DEFAULT are internal times, for today and for a default.
16898 Return shift list (N what def-flag)
16899 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16900 N is the number of WHATs to shift.
16901 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16902 the DEFAULT date rather than TODAY."
16903 (require 'parse-time)
16907 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16909 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16910 "\\([ \t]\\|$\\)") s)
16911 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16912 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16913 (string-to-char (substring (match-string 1 s) -1))
16915 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16916 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16917 (what (if (match-end 3) (match-string 3 s) "d"))
16918 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16919 (date (if rel default today))
16920 (wday (nth 6 (decode-time date)))
16924 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16925 (if (= delta 0) (setq delta 7))
16928 (setq delta (- delta 7))
16929 (if (= delta 0) (setq delta -7))))
16930 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16931 (list delta "d" rel))
16932 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16934 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16935 "Turn a user-specified date into the internal representation.
16936 The internal representation needed by the calendar is (month day year).
16937 This is a wrapper to handle the brain-dead convention in calendar that
16938 user function argument order change dependent on argument order."
16939 (if (boundp 'calendar-date-style)
16941 ((eq calendar-date-style 'american)
16942 (list arg1 arg2 arg3))
16943 ((eq calendar-date-style 'european)
16944 (list arg2 arg1 arg3))
16945 ((eq calendar-date-style 'iso)
16946 (list arg2 arg3 arg1)))
16947 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16948 (if (org-bound-and-true-p european-calendar-style)
16949 (list arg2 arg1 arg3)
16950 (list arg1 arg2 arg3)))))
16952 (defun org-eval-in-calendar (form &optional keepdate)
16953 "Eval FORM in the calendar window and return to current window.
16954 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16955 otherwise stick to the current value of `org-ans2'."
16956 (let ((sf (selected-frame))
16957 (sw (selected-window)))
16958 (select-window (get-buffer-window "*Calendar*" t))
16960 (when (and (not keepdate) (calendar-cursor-to-date))
16961 (let* ((date (calendar-cursor-to-date))
16962 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16963 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16964 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16966 (org-select-frame-set-input-focus sf)))
16968 (defun org-calendar-select ()
16969 "Return to `org-read-date' with the date currently selected.
16970 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16972 (when (calendar-cursor-to-date)
16973 (let* ((date (calendar-cursor-to-date))
16974 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16975 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16976 (if (active-minibuffer-window) (exit-minibuffer))))
16978 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16979 "Insert a date stamp for the date given by the internal TIME.
16980 WITH-HM means use the stamp format that includes the time of the day.
16981 INACTIVE means use square brackets instead of angular ones, so that the
16982 stamp will not contribute to the agenda.
16983 PRE and POST are optional strings to be inserted before and after the
16985 The command returns the inserted time stamp."
16986 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16988 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16989 (insert-before-markers (or pre ""))
16990 (when (listp extra)
16991 (setq extra (car extra))
16992 (if (and (stringp extra)
16993 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16994 (setq extra (format "-%02d:%02d"
16995 (string-to-number (match-string 1 extra))
16996 (string-to-number (match-string 2 extra))))
16999 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17000 (insert-before-markers (setq stamp (format-time-string fmt time)))
17001 (insert-before-markers (or post ""))
17002 (setq org-last-inserted-timestamp stamp)))
17004 (defun org-toggle-time-stamp-overlays ()
17005 "Toggle the use of custom time stamp formats."
17007 (setq org-display-custom-times (not org-display-custom-times))
17008 (unless org-display-custom-times
17009 (let ((p (point-min)) (bmp (buffer-modified-p)))
17010 (while (setq p (next-single-property-change p 'display))
17011 (if (and (get-text-property p 'display)
17012 (eq (get-text-property p 'face) 'org-date))
17013 (remove-text-properties
17014 p (setq p (next-single-property-change p 'display))
17016 (set-buffer-modified-p bmp)))
17017 (if (featurep 'xemacs)
17018 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17019 (org-restart-font-lock)
17020 (setq org-table-may-need-update t)
17021 (if org-display-custom-times
17022 (message "Time stamps are overlaid with custom format")
17023 (message "Time stamp overlays removed")))
17025 (defun org-display-custom-time (beg end)
17026 "Overlay modified time stamp format over timestamp between BEG and END."
17027 (let* ((ts (buffer-substring beg end))
17028 t1 w1 with-hm tf time str w2 (off 0))
17030 (setq t1 (org-parse-time-string ts t))
17031 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17032 (setq off (- (match-end 0) (match-beginning 0)))))
17033 (setq end (- end off))
17034 (setq w1 (- end beg)
17035 with-hm (and (nth 1 t1) (nth 2 t1))
17036 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17037 time (org-fix-decoded-time t1)
17039 (format-time-string
17040 (substring tf 1 -1) (apply 'encode-time time))
17041 nil 'mouse-face 'highlight)
17043 (if (not (= w2 w1))
17044 (add-text-properties (1+ beg) (+ 2 beg)
17045 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17046 (if (featurep 'xemacs)
17048 (put-text-property beg end 'invisible t)
17049 (put-text-property beg end 'end-glyph (make-glyph str)))
17050 (put-text-property beg end 'display str))))
17052 (defun org-translate-time (string)
17053 "Translate all timestamps in STRING to custom format.
17054 But do this only if the variable `org-display-custom-times' is set."
17055 (when org-display-custom-times
17058 (re org-ts-regexp-both)
17059 t1 with-hm inactive tf time str beg end)
17060 (while (setq start (string-match re string start))
17061 (setq beg (match-beginning 0)
17063 t1 (save-match-data
17064 (org-parse-time-string (substring string beg end) t))
17065 with-hm (and (nth 1 t1) (nth 2 t1))
17066 inactive (equal (substring string beg (1+ beg)) "[")
17067 tf (funcall (if with-hm 'cdr 'car)
17068 org-time-stamp-custom-formats)
17069 time (org-fix-decoded-time t1)
17070 str (format-time-string
17072 (if inactive "[" "<") (substring tf 1 -1)
17073 (if inactive "]" ">"))
17074 (apply 'encode-time time))
17075 string (replace-match str t t string)
17076 start (+ start (length str)))))))
17079 (defun org-fix-decoded-time (time)
17080 "Set 0 instead of nil for the first 6 elements of time.
17081 Don't touch the rest."
17083 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17085 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17087 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17088 "Difference between TIMESTAMP-STRING and now in days.
17089 If SECONDS is non-nil, return the difference in seconds."
17090 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17091 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17092 (funcall fdiff (current-time)))))
17094 (defun org-deadline-close (timestamp-string &optional ndays)
17095 "Is the time in TIMESTAMP-STRING close to the current date?"
17096 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17097 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17098 (not (org-entry-is-done-p))))
17100 (defun org-get-wdays (ts &optional delay zero-delay)
17101 "Get the deadline lead time appropriate for timestring TS.
17102 When DELAY is non-nil, get the delay time for scheduled items
17103 instead of the deadline lead time. When ZERO-DELAY is non-nil
17104 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17105 don't try to find the delay cookie in the scheduled timestamp."
17106 (let ((tv (if delay org-scheduled-delay-days
17107 org-deadline-warning-days)))
17109 ((or (and delay (< tv 0))
17110 (and delay zero-delay (<= tv 0))
17111 (and (not delay) (<= tv 0)))
17112 ;; Enforce this value no matter what
17114 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17115 ;; lead time is specified.
17116 (floor (* (string-to-number (match-string 1 ts))
17117 (cdr (assoc (match-string 2 ts)
17118 '(("d" . 1) ("w" . 7)
17119 ("m" . 30.4) ("y" . 365.25)
17120 ("h" . 0.041667)))))))
17121 ;; go for the default.
17124 (defun org-calendar-select-mouse (ev)
17125 "Return to `org-read-date' with the date currently selected.
17126 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17128 (mouse-set-point ev)
17129 (when (calendar-cursor-to-date)
17130 (let* ((date (calendar-cursor-to-date))
17131 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17132 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17133 (if (active-minibuffer-window) (exit-minibuffer))))
17135 (defun org-check-deadlines (ndays)
17136 "Check if there are any deadlines due or past due.
17137 A deadline is considered due if it happens within `org-deadline-warning-days'
17138 days from today's date. If the deadline appears in an entry marked DONE,
17139 it is not shown. The prefix arg NDAYS can be used to test that many
17140 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17142 (let* ((org-warn-days
17144 ((equal ndays '(4)) 100000)
17145 (ndays (prefix-numeric-value ndays))
17146 (t (abs org-deadline-warning-days))))
17147 (case-fold-search nil)
17148 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17150 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17152 (message "%d deadlines past-due or due within %d days"
17153 (org-occur regexp nil callback)
17156 (defsubst org-re-timestamp (type)
17157 "Return a regexp for timestamp TYPE.
17158 Allowed values for TYPE are:
17160 all: all timestamps
17161 active: only active timestamps (<...>)
17162 inactive: only inactive timestamps ([...])
17163 scheduled: only scheduled timestamps
17164 deadline: only deadline timestamps
17165 closed: only closed time-stamps
17167 When TYPE is nil, fall back on returning a regexp that matches
17168 both scheduled and deadline timestamps."
17169 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9>
\n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
17170 ((eq type 'active) org-ts-regexp)
17171 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^
\n>]*?\\)\\]")
17172 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
17173 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17174 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^
\n>]*?\\)\\]"))
17175 ((eq type 'scheduled-or-deadline)
17176 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
17178 (defun org-check-before-date (date)
17179 "Check if there are deadlines or scheduled entries before DATE."
17180 (interactive (list (org-read-date)))
17181 (let ((case-fold-search nil)
17182 (regexp (org-re-timestamp org-ts-type))
17184 (lambda () (time-less-p
17185 (org-time-string-to-time (match-string 1))
17186 (org-time-string-to-time date)))))
17187 (message "%d entries before %s"
17188 (org-occur regexp nil callback) date)))
17190 (defun org-check-after-date (date)
17191 "Check if there are deadlines or scheduled entries after DATE."
17192 (interactive (list (org-read-date)))
17193 (let ((case-fold-search nil)
17194 (regexp (org-re-timestamp org-ts-type))
17198 (org-time-string-to-time (match-string 1))
17199 (org-time-string-to-time date))))))
17200 (message "%d entries after %s"
17201 (org-occur regexp nil callback) date)))
17203 (defun org-check-dates-range (start-date end-date)
17204 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17205 (interactive (list (org-read-date nil nil nil "Range starts")
17206 (org-read-date nil nil nil "Range end")))
17207 (let ((case-fold-search nil)
17208 (regexp (org-re-timestamp org-ts-type))
17211 (let ((match (match-string 1)))
17214 (org-time-string-to-time match)
17215 (org-time-string-to-time start-date)))
17217 (org-time-string-to-time match)
17218 (org-time-string-to-time end-date)))))))
17219 (message "%d entries between %s and %s"
17220 (org-occur regexp nil callback) start-date end-date)))
17222 (defun org-evaluate-time-range (&optional to-buffer)
17223 "Evaluate a time range by computing the difference between start and end.
17224 Normally the result is just printed in the echo area, but with prefix arg
17225 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17226 If the time range is actually in a table, the result is inserted into the
17228 For time difference computation, a year is assumed to be exactly 365
17229 days in order to avoid rounding problems."
17232 (org-clock-update-time-maybe)
17234 (unless (org-at-date-range-p t)
17235 (goto-char (point-at-bol))
17236 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17237 (if (not (org-at-date-range-p t))
17238 (user-error "Not at a time-stamp range, and none found in current line")))
17239 (let* ((ts1 (match-string 1))
17240 (ts2 (match-string 2))
17241 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17242 (match-end (match-end 0))
17243 (time1 (org-time-string-to-time ts1))
17244 (time2 (org-time-string-to-time ts2))
17245 (t1 (org-float-time time1))
17246 (t2 (org-float-time time2))
17247 (diff (abs (- t2 t1)))
17248 (negative (< (- t2 t1) 0))
17249 ;; (ys (floor (* 365 24 60 60)))
17252 (fy "%dy %dd %02d:%02d")
17254 (fd "%dd %02d:%02d")
17259 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17261 d (floor (/ diff ds)) diff (mod diff ds)
17262 h (floor (/ diff hs)) diff (mod diff hs)
17263 m (floor (/ diff 60)))
17264 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17266 d (floor (+ (/ diff ds) 0.5))
17268 (if (not to-buffer)
17269 (message "%s" (org-make-tdiff-string y d h m))
17270 (if (org-at-table-p)
17272 (goto-char match-end)
17274 (and (looking-at " *|") (goto-char (match-end 0))))
17275 (goto-char match-end))
17277 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17278 (replace-match ""))
17279 (if negative (insert " -"))
17280 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17281 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17282 (insert " " (format fh h m))))
17283 (if align (org-table-align))
17284 (message "Time difference inserted")))))
17286 (defun org-make-tdiff-string (y d h m)
17289 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17291 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17293 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17295 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17297 (apply 'format fmt (nreverse l))))
17299 (defun org-time-string-to-time (s &optional buffer pos)
17300 "Convert a timestamp string into internal time."
17301 (condition-case errdata
17302 (apply 'encode-time (org-parse-time-string s))
17303 (error (error "Bad timestamp `%s'%s\nError was: %s"
17304 s (if (not (and buffer pos))
17306 (format " at %d in buffer `%s'" pos buffer))
17309 (defun org-time-string-to-seconds (s)
17310 "Convert a timestamp string to a number of seconds."
17311 (org-float-time (org-time-string-to-time s)))
17313 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17314 "Convert a time stamp to an absolute day number.
17315 If there is a specifier for a cyclic time stamp, get the closest
17317 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17318 The variable `date' is bound by the calendar when this is called."
17320 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17321 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17324 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17325 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17326 (time-to-days (current-time))) (match-string 0 s)
17329 (condition-case errdata
17330 (apply 'encode-time (org-parse-time-string s))
17331 (error (error "Bad timestamp `%s'%s\nError was: %s"
17332 s (if (not (and buffer pos))
17334 (format " at %d in buffer `%s'" pos buffer))
17335 (cdr errdata))))))))
17337 (defun org-days-to-iso-week (days)
17338 "Return the iso week number."
17340 (car (calendar-iso-from-absolute days)))
17342 (defun org-small-year-to-year (year)
17343 "Convert 2-digit years into 4-digit years.
17344 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17345 The year 2000 cannot be abbreviated. Any year larger than 99
17346 is returned unchanged."
17348 (setq year (+ 2000 year))
17350 (setq year (+ 1900 year))))
17353 (defun org-time-from-absolute (d)
17354 "Return the time corresponding to date D.
17355 D may be an absolute day number, or a calendar-type list (month day year)."
17356 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17357 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17359 (defun org-calendar-holiday ()
17360 "List of holidays, for Diary display in Org-mode."
17361 (require 'holidays)
17363 (if (fboundp 'calendar-check-holidays)
17364 'calendar-check-holidays 'check-calendar-holidays) date)))
17365 (if hl (mapconcat 'identity hl "; "))))
17367 (defun org-diary-sexp-entry (sexp entry date)
17368 "Process a SEXP diary ENTRY for DATE."
17369 (require 'diary-lib)
17370 (let ((result (if calendar-debug-sexp
17371 (let ((stack-trace-on-error t))
17372 (eval (car (read-from-string sexp))))
17373 (condition-case nil
17374 (eval (car (read-from-string sexp)))
17377 (message "Bad sexp at line %d in %s: %s"
17379 (buffer-file-name) sexp)
17381 (cond ((stringp result) (split-string result "; "))
17382 ((and (consp result)
17383 (not (consp (cdr result)))
17384 (stringp (cdr result))) (cdr result))
17385 ((and (consp result)
17386 (stringp (car result))) result)
17389 (defun org-diary-to-ical-string (frombuf)
17390 "Get iCalendar entries from diary entries in buffer FROMBUF.
17391 This uses the icalendar.el library."
17392 (let* ((tmpdir (if (featurep 'xemacs)
17394 temporary-file-directory))
17395 (tmpfile (make-temp-name
17396 (expand-file-name "orgics" tmpdir)))
17398 (with-current-buffer frombuf
17399 (icalendar-export-region (point-min) (point-max) tmpfile)
17400 (setq buf (find-buffer-visiting tmpfile))
17402 (goto-char (point-min))
17403 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17404 (setq b (match-beginning 0)))
17405 (goto-char (point-max))
17406 (if (re-search-backward "^END:VEVENT" nil t)
17407 (setq e (match-end 0)))
17408 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17410 (delete-file tmpfile)
17413 (defun org-closest-date (start current change prefer show-all)
17414 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17415 When PREFER is `past', return a date that is either CURRENT or past.
17416 When PREFER is `future', return a date that is either CURRENT or future.
17417 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17418 ;; Make the proper lists from the dates
17420 (let ((a1 '(("h" . hour)
17425 (shour (nth 2 (org-parse-time-string start)))
17426 dn dw sday cday n1 n2 n0
17427 d m y y1 y2 date1 date2 nmonths nm ny m2)
17429 (setq start (org-date-to-gregorian start)
17430 current (org-date-to-gregorian
17433 (time-to-days (current-time))))
17434 sday (calendar-absolute-from-gregorian start)
17435 cday (calendar-absolute-from-gregorian current))
17437 (if (<= cday sday) (throw 'exit sday))
17439 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17440 (setq dn (string-to-number (match-string 1 change))
17441 dw (cdr (assoc (match-string 2 change) a1)))
17442 (user-error "Invalid change specifier: %s" change))
17443 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17446 (let ((missing-hours
17447 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17449 (setq n1 (if (zerop missing-hours) cday
17450 (- cday (1+ (floor (/ missing-hours 24)))))
17451 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17453 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17456 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17457 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17458 (setq date1 (list m d y1)
17459 n1 (calendar-absolute-from-gregorian date1)
17460 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17461 n2 (calendar-absolute-from-gregorian date2)))
17463 ;; approx number of month between the two dates
17464 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17465 ;; How often does dn fit in there?
17466 (setq d (nth 1 start) m (car start) y (nth 2 start)
17467 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17469 ny (floor (/ m 12))
17472 (while (> m 12) (setq m (- m 12) y (1+ y)))
17473 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17474 (setq m2 (+ m dn) y2 y)
17475 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17476 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17477 (while (<= n2 cday)
17478 (setq n1 n2 m m2 y y2)
17479 (setq m2 (+ m dn) y2 y)
17480 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17481 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17482 ;; Make sure n1 is the earlier date
17483 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17486 ((eq prefer 'past) (if (= cday n2) n2 n1))
17487 ((eq prefer 'future) (if (= cday n1) n1 n2))
17488 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17490 ((eq prefer 'past) (if (= cday n2) n2 n1))
17491 ((eq prefer 'future) (if (= cday n1) n1 n2))
17492 (t (if (= cday n1) n1 n2)))))))
17494 (defun org-date-to-gregorian (date)
17495 "Turn any specification of DATE into a Gregorian date for the calendar."
17496 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17497 ((and (listp date) (= (length date) 3)) date)
17499 (setq date (org-parse-time-string date))
17500 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17502 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17504 (defun org-parse-time-string (s &optional nodefault)
17505 "Parse the standard Org-mode time string.
17506 This should be a lot faster than the normal `parse-time-string'.
17507 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17508 hour and minute fields will be nil if not given."
17509 (cond ((string-match org-ts-regexp0 s)
17511 (if (or (match-beginning 8) (not nodefault))
17512 (string-to-number (or (match-string 8 s) "0")))
17513 (if (or (match-beginning 7) (not nodefault))
17514 (string-to-number (or (match-string 7 s) "0")))
17515 (string-to-number (match-string 4 s))
17516 (string-to-number (match-string 3 s))
17517 (string-to-number (match-string 2 s))
17519 ((string-match "^<[^>]+>$" s)
17520 (decode-time (seconds-to-time (org-matcher-time s))))
17521 (t (error "Not a standard Org-mode time string: %s" s))))
17523 (defun org-timestamp-up (&optional arg)
17524 "Increase the date item at the cursor by one.
17525 If the cursor is on the year, change the year. If it is on the month,
17526 the day or the time, change that.
17527 With prefix ARG, change by that many units."
17529 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17531 (defun org-timestamp-down (&optional arg)
17532 "Decrease the date item at the cursor by one.
17533 If the cursor is on the year, change the year. If it is on the month,
17534 the day or the time, change that.
17535 With prefix ARG, change by that many units."
17537 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17539 (defun org-timestamp-up-day (&optional arg)
17540 "Increase the date in the time stamp by one day.
17541 With prefix ARG, change that many days."
17543 (if (and (not (org-at-timestamp-p t))
17544 (org-at-heading-p))
17546 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17548 (defun org-timestamp-down-day (&optional arg)
17549 "Decrease the date in the time stamp by one day.
17550 With prefix ARG, change that many days."
17552 (if (and (not (org-at-timestamp-p t))
17553 (org-at-heading-p))
17555 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17557 (defun org-at-timestamp-p (&optional inactive-ok)
17558 "Determine if the cursor is in or at a timestamp."
17560 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17562 (ans (or (looking-at tsr)
17564 (skip-chars-backward "^[<\n\r\t")
17565 (if (> (point) (point-min)) (backward-char 1))
17566 (and (looking-at tsr)
17567 (> (- (match-end 0) pos) -1))))))
17569 (boundp 'org-ts-what)
17572 ((= pos (match-beginning 0)) 'bracket)
17573 ;; Point is considered to be "on the bracket" whether
17574 ;; it's really on it or right after it.
17575 ((= pos (1- (match-end 0))) 'bracket)
17576 ((= pos (match-end 0)) 'after)
17577 ((org-pos-in-match-range pos 2) 'year)
17578 ((org-pos-in-match-range pos 3) 'month)
17579 ((org-pos-in-match-range pos 7) 'hour)
17580 ((org-pos-in-match-range pos 8) 'minute)
17581 ((or (org-pos-in-match-range pos 4)
17582 (org-pos-in-match-range pos 5)) 'day)
17583 ((and (> pos (or (match-end 8) (match-end 5)))
17584 (< pos (match-end 0)))
17585 (- pos (or (match-end 8) (match-end 5))))
17589 (defun org-toggle-timestamp-type ()
17590 "Toggle the type (<active> or [inactive]) of a time stamp."
17592 (when (org-at-timestamp-p t)
17593 (let ((beg (match-beginning 0)) (end (match-end 0))
17594 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17597 (while (re-search-forward "[][<>]" end t)
17598 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17600 (message "Timestamp is now %sactive"
17601 (if (equal (char-after beg) ?<) "" "in")))))
17603 (defun org-at-clock-log-p nil
17604 "Is the cursor on the clock log line?"
17606 (move-beginning-of-line 1)
17607 (looking-at org-clock-line-re)))
17609 (defvar org-clock-history) ; defined in org-clock.el
17610 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17611 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17612 "Change the date in the time stamp at point.
17613 The date will be changed by N times WHAT. WHAT can be `day', `month',
17614 `year', `minute', `second'. If WHAT is not given, the cursor position
17615 in the timestamp determines what will be changed.
17616 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17617 (let ((origin (point)) origin-cat
17619 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17622 ts time time0 fixnext clrgx)
17623 (if (not (org-at-timestamp-p t))
17624 (user-error "Not at a timestamp"))
17625 (if (and (not what) (eq org-ts-what 'bracket))
17626 (org-toggle-timestamp-type)
17627 ;; Point isn't on brackets. Remember the part of the time-stamp
17628 ;; the point was in. Indeed, size of time-stamps may change,
17629 ;; but point must be kept in the same category nonetheless.
17630 (setq origin-cat org-ts-what)
17631 (if (and (not what) (not (eq org-ts-what 'day))
17632 org-display-custom-times
17633 (get-text-property (point) 'display)
17634 (not (get-text-property (1- (point)) 'display)))
17635 (setq org-ts-what 'day))
17636 (setq org-ts-what (or what org-ts-what)
17637 inactive (= (char-after (match-beginning 0)) ?\[)
17638 ts (match-string 0))
17640 (when (string-match
17641 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17643 (setq extra (match-string 1 ts))
17644 (if suppress-tmp-delay
17645 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17646 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17648 (setq time0 (org-parse-time-string ts))
17650 (eq org-ts-what 'minute)
17651 (not current-prefix-arg))
17652 ;; This looks like s-up and s-down. Change by one rounding step.
17653 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17654 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17655 (setcar (cdr time0) (+ (nth 1 time0)
17656 (if (> n 0) (- rem) (- dm rem))))))
17658 (encode-time (or (car time0) 0)
17659 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17660 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17661 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17662 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17663 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17665 (when (and (member org-ts-what '(hour minute))
17667 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17668 (setq extra (org-modify-ts-extra
17670 (if (eq org-ts-what 'hour) 2 5)
17672 (when (integerp org-ts-what)
17673 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17674 (if (eq what 'calendar)
17675 (let ((cal-date (org-get-date-from-calendar)))
17676 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17677 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17678 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17679 (setcar time0 (or (car time0) 0))
17680 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17681 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17682 (setq time (apply 'encode-time time0))))
17683 ;; Insert the new time-stamp, and ensure point stays in the same
17684 ;; category as before (i.e. not after the last position in that
17686 (let ((pos (point)))
17687 ;; Stay before inserted string. `save-excursion' is of no use.
17688 (setq org-last-changed-timestamp
17689 (org-insert-time-stamp time with-hm inactive nil nil extra))
17692 (looking-at org-ts-regexp3)
17694 ;; `day' category ends before `hour' if any, or at
17695 ;; the end of the day name.
17696 ((eq origin-cat 'day)
17697 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17698 ((eq origin-cat 'hour) (min (match-end 7) origin))
17699 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17700 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17701 ;; `year' and `month' have both fixed size: point
17702 ;; couldn't have moved into another part.
17704 ;; Update clock if on a CLOCK line.
17705 (org-clock-update-time-maybe)
17706 ;; Maybe adjust the closest clock in `org-clock-history'
17707 (when org-clock-adjust-closest
17708 (if (not (and (org-at-clock-log-p)
17709 (< 1 (length (delq nil (mapcar 'marker-position
17710 org-clock-history))))))
17711 (message "No clock to adjust")
17712 (cond ((save-excursion ; fix previous clock?
17713 (re-search-backward org-ts-regexp0 nil t)
17714 (org-looking-back (concat org-clock-string " \\[")))
17715 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17716 ((save-excursion ; fix next clock?
17717 (re-search-backward org-ts-regexp0 nil t)
17718 (looking-at (concat org-ts-regexp0 "\\] =>")))
17719 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17720 (save-window-excursion
17721 ;; Find closest clock to point, adjust the previous/next one in history
17722 (let* ((p (save-excursion (org-back-to-heading t)))
17723 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17725 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17726 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17728 (message "No clock to adjust")
17730 (org-goto-marker-or-bmk clfixpos)
17732 (when (re-search-forward clrgx nil t)
17733 (goto-char (match-beginning 1))
17734 (let (org-clock-adjust-closest)
17735 (org-timestamp-change n org-ts-what updown))
17736 (message "Clock adjusted in %s for heading: %s"
17737 (file-name-nondirectory (buffer-file-name))
17738 (org-get-heading t t)))))))))
17739 ;; Try to recenter the calendar window, if any.
17740 (if (and org-calendar-follow-timestamp-change
17741 (get-buffer-window "*Calendar*" t)
17742 (memq org-ts-what '(day month year)))
17743 (org-recenter-calendar (time-to-days time))))))
17745 (defun org-modify-ts-extra (s pos n dm)
17746 "Change the different parts of the lead-time and repeat fields in timestamp."
17747 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17749 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17751 ((or (org-pos-in-match-range pos 2)
17752 (org-pos-in-match-range pos 3))
17753 (setq m (string-to-number (match-string 3 s))
17754 h (string-to-number (match-string 2 s)))
17755 (if (org-pos-in-match-range pos 2)
17757 (setq n (* dm (org-no-warnings (signum n))))
17758 (when (not (= 0 (setq rem (% m dm))))
17759 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17761 (if (< m 0) (setq m (+ m 60) h (1- h)))
17762 (if (> m 59) (setq m (- m 60) h (1+ h)))
17763 (setq h (min 24 (max 0 h)))
17764 (setq ng 1 new (format "-%02d:%02d" h m)))
17765 ((org-pos-in-match-range pos 6)
17766 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17767 ((org-pos-in-match-range pos 5)
17768 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17770 ((org-pos-in-match-range pos 9)
17771 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17772 ((org-pos-in-match-range pos 8)
17773 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17777 (substring s 0 (match-beginning ng))
17779 (substring s (match-end ng))))))
17782 (defun org-recenter-calendar (date)
17783 "If the calendar is visible, recenter it to DATE."
17784 (let ((cwin (get-buffer-window "*Calendar*" t)))
17786 (let ((calendar-move-hook nil))
17787 (with-selected-window cwin
17788 (calendar-goto-date (if (listp date) date
17789 (calendar-gregorian-from-absolute date))))))))
17791 (defun org-goto-calendar (&optional arg)
17792 "Go to the Emacs calendar at the current date.
17793 If there is a time stamp in the current line, go to that date.
17794 A prefix ARG can be used to force the current date."
17796 (let ((tsr org-ts-regexp) diff
17797 (calendar-move-hook nil)
17798 (calendar-view-holidays-initially-flag nil)
17799 (calendar-view-diary-initially-flag nil))
17800 (if (or (org-at-timestamp-p)
17802 (beginning-of-line 1)
17803 (looking-at (concat ".*" tsr))))
17804 (let ((d1 (time-to-days (current-time)))
17806 (org-time-string-to-time (match-string 1)))))
17807 (setq diff (- d2 d1))))
17809 (calendar-goto-today)
17810 (if (and diff (not arg)) (calendar-forward-day diff))))
17812 (defun org-get-date-from-calendar ()
17813 "Return a list (month day year) of date at point in calendar."
17814 (with-current-buffer "*Calendar*"
17816 (calendar-cursor-to-date))))
17818 (defun org-date-from-calendar ()
17819 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17820 If there is already a time stamp at the cursor position, update it."
17822 (if (org-at-timestamp-p t)
17823 (org-timestamp-change 0 'calendar)
17824 (let ((cal-date (org-get-date-from-calendar)))
17825 (org-insert-time-stamp
17826 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17828 (defcustom org-effort-durations
17831 ("w" . ,(* 60 8 5))
17832 ("m" . ,(* 60 8 5 4))
17833 ("y" . ,(* 60 8 5 40)))
17834 "Conversion factor to minutes for an effort modifier.
17836 Each entry has the form (MODIFIER . MINUTES).
17838 In an effort string, a number followed by MODIFIER is multiplied
17839 by the specified number of MINUTES to obtain an effort in
17842 For example, if the value of this variable is ((\"hours\" . 60)), then an
17843 effort string \"2hours\" is equivalent to 120 minutes."
17846 :type '(alist :key-type (string :tag "Modifier")
17847 :value-type (number :tag "Minutes")))
17849 (defun org-minutes-to-clocksum-string (m)
17850 "Format number of minutes as a clocksum string.
17851 The format is determined by `org-time-clocksum-format',
17852 `org-time-clocksum-use-fractional' and
17853 `org-time-clocksum-fractional-format' and
17854 `org-time-clocksum-use-effort-durations'."
17855 (let ((clocksum "")
17856 (m (round m)) ; Don't allow fractions of minutes
17858 (setq h (if org-time-clocksum-use-effort-durations
17859 (cdr (assoc "h" org-effort-durations)) 60)
17860 d (if org-time-clocksum-use-effort-durations
17861 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17862 w (if org-time-clocksum-use-effort-durations
17863 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17864 mo (if org-time-clocksum-use-effort-durations
17865 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17866 y (if org-time-clocksum-use-effort-durations
17867 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17868 ;; fractional format
17869 (if org-time-clocksum-use-fractional
17871 ;; single format string
17872 ((stringp org-time-clocksum-fractional-format)
17873 (format org-time-clocksum-fractional-format (/ m (float h))))
17874 ;; choice of fractional formats for different time units
17875 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17876 (> (/ (truncate m) (* y d h)) 0))
17877 (format fmt (/ m (* y d (float h)))))
17878 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17879 (> (/ (truncate m) (* mo d h)) 0))
17880 (format fmt (/ m (* mo d (float h)))))
17881 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17882 (> (/ (truncate m) (* w d h)) 0))
17883 (format fmt (/ m (* w d (float h)))))
17884 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17885 (> (/ (truncate m) (* d h)) 0))
17886 (format fmt (/ m (* d (float h)))))
17887 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17888 (> (/ (truncate m) h) 0))
17889 (format fmt (/ m (float h))))
17890 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17892 ;; fall back to smallest time unit with a format
17893 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17894 (format fmt (/ m (float h))))
17895 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17896 (format fmt (/ m (* d (float h)))))
17897 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17898 (format fmt (/ m (* w d (float h)))))
17899 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17900 (format fmt (/ m (* mo d (float h)))))
17901 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17902 (format fmt (/ m (* y d (float h))))))
17903 ;; standard (non-fractional) format, with single format string
17904 (if (stringp org-time-clocksum-format)
17905 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17906 ;; separate formats components
17907 (and (setq fmt (plist-get org-time-clocksum-format :years))
17908 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17909 (plist-get org-time-clocksum-format :require-years))
17910 (setq clocksum (concat clocksum (format fmt n))
17911 m (- m (* n y d h))))
17912 (and (setq fmt (plist-get org-time-clocksum-format :months))
17913 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17914 (plist-get org-time-clocksum-format :require-months))
17915 (setq clocksum (concat clocksum (format fmt n))
17916 m (- m (* n mo d h))))
17917 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17918 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17919 (plist-get org-time-clocksum-format :require-weeks))
17920 (setq clocksum (concat clocksum (format fmt n))
17921 m (- m (* n w d h))))
17922 (and (setq fmt (plist-get org-time-clocksum-format :days))
17923 (or (> (setq n (/ (truncate m) (* d h))) 0)
17924 (plist-get org-time-clocksum-format :require-days))
17925 (setq clocksum (concat clocksum (format fmt n))
17926 m (- m (* n d h))))
17927 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17928 (or (> (setq n (/ (truncate m) h)) 0)
17929 (plist-get org-time-clocksum-format :require-hours))
17930 (setq clocksum (concat clocksum (format fmt n))
17932 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17933 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17934 (setq clocksum (concat clocksum (format fmt m))))
17935 ;; return formatted time duration
17938 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17939 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17940 "Org mode version 8.0")
17942 (defun org-hours-to-clocksum-string (n)
17943 (org-minutes-to-clocksum-string (* n 60)))
17945 (defun org-hh:mm-string-to-minutes (s)
17946 "Convert a string H:MM to a number of minutes.
17947 If the string is just a number, interpret it as minutes.
17948 In fact, the first hh:mm or number in the string will be taken,
17949 there can be extra stuff in the string.
17950 If no number is found, the return value is 0."
17953 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17954 (+ (* (string-to-number (match-string 1 s)) 60)
17955 (string-to-number (match-string 2 s))))
17956 ((string-match "\\([0-9]+\\)" s)
17957 (string-to-number (match-string 1 s)))
17960 (defcustom org-image-actual-width t
17961 "Should we use the actual width of images when inlining them?
17963 When set to `t', always use the image width.
17965 When set to a number, use imagemagick (when available) to set
17966 the image's width to this value.
17968 When set to a number in a list, try to get the width from any
17969 #+ATTR.* keyword if it matches a width specification like
17971 #+ATTR_HTML: :width 300px
17973 and fall back on that number if none is found.
17975 When set to nil, try to get the width from an #+ATTR.* keyword
17976 and fall back on the original width if none is found.
17978 This requires Emacs >= 24.1, build with imagemagick support."
17979 :group 'org-appearance
17981 :package-version '(Org . "8.0")
17983 (const :tag "Use the image width" t)
17984 (integer :tag "Use a number of pixels")
17985 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17986 (const :tag "Use #+ATTR* or don't resize" nil)))
17988 (defcustom org-agenda-inhibit-startup nil
17989 "Inhibit startup when preparing agenda buffers.
17990 When this variable is `t', the initialization of the Org agenda
17991 buffers is inhibited: e.g. the visibility state is not set, the
17992 tables are not re-aligned, etc."
17995 :group 'org-agenda)
17997 (define-obsolete-variable-alias
17998 'org-agenda-ignore-drawer-properties
17999 'org-agenda-ignore-properties "24.5")
18001 (defcustom org-agenda-ignore-properties nil
18002 "Avoid updating text properties when building the agenda.
18003 Properties are used to prepare buffers for effort estimates,
18004 appointments, statistics and subtree-local categories.
18005 If you don't use these in the agenda, you can add them to this
18006 list and agenda building will be a bit faster.
18007 The value is a list, with zero or more of the symbols `effort', `appt',
18008 `stats' or `category'."
18009 :type '(set :greedy t
18015 :package-version '(Org . "8.3")
18016 :group 'org-agenda)
18018 (defun org-duration-string-to-minutes (s &optional output-to-string)
18019 "Convert a duration string S to minutes.
18021 A bare number is interpreted as minutes, modifiers can be set by
18022 customizing `org-effort-durations' (which see).
18024 Entries containing a colon are interpreted as H:MM by
18025 `org-hh:mm-string-to-minutes'."
18027 (re (concat "\\([0-9.]+\\) *\\("
18028 (regexp-opt (mapcar 'car org-effort-durations))
18030 (while (string-match re s)
18031 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18032 (string-to-number (match-string 1 s))))
18033 (setq s (replace-match "" nil t s)))
18034 (setq result (floor result))
18035 (incf result (org-hh:mm-string-to-minutes s))
18036 (if output-to-string (number-to-string result) result)))
18040 (defun org-save-all-org-buffers ()
18041 "Save all Org-mode buffers without user confirmation."
18043 (message "Saving all Org-mode buffers...")
18044 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18045 (when (featurep 'org-id) (org-id-locations-save))
18046 (message "Saving all Org-mode buffers... done"))
18048 (defun org-revert-all-org-buffers ()
18049 "Revert all Org-mode buffers.
18050 Prompt for confirmation when there are unsaved changes.
18051 Be sure you know what you are doing before letting this function
18052 overwrite your changes.
18054 This function is useful in a setup where one tracks org files
18055 with a version control system, to revert on one machine after pulling
18056 changes from another. I believe the procedure must be like this:
18058 1. M-x org-save-all-org-buffers
18059 2. Pull changes from the other machine, resolve conflicts
18060 3. M-x org-revert-all-org-buffers"
18062 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18063 (user-error "Abort"))
18065 (save-window-excursion
18068 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18069 (with-current-buffer b buffer-file-name))
18070 (org-pop-to-buffer-same-window b)
18071 (revert-buffer t 'no-confirm)))
18073 (when (and (featurep 'org-id) org-id-track-globally)
18074 (org-id-locations-load)))))
18079 (defun org-switchb (&optional arg)
18080 "Switch between Org buffers.
18081 With one prefix argument, restrict available buffers to files.
18082 With two prefix arguments, restrict available buffers to agenda files.
18084 Defaults to `iswitchb' for buffer name completion.
18085 Set `org-completion-use-ido' to make it use ido instead."
18087 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18088 ((equal arg '(16)) (org-buffer-list 'agenda))
18089 (t (org-buffer-list))))
18090 (org-completion-use-iswitchb org-completion-use-iswitchb)
18091 (org-completion-use-ido org-completion-use-ido))
18092 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18093 (setq org-completion-use-iswitchb t))
18094 (org-pop-to-buffer-same-window
18095 (org-icompleting-read "Org buffer: "
18096 (mapcar 'list (mapcar 'buffer-name blist))
18099 ;;; Define some older names previously used for this functionality
18101 (defalias 'org-ido-switchb 'org-switchb)
18103 (defalias 'org-iswitchb 'org-switchb)
18105 (defun org-buffer-list (&optional predicate exclude-tmp)
18106 "Return a list of Org buffers.
18107 PREDICATE can be `export', `files' or `agenda'.
18109 export restrict the list to Export buffers.
18110 files restrict the list to buffers visiting Org files.
18111 agenda restrict the list to buffers visiting agenda files.
18113 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18115 (agenda-files (and (eq predicate 'agenda)
18116 (mapcar 'file-truename (org-agenda-files t))))
18119 ((eq predicate 'files)
18120 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18121 ((eq predicate 'export)
18122 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
18123 ((eq predicate 'agenda)
18125 (with-current-buffer b
18126 (and (derived-mode-p 'org-mode)
18127 (setq bfn (buffer-file-name b))
18128 (member (file-truename bfn) agenda-files)))))
18129 (t (lambda (b) (with-current-buffer b
18130 (or (derived-mode-p 'org-mode)
18131 (string-match "\*Org .*Export"
18132 (buffer-name b)))))))))
18136 (if (and (funcall filter b)
18137 (or (not exclude-tmp)
18138 (not (string-match "tmp" (buffer-name b)))))
18143 (defun org-agenda-files (&optional unrestricted archives)
18144 "Get the list of agenda files.
18145 Optional UNRESTRICTED means return the full list even if a restriction
18146 is currently in place.
18147 When ARCHIVES is t, include all archive files that are really being
18148 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18149 `org-agenda-archives-mode' is t."
18152 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18153 ((stringp org-agenda-files) (org-read-agenda-file-list))
18154 ((listp org-agenda-files) org-agenda-files)
18155 (t (error "Invalid value of `org-agenda-files'")))))
18156 (setq files (apply 'append
18157 (mapcar (lambda (f)
18158 (if (file-directory-p f)
18160 f t org-agenda-file-regexp)
18163 (when org-agenda-skip-unavailable-files
18164 (setq files (delq nil
18167 (and (file-readable-p file) file)))
18169 (when (or (eq archives t)
18170 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18171 (setq files (org-add-archive-files files)))
18174 (defun org-agenda-file-p (&optional file)
18175 "Return non-nil, if FILE is an agenda file.
18176 If FILE is omitted, use the file associated with the current
18178 (member (or file (buffer-file-name))
18179 (org-agenda-files t)))
18181 (defun org-edit-agenda-file-list ()
18182 "Edit the list of agenda files.
18183 Depending on setup, this either uses customize to edit the variable
18184 `org-agenda-files', or it visits the file that is holding the list. In the
18185 latter case, the buffer is set up in a way that saving it automatically kills
18186 the buffer and restores the previous window configuration."
18188 (if (stringp org-agenda-files)
18189 (let ((cw (current-window-configuration)))
18190 (find-file org-agenda-files)
18191 (org-set-local 'org-window-configuration cw)
18192 (org-add-hook 'after-save-hook
18194 (set-window-configuration
18195 (prog1 org-window-configuration
18196 (kill-buffer (current-buffer))))
18197 (org-install-agenda-files-menu)
18198 (message "New agenda file list installed"))
18200 (message "%s" (substitute-command-keys
18201 "Edit list and finish with \\[save-buffer]")))
18202 (customize-variable 'org-agenda-files)))
18204 (defun org-store-new-agenda-file-list (list)
18205 "Set new value for the agenda file list and save it correctly."
18206 (if (stringp org-agenda-files)
18207 (let ((fe (org-read-agenda-file-list t)) b u)
18208 (while (setq b (find-buffer-visiting org-agenda-files))
18210 (with-temp-file org-agenda-files
18213 (lambda (f) ;; Keep un-expanded entries.
18214 (if (setq u (assoc f fe))
18219 (let ((org-mode-hook nil) (org-inhibit-startup t)
18220 (org-insert-mode-line-in-empty-file nil))
18221 (setq org-agenda-files list)
18222 (customize-save-variable 'org-agenda-files org-agenda-files))))
18224 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18225 "Read the list of agenda files from a file.
18226 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18227 filenames, used by `org-store-new-agenda-file-list' to write back
18228 un-expanded file names."
18229 (when (file-directory-p org-agenda-files)
18230 (error "`org-agenda-files' cannot be a single directory"))
18231 (when (stringp org-agenda-files)
18233 (insert-file-contents org-agenda-files)
18236 (let ((e (expand-file-name (substitute-in-file-name f)
18238 (if pair-with-expansion
18241 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18244 (defun org-cycle-agenda-files ()
18245 "Cycle through the files in `org-agenda-files'.
18246 If the current buffer visits an agenda file, find the next one in the list.
18247 If the current buffer does not, find the first agenda file."
18249 (let* ((fs (org-agenda-files t))
18250 (files (append fs (list (car fs))))
18251 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18253 (unless files (user-error "No agenda files"))
18255 (while (setq file (pop files))
18256 (if (equal (file-truename file) tcf)
18258 (find-file (car files))
18260 (find-file (car fs)))
18261 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18263 (defun org-agenda-file-to-front (&optional to-end)
18264 "Move/add the current file to the top of the agenda file list.
18265 If the file is not present in the list, it is added to the front. If it is
18266 present, it is moved there. With optional argument TO-END, add/move to the
18269 (let ((org-agenda-skip-unavailable-files nil)
18270 (file-alist (mapcar (lambda (x)
18271 (cons (file-truename x) x))
18272 (org-agenda-files t)))
18273 (ctf (file-truename
18274 (or buffer-file-name
18275 (user-error "Please save the current buffer to a file"))))
18277 (setq x (assoc ctf file-alist) had x)
18279 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18281 (setq file-alist (append (delq x file-alist) (list x)))
18282 (setq file-alist (cons x (delq x file-alist))))
18283 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18284 (org-install-agenda-files-menu)
18285 (message "File %s to %s of agenda file list"
18286 (if had "moved" "added") (if to-end "end" "front"))))
18288 (defun org-remove-file (&optional file)
18289 "Remove current file from the list of files in variable `org-agenda-files'.
18290 These are the files which are being checked for agenda entries.
18291 Optional argument FILE means use this file instead of the current."
18293 (let* ((org-agenda-skip-unavailable-files nil)
18294 (file (or file buffer-file-name
18295 (user-error "Current buffer does not visit a file")))
18296 (true-file (file-truename file))
18297 (afile (abbreviate-file-name file))
18298 (files (delq nil (mapcar
18300 (if (equal true-file
18303 (org-agenda-files t)))))
18304 (if (not (= (length files) (length (org-agenda-files t))))
18306 (org-store-new-agenda-file-list files)
18307 (org-install-agenda-files-menu)
18308 (message "Removed file: %s" afile))
18309 (message "File was not in list: %s (not removed)" afile))))
18311 (defun org-file-menu-entry (file)
18312 (vector file (list 'find-file file) t))
18314 (defun org-check-agenda-file (file)
18315 "Make sure FILE exists. If not, ask user what to do."
18316 (when (not (file-exists-p file))
18317 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18318 (abbreviate-file-name file))
18319 (let ((r (downcase (read-char-exclusive))))
18322 (org-remove-file file)
18323 (throw 'nextfile t))
18324 (t (user-error "Abort"))))))
18326 (defun org-get-agenda-file-buffer (file)
18327 "Get an agenda buffer visiting FILE.
18328 If the buffer needs to be created, add it to the list of buffers
18329 which might be released later."
18330 (let ((buf (org-find-base-buffer-visiting file)))
18332 buf ; just return it
18333 ;; Make a new buffer and remember it
18334 (setq buf (find-file-noselect file))
18335 (if buf (push buf org-agenda-new-buffers))
18338 (defun org-release-buffers (blist)
18339 "Release all buffers in list, asking the user for confirmation when needed.
18340 When a buffer is unmodified, it is just killed. When modified, it is saved
18341 \(if the user agrees) and then killed."
18343 (while (setq buf (pop blist))
18344 (setq file (buffer-file-name buf))
18345 (when (and (buffer-modified-p buf)
18347 (y-or-n-p (format "Save file %s? " file)))
18348 (with-current-buffer buf (save-buffer)))
18349 (kill-buffer buf))))
18351 (defun org-agenda-prepare-buffers (files)
18352 "Create buffers for all agenda files, protect archived trees and comments."
18354 (let ((pa '(:org-archived t))
18355 (pc '(:org-comment t))
18356 (pall '(:org-archived t :org-comment t))
18357 (inhibit-read-only t)
18358 (org-inhibit-startup org-agenda-inhibit-startup)
18359 (rea (concat ":" org-archive-tag ":"))
18361 (setq org-tag-alist-for-agenda nil
18362 org-tag-groups-alist-for-agenda nil)
18365 (while (setq file (pop files))
18369 (org-check-agenda-file file)
18370 (set-buffer (org-get-agenda-file-buffer file)))
18372 (org-set-regexps-and-options-for-tags)
18374 (goto-char (point-min))
18375 (let ((case-fold-search t))
18376 (when (search-forward "#+setupfile" nil t)
18377 ;; Don't set all regexps and options systematically as
18378 ;; this is only run for setting agenda tags from setup
18380 (org-set-regexps-and-options)))
18381 (or (memq 'category org-agenda-ignore-properties)
18382 (org-refresh-category-properties))
18383 (or (memq 'stats org-agenda-ignore-properties)
18384 (org-refresh-stats-properties))
18385 (or (memq 'effort org-agenda-ignore-properties)
18386 (org-refresh-effort-properties))
18387 (or (memq 'appt org-agenda-ignore-properties)
18388 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18389 (setq org-todo-keywords-for-agenda
18390 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18391 (setq org-done-keywords-for-agenda
18392 (append org-done-keywords-for-agenda org-done-keywords))
18393 (setq org-todo-keyword-alist-for-agenda
18394 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18395 (setq org-tag-alist-for-agenda
18397 (append org-tag-alist-for-agenda
18399 org-tag-persistent-alist)))
18401 (setq org-tag-groups-alist-for-agenda
18402 (org-uniquify-alist
18403 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18404 (org-with-silent-modifications
18406 (remove-text-properties (point-min) (point-max) pall)
18407 (when org-agenda-skip-archived-trees
18408 (goto-char (point-min))
18409 (while (re-search-forward rea nil t)
18410 (if (org-at-heading-p t)
18411 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18412 (goto-char (point-min))
18413 (setq re (format "^\\* .*\\<%s\\>" org-comment-string))
18414 (while (re-search-forward re nil t)
18415 (when (save-match-data (org-in-commented-heading-p t))
18416 (add-text-properties
18417 (match-beginning 0) (org-end-of-subtree t) pc)))))
18418 (goto-char pos)))))
18419 (setq org-todo-keywords-for-agenda
18420 (org-uniquify org-todo-keywords-for-agenda))
18421 (setq org-todo-keyword-alist-for-agenda
18422 (org-uniquify org-todo-keyword-alist-for-agenda))))
18425 ;;;; CDLaTeX minor mode
18427 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18428 "Keymap for the minor `org-cdlatex-mode'.")
18430 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18431 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18432 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18433 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18434 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18436 (defvar org-cdlatex-texmathp-advice-is-done nil
18437 "Flag remembering if we have applied the advice to texmathp already.")
18439 (define-minor-mode org-cdlatex-mode
18440 "Toggle the minor `org-cdlatex-mode'.
18441 This mode supports entering LaTeX environment and math in LaTeX fragments
18443 \\{org-cdlatex-mode-map}"
18445 (when org-cdlatex-mode
18447 (run-hooks 'cdlatex-mode-hook)
18448 (cdlatex-compute-tables))
18449 (unless org-cdlatex-texmathp-advice-is-done
18450 (setq org-cdlatex-texmathp-advice-is-done t)
18451 (defadvice texmathp (around org-math-always-on activate)
18452 "Always return t in org-mode buffers.
18453 This is because we want to insert math symbols without dollars even outside
18454 the LaTeX math segments. If Orgmode thinks that point is actually inside
18455 an embedded LaTeX fragment, let texmathp do its job.
18456 \\[org-cdlatex-mode-map]"
18460 ((not (derived-mode-p 'org-mode)) ad-do-it)
18461 ((eq this-command 'cdlatex-math-symbol)
18462 (setq ad-return-value t
18463 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18465 (let ((p (org-inside-LaTeX-fragment-p)))
18466 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18467 (setq ad-return-value t
18468 texmathp-why '("Org-mode embedded math" . 0))
18469 (if p ad-do-it)))))))))
18471 (defun turn-on-org-cdlatex ()
18472 "Unconditionally turn on `org-cdlatex-mode'."
18473 (org-cdlatex-mode 1))
18475 (defun org-try-cdlatex-tab ()
18476 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18477 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18478 - inside a LaTeX fragment, or
18479 - after the first word in a line, where an abbreviation expansion could
18480 insert a LaTeX environment."
18481 (when org-cdlatex-mode
18483 ;; Before any word on the line: No expansion possible.
18484 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18485 ;; Just after first word on the line: Expand it. Make sure it
18486 ;; cannot happen on headlines, though.
18488 (skip-chars-backward "a-zA-Z0-9*")
18489 (skip-chars-backward " \t")
18490 (and (bolp) (not (org-at-heading-p))))
18492 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18494 (defun org-cdlatex-underscore-caret (&optional arg)
18495 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18496 Revert to the normal definition outside of these fragments."
18498 (if (org-inside-LaTeX-fragment-p)
18499 (call-interactively 'cdlatex-sub-superscript)
18500 (let (org-cdlatex-mode)
18501 (call-interactively (key-binding (vector last-input-event))))))
18503 (defun org-cdlatex-math-modify (&optional arg)
18504 "Execute `cdlatex-math-modify' in LaTeX fragments.
18505 Revert to the normal definition outside of these fragments."
18507 (if (org-inside-LaTeX-fragment-p)
18508 (call-interactively 'cdlatex-math-modify)
18509 (let (org-cdlatex-mode)
18510 (call-interactively (key-binding (vector last-input-event))))))
18512 (defun org-cdlatex-environment-indent (&optional environment item)
18513 "Execute `cdlatex-environment' and indent the inserted environment."
18515 (cdlatex-environment environment item)
18516 (let ((element (org-element-at-point)))
18517 (org-indent-region (org-element-property :begin element)
18518 (org-element-property :end element))))
18521 ;;;; LaTeX fragments
18523 (defun org-inside-LaTeX-fragment-p ()
18524 "Test if point is inside a LaTeX fragment.
18525 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18526 sequence appearing also before point.
18527 Even though the matchers for math are configurable, this function assumes
18528 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18529 delimiters are skipped when they have been removed by customization.
18530 The return value is nil, or a cons cell with the delimiter and the
18531 position of this delimiter.
18533 This function does a reasonably good job, but can locally be fooled by
18534 for example currency specifications. For example it will assume being in
18535 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18536 fragments that are properly closed, but during editing, we have to live
18537 with the uncertainty caused by missing closing delimiters. This function
18538 looks only before point, not after."
18540 (let ((pos (point))
18541 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18543 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18545 dd-on str (start 0) m re)
18548 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18549 re (nth 1 (assoc "$" org-latex-regexps)))
18550 (while (string-match re str start)
18552 ((= (match-end 0) (length str))
18553 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18554 ((= (match-end 0) (- (length str) 5))
18556 (t (setq start (match-end 0))))))
18557 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18559 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18560 (and (match-beginning 2) (throw 'exit nil))
18562 (while (re-search-backward "\\$\\$" lim t)
18563 (setq dd-on (not dd-on)))
18565 (if dd-on (cons "$$" m))))))
18567 (defun org-inside-latex-macro-p ()
18568 "Is point inside a LaTeX macro or its arguments?"
18571 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18573 (defvar org-latex-fragment-image-overlays nil
18574 "List of overlays carrying the images of latex fragments.")
18575 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18577 (defun org-remove-latex-fragment-image-overlays ()
18578 "Remove all overlays with LaTeX fragment images in current buffer."
18579 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18580 (setq org-latex-fragment-image-overlays nil))
18582 (define-obsolete-function-alias
18583 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
18584 (defun org-toggle-latex-fragment (&optional subtree)
18585 "Preview the LaTeX fragment at point, or all locally or globally.
18586 If the cursor is in a LaTeX fragment, create the image and overlay
18587 it over the source code. If there is no fragment at point, display
18588 all fragments in the current text, from one headline to the next. With
18589 prefix SUBTREE, display all fragments in the current subtree. With a
18590 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18591 the cursor is before the first headline,
18592 display all fragments in the buffer.
18593 The images can be removed again with \\[org-toggle-latex-fragment]."
18595 (unless buffer-file-name
18596 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18597 (if org-latex-fragment-image-overlays
18598 (progn (org-remove-latex-fragment-image-overlays)
18599 (message "LaTeX fragments images removed"))
18600 (when (display-graphic-p)
18601 (org-remove-latex-fragment-image-overlays)
18604 (let (beg end at msg)
18606 ((or (equal subtree '(16))
18607 (not (save-excursion
18608 (re-search-backward org-outline-regexp-bol nil t))))
18609 (setq beg (point-min) end (point-max)
18610 msg "Creating images for buffer...%s"))
18611 ((equal subtree '(4))
18612 (org-back-to-heading)
18613 (setq beg (point) end (org-end-of-subtree t)
18614 msg "Creating images for subtree...%s"))
18616 (if (setq at (org-inside-LaTeX-fragment-p))
18617 (goto-char (max (point-min) (- (cdr at) 2)))
18618 (org-back-to-heading))
18619 (setq beg (point) end (progn (outline-next-heading) (point))
18620 msg (if at "Creating image...%s"
18621 "Creating images for entry...%s"))))
18623 (narrow-to-region beg end)
18626 (concat org-latex-preview-ltxpng-directory
18627 (file-name-sans-extension
18628 (file-name-nondirectory buffer-file-name)))
18629 default-directory 'overlays msg at 'forbuffer
18630 org-latex-create-formula-image-program)
18631 (message msg "done. Use `C-c C-x C-l' to remove images.")))))))
18633 (defun org-format-latex (prefix &optional dir overlays msg at
18634 forbuffer processing-type)
18635 "Replace LaTeX fragments with links to an image, and produce images.
18636 Some of the options can be changed using the variable
18637 `org-format-latex-options'."
18638 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18639 (let* ((prefixnodir (file-name-nondirectory prefix))
18640 (absprefix (expand-file-name prefix dir))
18641 (todir (file-name-directory absprefix))
18642 (opt org-format-latex-options)
18643 (optnew org-format-latex-options)
18644 (matchers (plist-get opt :matchers))
18645 (re-list org-latex-regexps)
18646 (cnt 0) txt hash link beg end re e checkdir
18648 m n block-type block linkfile movefile ov)
18649 ;; Check the different regular expressions
18650 (while (setq e (pop re-list))
18651 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18652 block (if block-type "\n\n" ""))
18653 (when (member m matchers)
18654 (goto-char (point-min))
18655 (while (re-search-forward re nil t)
18656 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18658 (not (eq (get-char-property (match-beginning n)
18660 'org-latex-overlay))))
18662 ((eq processing-type 'verbatim))
18663 ((eq processing-type 'mathjax)
18664 ;; Prepare for MathJax processing.
18665 (setq string (match-string n))
18666 (when (member m '("$" "$1"))
18668 (delete-region (match-beginning n) (match-end n))
18669 (goto-char (match-beginning n))
18670 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18671 ((or (eq processing-type 'dvipng)
18672 (eq processing-type 'imagemagick))
18673 ;; Process to an image.
18674 (setq txt (match-string n)
18675 beg (match-beginning n) end (match-end n)
18677 (let ((face (face-at-point))
18678 (fg (plist-get opt :foreground))
18679 (bg (plist-get opt :background))
18680 ;; Ensure full list is printed.
18681 print-length print-level)
18683 ;; Get the colors from the face at point.
18685 (when (eq fg 'auto)
18686 (setq fg (face-attribute face :foreground nil 'default)))
18687 (when (eq bg 'auto)
18688 (setq bg (face-attribute face :background nil 'default)))
18689 (setq optnew (copy-sequence opt))
18690 (plist-put optnew :foreground fg)
18691 (plist-put optnew :background bg))
18692 (setq hash (sha1 (prin1-to-string
18693 (list org-format-latex-header
18694 org-latex-default-packages-alist
18695 org-latex-packages-alist
18696 org-format-latex-options
18697 forbuffer txt fg bg)))
18698 linkfile (format "%s_%s.png" prefix hash)
18699 movefile (format "%s_%s.png" absprefix hash)))
18700 (setq link (concat block "[[file:" linkfile "]]" block))
18701 (if msg (message msg cnt))
18703 (unless checkdir ; Ensure the directory exists.
18705 (or (file-directory-p todir) (make-directory todir t)))
18706 (unless (file-exists-p movefile)
18707 (org-create-formula-image
18708 txt movefile optnew forbuffer processing-type))
18712 (if (eq (overlay-get o 'org-overlay-type)
18713 'org-latex-overlay)
18714 (delete-overlay o)))
18715 (overlays-in beg end))
18716 (setq ov (make-overlay beg end))
18717 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18718 (if (featurep 'xemacs)
18720 (overlay-put ov 'invisible t)
18723 (make-glyph (vector 'png :file movefile))))
18726 (list 'image :type 'png :file movefile :ascent 'center)))
18727 (push ov org-latex-fragment-image-overlays)
18729 (delete-region beg end)
18730 (insert (org-add-props link
18731 (list 'org-latex-src
18732 (replace-regexp-in-string
18734 'org-latex-src-embed-type
18735 (if block-type 'paragraph 'character))))))
18736 ((eq processing-type 'mathml)
18737 ;; Process to MathML
18738 (unless (save-match-data (org-format-latex-mathml-available-p))
18739 (user-error "LaTeX to MathML converter not configured"))
18740 (setq txt (match-string n)
18741 beg (match-beginning n) end (match-end n)
18743 (if msg (message msg cnt))
18745 (delete-region beg end)
18746 (insert (org-format-latex-as-mathml
18747 txt block-type prefix dir)))
18749 (error "Unknown conversion type %s for LaTeX fragments"
18750 processing-type)))))))))
18752 (defun org-create-math-formula (latex-frag &optional mathml-file)
18753 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18754 Use `org-latex-to-mathml-convert-command'. If the conversion is
18755 sucessful, return the portion between \"<math...> </math>\"
18756 elements otherwise return nil. When MATHML-FILE is specified,
18757 write the results in to that file. When invoked as an
18758 interactive command, prompt for LATEX-FRAG, with initial value
18759 set to the current active region and echo the results for user
18761 (interactive (list (let ((frag (when (org-region-active-p)
18762 (buffer-substring-no-properties
18763 (region-beginning) (region-end)))))
18764 (read-string "LaTeX Fragment: " frag nil frag))))
18765 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18766 (let* ((tmp-in-file (file-relative-name
18767 (make-temp-name (expand-file-name "ltxmathml-in"))))
18768 (ignore (write-region latex-frag nil tmp-in-file))
18769 (tmp-out-file (file-relative-name
18770 (make-temp-name (expand-file-name "ltxmathml-out"))))
18772 org-latex-to-mathml-convert-command
18773 `((?j . ,(shell-quote-argument
18774 (expand-file-name org-latex-to-mathml-jar-file)))
18775 (?I . ,(shell-quote-argument tmp-in-file))
18776 (?o . ,(shell-quote-argument tmp-out-file)))))
18777 mathml shell-command-output)
18778 (when (org-called-interactively-p 'any)
18779 (unless (org-format-latex-mathml-available-p)
18780 (user-error "LaTeX to MathML converter not configured")))
18781 (message "Running %s" cmd)
18782 (setq shell-command-output (shell-command-to-string cmd))
18784 (when (file-readable-p tmp-out-file)
18785 (with-current-buffer (find-file-noselect tmp-out-file t)
18786 (goto-char (point-min))
18787 (when (re-search-forward
18790 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18792 (regexp-quote "</math>")) nil t)
18793 (prog1 (match-string 0) (kill-buffer))))))
18797 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18799 (write-region mathml nil mathml-file))
18800 (when (org-called-interactively-p 'any)
18802 ((message "LaTeX to MathML conversion failed")
18803 (message shell-command-output)))
18804 (delete-file tmp-in-file)
18805 (when (file-exists-p tmp-out-file)
18806 (delete-file tmp-out-file))
18809 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18810 prefix &optional dir)
18811 "Use `org-create-math-formula' but check local cache first."
18812 (let* ((absprefix (expand-file-name prefix dir))
18813 (print-length nil) (print-level nil)
18814 (formula-id (concat
18819 org-latex-to-mathml-convert-command)))))
18820 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18821 (formula-cache-dir (file-name-directory formula-cache)))
18823 (unless (file-directory-p formula-cache-dir)
18824 (make-directory formula-cache-dir t))
18826 (unless (file-exists-p formula-cache)
18827 (org-create-math-formula latex-frag formula-cache))
18829 (if (file-exists-p formula-cache)
18830 ;; Successful conversion. Return the link to MathML file.
18832 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18833 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18834 'org-latex-src-embed-type (if latex-frag-type
18835 'paragraph 'character)))
18836 ;; Failed conversion. Return the LaTeX fragment verbatim
18839 (defun org-create-formula-image (string tofile options buffer &optional type)
18840 "Create an image from LaTeX source using dvipng or convert.
18841 This function calls either `org-create-formula-image-with-dvipng'
18842 or `org-create-formula-image-with-imagemagick' depending on the
18843 value of `org-latex-create-formula-image-program' or on the value
18844 of the optional TYPE variable.
18846 Note: ultimately these two function should be combined as they
18847 share a good deal of logic."
18848 (org-check-external-command
18849 "latex" "needed to convert LaTeX fragments to images")
18851 (case (or type org-latex-create-formula-image-program)
18853 (org-check-external-command
18854 "dvipng" "needed to convert LaTeX fragments to images")
18855 'org-create-formula-image-with-dvipng)
18857 (org-check-external-command
18858 "convert" "you need to install imagemagick")
18859 'org-create-formula-image-with-imagemagick)
18861 "Invalid value of `org-latex-create-formula-image-program'")))
18862 string tofile options buffer))
18864 (declare-function org-export-get-backend "ox" (name))
18865 (declare-function org-export--get-global-options "ox" (&optional backend))
18866 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18867 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18868 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18869 (defun org-create-formula--latex-header ()
18870 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18871 (let ((info (org-combine-plists (org-export--get-global-options
18872 (org-export-get-backend 'latex))
18873 (org-export--get-inbuffer-options
18874 (org-export-get-backend 'latex)))))
18875 (org-latex-guess-babel-language
18876 (org-latex-guess-inputenc
18877 (org-splice-latex-header
18878 org-format-latex-header
18879 org-latex-default-packages-alist
18880 org-latex-packages-alist t
18881 (plist-get info :latex-header)))
18884 ;; This function borrows from Ganesh Swami's latex2png.el
18885 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18886 "This calls dvipng."
18887 (require 'ox-latex)
18888 (let* ((tmpdir (if (featurep 'xemacs)
18890 temporary-file-directory))
18891 (texfilebase (make-temp-name
18892 (expand-file-name "orgtex" tmpdir)))
18893 (texfile (concat texfilebase ".tex"))
18894 (dvifile (concat texfilebase ".dvi"))
18895 (pngfile (concat texfilebase ".png"))
18896 (fnh (if (featurep 'xemacs)
18897 (font-height (face-font 'default))
18898 (face-attribute 'default :height nil)))
18899 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18900 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18901 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18903 (bg (or (plist-get options (if buffer :background :html-background))
18905 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18906 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18907 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18908 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18909 (let ((latex-header (org-create-formula--latex-header)))
18910 (with-temp-file texfile
18911 (insert latex-header)
18912 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18913 (let ((dir default-directory))
18916 (call-process "latex" nil nil nil texfile))
18918 (if (not (file-exists-p dvifile))
18919 (progn (message "Failed to create dvi file from %s" texfile) nil)
18921 (if (featurep 'xemacs)
18922 (call-process "dvipng" nil nil nil
18927 (call-process "dvipng" nil nil nil
18930 ;;"-x" scale "-y" scale
18934 (if (not (file-exists-p pngfile))
18935 (if org-format-latex-signal-error
18936 (error "Failed to create png file from %s" texfile)
18937 (message "Failed to create png file from %s" texfile)
18939 ;; Use the requested file name and clean up
18940 (copy-file pngfile tofile 'replace)
18941 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18942 (if (file-exists-p (concat texfilebase e))
18943 (delete-file (concat texfilebase e))))
18946 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18947 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18948 "This calls convert, which is included into imagemagick."
18949 (require 'ox-latex)
18950 (let* ((tmpdir (if (featurep 'xemacs)
18952 temporary-file-directory))
18953 (texfilebase (make-temp-name
18954 (expand-file-name "orgtex" tmpdir)))
18955 (texfile (concat texfilebase ".tex"))
18956 (pdffile (concat texfilebase ".pdf"))
18957 (pngfile (concat texfilebase ".png"))
18958 (fnh (if (featurep 'xemacs)
18959 (font-height (face-font 'default))
18960 (face-attribute 'default :height nil)))
18961 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18962 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18963 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18965 (bg (or (plist-get options (if buffer :background :html-background))
18967 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18968 (setq fg (org-latex-color-format fg)))
18969 (if (eq bg 'default) (setq bg (org-latex-color :background))
18970 (setq bg (org-latex-color-format
18971 (if (string= bg "Transparent") "white" bg))))
18972 (let ((latex-header (org-create-formula--latex-header)))
18973 (with-temp-file texfile
18974 (insert latex-header)
18975 (insert "\n\\begin{document}\n"
18976 "\\definecolor{fg}{rgb}{" fg "}\n"
18977 "\\definecolor{bg}{rgb}{" bg "}\n"
18978 "\n\\pagecolor{bg}\n"
18982 "\n\\end{document}\n")))
18983 (org-latex-compile texfile t)
18984 (if (not (file-exists-p pdffile))
18985 (progn (message "Failed to create pdf file from %s" texfile) nil)
18987 (if (featurep 'xemacs)
18988 (call-process "convert" nil nil nil
18994 ;; "-sharpen" "0x1.0"
18996 (call-process "convert" nil nil nil
19002 ;; "-sharpen" "0x1.0"
19004 (if (not (file-exists-p pngfile))
19005 (if org-format-latex-signal-error
19006 (error "Failed to create png file from %s" texfile)
19007 (message "Failed to create png file from %s" texfile)
19009 ;; Use the requested file name and clean up
19010 (copy-file pngfile tofile 'replace)
19011 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
19012 (if (file-exists-p (concat texfilebase e))
19013 (delete-file (concat texfilebase e))))
19016 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19017 "Fill a LaTeX header template TPL.
19018 In the template, the following place holders will be recognized:
19020 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19021 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19022 [PACKAGES] \\usepackage statements for PKG
19023 [NO-PACKAGES] do not include PKG
19024 [EXTRA] the string EXTRA
19025 [NO-EXTRA] do not include EXTRA
19027 For backward compatibility, if both the positive and the negative place
19028 holder is missing, the positive one (without the \"NO-\") will be
19029 assumed to be present at the end of the template.
19030 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19032 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19033 (let (rpl (end ""))
19034 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19035 (setq rpl (if (or (match-end 1) (not def-pkg))
19036 "" (org-latex-packages-to-string def-pkg snippets-p t))
19037 tpl (replace-match rpl t t tpl))
19038 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19040 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19041 (setq rpl (if (or (match-end 1) (not pkg))
19042 "" (org-latex-packages-to-string pkg snippets-p t))
19043 tpl (replace-match rpl t t tpl))
19046 (org-latex-packages-to-string pkg snippets-p)))))
19048 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19049 (setq rpl (if (or (match-end 1) (not extra))
19050 "" (concat extra "\n"))
19051 tpl (replace-match rpl t t tpl))
19052 (if (and extra (string-match "\\S-" extra))
19053 (setq end (concat end "\n" extra))))
19055 (if (string-match "\\S-" end)
19056 (concat tpl "\n" end)
19059 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19060 "Turn an alist of packages into a string with the \\usepackage macros."
19061 (setq pkg (mapconcat (lambda(p)
19064 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19065 (format "%% Package %s omitted" (cadr p)))
19066 ((equal "" (car p))
19067 (format "\\usepackage{%s}" (cadr p)))
19069 (format "\\usepackage[%s]{%s}"
19070 (car p) (cadr p)))))
19073 (if newline (concat pkg "\n") pkg))
19075 (defun org-dvipng-color (attr)
19076 "Return a RGB color specification for dvipng."
19077 (apply 'format "rgb %s %s %s"
19078 (mapcar 'org-normalize-color
19079 (if (featurep 'xemacs)
19080 (color-rgb-components
19081 (face-property 'default
19082 (cond ((eq attr :foreground) 'foreground)
19083 ((eq attr :background) 'background))))
19084 (color-values (face-attribute 'default attr nil))))))
19086 (defun org-dvipng-color-format (color-name)
19087 "Convert COLOR-NAME to a RGB color value for dvipng."
19088 (apply 'format "rgb %s %s %s"
19089 (mapcar 'org-normalize-color
19090 (color-values color-name))))
19092 (defun org-latex-color (attr)
19093 "Return a RGB color for the LaTeX color package."
19094 (apply 'format "%s,%s,%s"
19095 (mapcar 'org-normalize-color
19096 (if (featurep 'xemacs)
19097 (color-rgb-components
19098 (face-property 'default
19099 (cond ((eq attr :foreground) 'foreground)
19100 ((eq attr :background) 'background))))
19101 (color-values (face-attribute 'default attr nil))))))
19103 (defun org-latex-color-format (color-name)
19104 "Convert COLOR-NAME to a RGB color value."
19105 (apply 'format "%s,%s,%s"
19106 (mapcar 'org-normalize-color
19107 (color-values color-name))))
19109 (defun org-normalize-color (value)
19110 "Return string to be used as color value for an RGB component."
19111 (format "%g" (/ value 65535.0)))
19117 (defvar org-inline-image-overlays nil)
19118 (make-variable-buffer-local 'org-inline-image-overlays)
19120 (defun org-toggle-inline-images (&optional include-linked)
19121 "Toggle the display of inline images.
19122 INCLUDE-LINKED is passed to `org-display-inline-images'."
19124 (if org-inline-image-overlays
19126 (org-remove-inline-images)
19127 (message "Inline image display turned off"))
19128 (org-display-inline-images include-linked)
19129 (if (and (org-called-interactively-p)
19130 org-inline-image-overlays)
19131 (message "%d images displayed inline"
19132 (length org-inline-image-overlays))
19133 (message "No images to display inline"))))
19135 (defun org-redisplay-inline-images ()
19136 "Refresh the display of inline images."
19138 (if (not org-inline-image-overlays)
19139 (org-toggle-inline-images)
19140 (org-toggle-inline-images)
19141 (org-toggle-inline-images)))
19143 (defun org-display-inline-images (&optional include-linked refresh beg end)
19144 "Display inline images.
19146 An inline image is a link which follows either of these
19149 1. Its path is a file with an extension matching return value
19150 from `image-file-name-regexp' and it has no contents.
19152 2. Its description consists in a single link of the previous
19155 When optional argument INCLUDE-LINKED is non-nil, also links with
19156 a text description part will be inlined. This can be nice for
19157 a quick look at those images, but it does not reflect what
19158 exported files will look like.
19160 When optional argument REFRESH is non-nil, refresh existing
19161 images between BEG and END. This will create new image displays
19162 only if necessary. BEG and END default to the buffer
19165 (when (display-graphic-p)
19167 (org-remove-inline-images)
19168 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19169 (org-with-wide-buffer
19170 (goto-char (or beg (point-min)))
19171 (let ((case-fold-search t)
19172 (file-extension-re (org-image-file-name-regexp)))
19173 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19174 (let ((link (save-match-data (org-element-context))))
19175 ;; Check if we're at an inline image.
19176 (when (and (equal (org-element-property :type link) "file")
19178 (not (org-element-property :contents-begin link)))
19179 (let ((parent (org-element-property :parent link)))
19180 (or (not (eq (org-element-type parent) 'link))
19181 (not (cdr (org-element-contents parent)))))
19182 (org-string-match-p file-extension-re
19183 (org-element-property :path link)))
19184 (let ((file (expand-file-name (org-element-property :path link))))
19185 (when (file-exists-p file)
19187 ;; Apply `org-image-actual-width' specifications.
19189 ((not (image-type-available-p 'imagemagick)) nil)
19190 ((eq org-image-actual-width t) nil)
19191 ((listp org-image-actual-width)
19193 ;; First try to find a width among
19194 ;; attributes associated to the paragraph
19195 ;; containing link.
19198 (while (and (setq e (org-element-property
19200 (not (eq (org-element-type e)
19205 (goto-char (org-element-property :begin paragraph))
19208 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19209 (org-element-property
19210 :post-affiliated paragraph)
19212 (string-to-number (match-string 1))))))
19213 ;; Otherwise, fall-back to provided number.
19214 (car org-image-actual-width)))
19215 ((numberp org-image-actual-width)
19216 org-image-actual-width)))
19217 (old (get-char-property-and-overlay
19218 (org-element-property :begin link)
19219 'org-image-overlay)))
19220 (if (and (car-safe old) refresh)
19221 (image-refresh (overlay-get (cdr old) 'display))
19222 (let ((image (create-image file
19223 (and width 'imagemagick)
19228 ;; If inline image is the description
19229 ;; of another link, be sure to
19230 ;; consider the latter as the one to
19231 ;; apply the overlay on.
19233 (org-element-property :parent link)))
19234 (if (eq (org-element-type parent) 'link)
19238 (org-element-property :begin link)
19241 (org-element-property :end link))
19242 (skip-chars-backward " \t")
19244 (overlay-put ov 'display image)
19245 (overlay-put ov 'face 'default)
19246 (overlay-put ov 'org-image-overlay t)
19248 ov 'modification-hooks
19249 (list 'org-display-inline-remove-overlay))
19250 (push ov org-inline-image-overlays)))))))))))))))
19252 (define-obsolete-function-alias
19253 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19255 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19256 "Remove inline-display overlay if a corresponding region is modified."
19257 (let ((inhibit-modification-hooks t))
19258 (when (and ov after)
19259 (delete ov org-inline-image-overlays)
19260 (delete-overlay ov))))
19262 (defun org-remove-inline-images ()
19263 "Remove inline display of images."
19265 (mapc 'delete-overlay org-inline-image-overlays)
19266 (setq org-inline-image-overlays nil))
19270 ;; Outline functions from `outline-mode-prefix-map'
19271 ;; that can be remapped in Org:
19272 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19273 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19274 (define-key org-mode-map [remap outline-forward-same-level]
19275 'org-forward-heading-same-level)
19276 (define-key org-mode-map [remap outline-backward-same-level]
19277 'org-backward-heading-same-level)
19278 (define-key org-mode-map [remap show-branches]
19279 'org-kill-note-or-show-branches)
19280 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19281 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19282 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19284 ;; Outline functions from `outline-mode-prefix-map' that can not
19285 ;; be remapped in Org:
19287 ;; - the column "key binding" shows whether the Outline function is still
19288 ;; available in Org mode on the same key that it has been bound to in
19290 ;; - "overridden": key used for a different functionality in Org mode
19291 ;; - else: key still bound to the same Outline function in Org mode
19293 ;; | Outline function | key binding | Org replacement |
19294 ;; |------------------------------------+-------------+-----------------------|
19295 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19296 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19297 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19298 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19299 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19300 ;; | `show-entry' | overridden | no replacement |
19301 ;; | `show-children' | `C-c C-i' | visibility cycling |
19302 ;; | `show-branches' | `C-c C-k' | still same function |
19303 ;; | `show-subtree' | overridden | visibility cycling |
19304 ;; | `show-all' | overridden | no replacement |
19305 ;; | `hide-subtree' | overridden | visibility cycling |
19306 ;; | `hide-body' | overridden | no replacement |
19307 ;; | `hide-entry' | overridden | visibility cycling |
19308 ;; | `hide-leaves' | overridden | no replacement |
19309 ;; | `hide-sublevels' | overridden | no replacement |
19310 ;; | `hide-other' | overridden | no replacement |
19312 ;; Make `C-c C-x' a prefix key
19313 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19315 ;; TAB key with modifiers
19316 (org-defkey org-mode-map "\C-i" 'org-cycle)
19317 (org-defkey org-mode-map [(tab)] 'org-cycle)
19318 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19319 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19320 ;; The following line is necessary under Suse GNU/Linux
19321 (unless (featurep 'xemacs)
19322 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19323 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19324 (define-key org-mode-map [backtab] 'org-shifttab)
19326 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19327 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19328 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19330 ;; Cursor keys with modifiers
19331 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19332 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19333 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19334 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19336 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19337 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19338 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19339 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19340 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19341 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19343 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19344 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19345 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19346 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19348 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19349 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19350 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19351 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19354 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19355 (mapc (lambda (pair)
19356 (define-key org-babel-map (car pair) (cdr pair)))
19357 org-babel-key-bindings)
19359 ;;; Extra keys for tty access.
19360 ;; We only set them when really needed because otherwise the
19361 ;; menus don't show the simple keys
19363 (when (or org-use-extra-keys
19364 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19365 (not window-system))
19366 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19367 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19368 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19369 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19370 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19371 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19372 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19373 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19374 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19375 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19376 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19377 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19378 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19379 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19380 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19381 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19382 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19383 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19384 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19385 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19386 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19387 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19388 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19389 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19390 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19391 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19392 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19393 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19395 ;; All the other keys
19397 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19398 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19399 (if (boundp 'narrow-map)
19400 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19401 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19402 (if (boundp 'narrow-map)
19403 (org-defkey narrow-map "b" 'org-narrow-to-block)
19404 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19405 (if (boundp 'narrow-map)
19406 (org-defkey narrow-map "e" 'org-narrow-to-element)
19407 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19408 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19409 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19410 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19411 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19412 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19413 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19414 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19415 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19416 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19417 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19418 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19419 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19420 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19421 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19422 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19423 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19424 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19425 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19426 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19427 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19428 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19429 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19430 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19431 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19432 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19433 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19434 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19435 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19436 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19437 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19438 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19439 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19440 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19441 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19442 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19443 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19444 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19445 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19446 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19447 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19448 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19449 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19450 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19451 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19452 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19453 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19454 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19455 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19456 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19457 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19458 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19459 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19460 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19461 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19462 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19463 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19464 (org-defkey org-mode-map "\C-c^" 'org-sort)
19465 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19466 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19467 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19468 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19469 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19470 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19471 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19472 (org-defkey org-mode-map "\C-m" 'org-return)
19473 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19474 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19475 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19476 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19477 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19478 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19479 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19480 (org-defkey org-mode-map "\C-cp" 'orgtbl-ascii-plot)
19481 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19482 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19483 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19484 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19485 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19486 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19487 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19488 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19489 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19490 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19491 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19492 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19493 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19494 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19495 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19496 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19498 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19499 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19500 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19502 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19503 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19504 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19505 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19506 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19507 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19508 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19509 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19510 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19511 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19512 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19513 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19514 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19515 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19516 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19517 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19518 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19519 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19520 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19521 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19522 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19523 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19524 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19526 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19527 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19528 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19529 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19530 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19532 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19534 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19536 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19537 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19539 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19542 (when (featurep 'xemacs)
19543 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19546 (defconst org-speed-commands-default
19548 ("Outline Navigation")
19549 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19550 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19551 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19552 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19553 ("F" . org-next-block)
19554 ("B" . org-previous-block)
19555 ("u" . (org-speed-move-safe 'outline-up-heading))
19557 ("g" . (org-refile t))
19558 ("Outline Visibility")
19560 ("C" . org-shifttab)
19561 (" " . org-display-outline-path)
19562 ("s" . org-narrow-to-subtree)
19563 ("=" . org-columns)
19564 ("Outline Structure Editing")
19566 ("D" . org-metadown)
19567 ("r" . org-metaright)
19568 ("l" . org-metaleft)
19569 ("R" . org-shiftmetaright)
19570 ("L" . org-shiftmetaleft)
19571 ("i" . (progn (forward-char 1) (call-interactively
19572 'org-insert-heading-respect-content)))
19575 ("a" . org-archive-subtree-default-with-confirmation)
19576 ("@" . org-mark-subtree)
19577 ("#" . org-toggle-comment)
19579 ("I" . org-clock-in)
19580 ("O" . org-clock-out)
19581 ("Meta Data Editing")
19583 ("," . (org-priority))
19584 ("0" . (org-priority ?\ ))
19585 ("1" . (org-priority ?A))
19586 ("2" . (org-priority ?B))
19587 ("3" . (org-priority ?C))
19588 (":" . org-set-tags-command)
19589 ("e" . org-set-effort)
19590 ("E" . org-inc-effort)
19591 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19592 (org-entry-put (point) "APPT_WARNTIME" m)))
19593 ("Agenda Views etc")
19595 ("/" . org-sparse-tree)
19597 ("o" . org-open-at-point)
19598 ("?" . org-speed-command-help)
19599 ("<" . (org-agenda-set-restriction-lock 'subtree))
19600 (">" . (org-agenda-remove-restriction-lock))
19602 "The default speed commands.")
19604 (defun org-print-speed-command (e)
19605 (if (> (length (car e)) 1)
19610 (princ (make-string (length (car e)) ?-))
19614 (if (symbolp (cdr e))
19615 (princ (symbol-name (cdr e)))
19619 (defun org-speed-command-help ()
19620 "Show the available speed commands."
19622 (if (not org-use-speed-commands)
19623 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19624 (with-output-to-temp-buffer "*Help*"
19625 (princ "User-defined Speed commands\n===========================\n")
19626 (mapc 'org-print-speed-command org-speed-commands-user)
19628 (princ "Built-in Speed commands\n=======================\n")
19629 (mapc 'org-print-speed-command org-speed-commands-default))
19630 (with-current-buffer "*Help*"
19631 (setq truncate-lines t))))
19633 (defun org-speed-move-safe (cmd)
19634 "Execute CMD, but make sure that the cursor always ends up in a headline.
19635 If not, return to the original position and throw an error."
19637 (let ((pos (point)))
19638 (call-interactively cmd)
19639 (unless (and (bolp) (org-at-heading-p))
19641 (error "Boundary reached while executing %s" cmd))))
19643 (defvar org-self-insert-command-undo-counter 0)
19645 (defvar org-table-auto-blank-field) ; defined in org-table.el
19646 (defvar org-speed-command nil)
19648 (define-obsolete-function-alias
19649 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19651 (defun org-speed-command-activate (keys)
19652 "Hook for activating single-letter speed commands.
19653 `org-speed-commands-default' specifies a minimal command set.
19654 Use `org-speed-commands-user' for further customization."
19655 (when (or (and (bolp) (looking-at org-outline-regexp))
19656 (and (functionp org-use-speed-commands)
19657 (funcall org-use-speed-commands)))
19658 (cdr (assoc keys (append org-speed-commands-user
19659 org-speed-commands-default)))))
19661 (define-obsolete-function-alias
19662 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19664 (defun org-babel-speed-command-activate (keys)
19665 "Hook for activating single-letter code block commands."
19666 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19667 (cdr (assoc keys org-babel-key-bindings))))
19669 (defcustom org-speed-command-hook
19670 '(org-speed-command-default-hook org-babel-speed-command-hook)
19671 "Hook for activating speed commands at strategic locations.
19672 Hook functions are called in sequence until a valid handler is
19675 Each hook takes a single argument, a user-pressed command key
19676 which is also a `self-insert-command' from the global map.
19678 Within the hook, examine the cursor position and the command key
19679 and return nil or a valid handler as appropriate. Handler could
19680 be one of an interactive command, a function, or a form.
19682 Set `org-use-speed-commands' to non-nil value to enable this
19683 hook. The default setting is `org-speed-command-activate'."
19684 :group 'org-structure
19688 (defun org-self-insert-command (N)
19689 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19690 If the cursor is in a table looking at whitespace, the whitespace is
19691 overwritten, and the table is not marked as requiring realignment."
19693 (org-check-before-invisible-edit 'insert)
19695 ((and org-use-speed-commands
19696 (setq org-speed-command
19697 (run-hook-with-args-until-success
19698 'org-speed-command-hook (this-command-keys))))
19700 ((commandp org-speed-command)
19701 (setq this-command org-speed-command)
19702 (call-interactively org-speed-command))
19703 ((functionp org-speed-command)
19704 (funcall org-speed-command))
19705 ((and org-speed-command (listp org-speed-command))
19706 (eval org-speed-command))
19707 (t (let (org-use-speed-commands)
19708 (call-interactively 'org-self-insert-command)))))
19712 ;; check if we blank the field, and if that triggers align
19713 (and (featurep 'org-table) org-table-auto-blank-field
19714 (member last-command
19715 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas-expand))
19716 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19717 ;; got extra space, this field does not determine column width
19718 (let (org-table-may-need-update) (org-table-blank-field))
19719 ;; no extra space, this field may determine column width
19720 (org-table-blank-field)))
19723 (looking-at "[^|\n]* |"))
19724 (let (org-table-may-need-update)
19725 (goto-char (1- (match-end 0)))
19726 (backward-delete-char 1)
19727 (goto-char (match-beginning 0))
19728 (self-insert-command N)))
19730 (setq org-table-may-need-update t)
19731 (self-insert-command N)
19732 (org-fix-tags-on-the-fly)
19733 (if org-self-insert-cluster-for-undo
19734 (if (not (eq last-command 'org-self-insert-command))
19735 (setq org-self-insert-command-undo-counter 1)
19736 (if (>= org-self-insert-command-undo-counter 20)
19737 (setq org-self-insert-command-undo-counter 1)
19738 (and (> org-self-insert-command-undo-counter 0)
19739 buffer-undo-list (listp buffer-undo-list)
19740 (not (cadr buffer-undo-list)) ; remove nil entry
19741 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19742 (setq org-self-insert-command-undo-counter
19743 (1+ org-self-insert-command-undo-counter))))))))
19745 (defun org-check-before-invisible-edit (kind)
19746 "Check is editing if kind KIND would be dangerous with invisible text around.
19747 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19748 ;; First, try to get out of here as quickly as possible, to reduce overhead
19749 (if (and org-catch-invisible-edits
19750 (or (not (boundp 'visible-mode)) (not visible-mode))
19751 (or (get-char-property (point) 'invisible)
19752 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19753 ;; OK, we need to take a closer look
19754 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19755 (invisible-before-point (if (bobp) nil (get-char-property
19756 (1- (point)) 'invisible)))
19757 (border-and-ok-direction
19759 ;; Check if we are acting predictably before invisible text
19760 (and invisible-at-point (not invisible-before-point)
19761 (memq kind '(insert delete-backward)))
19762 ;; Check if we are acting predictably after invisible text
19763 ;; This works not well, and I have turned it off. It seems
19764 ;; better to always show and stop after invisible text.
19765 ;; (and (not invisible-at-point) invisible-before-point
19766 ;; (memq kind '(insert delete)))
19768 (when (or (memq invisible-at-point '(outline org-hide-block t))
19769 (memq invisible-before-point '(outline org-hide-block t)))
19770 (if (eq org-catch-invisible-edits 'error)
19771 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19772 (if (and org-custom-properties-overlays
19773 (y-or-n-p "Display invisible properties in this buffer? "))
19774 (org-toggle-custom-properties-visibility)
19775 ;; Make the area visible
19777 (if invisible-before-point
19778 (goto-char (previous-single-char-property-change
19779 (point) 'invisible)))
19782 ((eq org-catch-invisible-edits 'show)
19783 ;; That's it, we do the edit after showing
19785 "Unfolding invisible region around point before editing")
19787 ((and (eq org-catch-invisible-edits 'smart)
19788 border-and-ok-direction)
19789 (message "Unfolding invisible region around point before editing"))
19791 ;; Don't do the edit, make the user repeat it in full visibility
19792 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19794 (defun org-fix-tags-on-the-fly ()
19795 (when (and (equal (char-after (point-at-bol)) ?*)
19796 (org-at-heading-p))
19797 (org-align-tags-here org-tags-column)))
19799 (defun org-delete-backward-char (N)
19800 "Like `delete-backward-char', insert whitespace at field end in tables.
19801 When deleting backwards, in tables this function will insert whitespace in
19802 front of the next \"|\" separator, to keep the table aligned. The table will
19803 still be marked for re-alignment if the field did fill the entire column,
19804 because, in this case the deletion might narrow the column."
19807 (org-check-before-invisible-edit 'delete-backward)
19808 (if (and (org-table-p)
19810 (string-match "|" (buffer-substring (point-at-bol) (point)))
19811 (looking-at ".*?|"))
19812 (let ((pos (point))
19813 (noalign (looking-at "[^|\n\r]* |"))
19814 (c org-table-may-need-update))
19815 (backward-delete-char N)
19816 (if (not overwrite-mode)
19818 (skip-chars-forward "^|")
19820 (goto-char (1- pos))))
19821 ;; noalign: if there were two spaces at the end, this field
19822 ;; does not determine the width of the column.
19823 (if noalign (setq org-table-may-need-update c)))
19824 (backward-delete-char N)
19825 (org-fix-tags-on-the-fly))))
19827 (defun org-delete-char (N)
19828 "Like `delete-char', but insert whitespace at field end in tables.
19829 When deleting characters, in tables this function will insert whitespace in
19830 front of the next \"|\" separator, to keep the table aligned. The table will
19831 still be marked for re-alignment if the field did fill the entire column,
19832 because, in this case the deletion might narrow the column."
19835 (org-check-before-invisible-edit 'delete)
19836 (if (and (org-table-p)
19838 (not (= (char-after) ?|))
19840 (if (looking-at ".*?|")
19841 (let ((pos (point))
19842 (noalign (looking-at "[^|\n\r]* |"))
19843 (c org-table-may-need-update))
19845 (concat (substring (match-string 0) 1 -1) " |") nil t)
19847 ;; noalign: if there were two spaces at the end, this field
19848 ;; does not determine the width of the column.
19849 (if noalign (setq org-table-may-need-update c)))
19852 (org-fix-tags-on-the-fly))))
19854 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19855 (put 'org-self-insert-command 'delete-selection
19857 (not (run-hook-with-args-until-success
19858 'self-insert-uses-region-functions))))
19859 (put 'orgtbl-self-insert-command 'delete-selection
19861 (not (run-hook-with-args-until-success
19862 'self-insert-uses-region-functions))))
19863 (put 'org-delete-char 'delete-selection 'supersede)
19864 (put 'org-delete-backward-char 'delete-selection 'supersede)
19865 (put 'org-yank 'delete-selection 'yank)
19867 ;; Make `flyspell-mode' delay after some commands
19868 (put 'org-self-insert-command 'flyspell-delayed t)
19869 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19870 (put 'org-delete-char 'flyspell-delayed t)
19871 (put 'org-delete-backward-char 'flyspell-delayed t)
19873 ;; Make pabbrev-mode expand after org-mode commands
19874 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19875 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19877 (defun org-remap (map &rest commands)
19878 "In MAP, remap the functions given in COMMANDS.
19879 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19882 (setq old (pop commands) new (pop commands))
19883 (if (fboundp 'command-remapping)
19884 (org-defkey map (vector 'remap old) new)
19885 (substitute-key-definition old new map global-map)))))
19887 (defun org-transpose-words ()
19888 "Transpose words for Org.
19889 This uses the `org-mode-transpose-word-syntax-table' syntax
19890 table, which interprets characters in `org-emphasis-alist' as
19891 word constituents."
19893 (with-syntax-table org-mode-transpose-word-syntax-table
19894 (call-interactively 'transpose-words)))
19895 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19897 (when (eq org-enable-table-editor 'optimized)
19898 ;; If the user wants maximum table support, we need to hijack
19899 ;; some standard editing functions
19900 (org-remap org-mode-map
19901 'self-insert-command 'org-self-insert-command
19902 'delete-char 'org-delete-char
19903 'delete-backward-char 'org-delete-backward-char)
19904 (org-defkey org-mode-map "|" 'org-force-self-insert))
19906 (defvar org-ctrl-c-ctrl-c-hook nil
19907 "Hook for functions attaching themselves to `C-c C-c'.
19909 This can be used to add additional functionality to the C-c C-c
19910 key which executes context-dependent commands. This hook is run
19911 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19912 run after the last test.
19914 Each function will be called with no arguments. The function
19915 must check if the context is appropriate for it to act. If yes,
19916 it should do its thing and then return a non-nil value. If the
19917 context is wrong, just do nothing and return nil.")
19919 (defvar org-ctrl-c-ctrl-c-final-hook nil
19920 "Hook for functions attaching themselves to `C-c C-c'.
19922 This can be used to add additional functionality to the C-c C-c
19923 key which executes context-dependent commands. This hook is run
19924 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19925 before the first test.
19927 Each function will be called with no arguments. The function
19928 must check if the context is appropriate for it to act. If yes,
19929 it should do its thing and then return a non-nil value. If the
19930 context is wrong, just do nothing and return nil.")
19932 (defvar org-tab-first-hook nil
19933 "Hook for functions to attach themselves to TAB.
19934 See `org-ctrl-c-ctrl-c-hook' for more information.
19935 This hook runs as the first action when TAB is pressed, even before
19936 `org-cycle' messes around with the `outline-regexp' to cater for
19937 inline tasks and plain list item folding.
19938 If any function in this hook returns t, any other actions that
19939 would have been caused by TAB (such as table field motion or visibility
19940 cycling) will not occur.")
19942 (defvar org-tab-after-check-for-table-hook nil
19943 "Hook for functions to attach themselves to TAB.
19944 See `org-ctrl-c-ctrl-c-hook' for more information.
19945 This hook runs after it has been established that the cursor is not in a
19946 table, but before checking if the cursor is in a headline or if global cycling
19948 If any function in this hook returns t, not other actions like visibility
19949 cycling will be done.")
19951 (defvar org-tab-after-check-for-cycling-hook nil
19952 "Hook for functions to attach themselves to TAB.
19953 See `org-ctrl-c-ctrl-c-hook' for more information.
19954 This hook runs after it has been established that not table field motion and
19955 not visibility should be done because of current context. This is probably
19956 the place where a package like yasnippets can hook in.")
19958 (defvar org-tab-before-tab-emulation-hook nil
19959 "Hook for functions to attach themselves to TAB.
19960 See `org-ctrl-c-ctrl-c-hook' for more information.
19961 This hook runs after every other options for TAB have been exhausted, but
19962 before indentation and \t insertion takes place.")
19964 (defvar org-metaleft-hook nil
19965 "Hook for functions attaching themselves to `M-left'.
19966 See `org-ctrl-c-ctrl-c-hook' for more information.")
19967 (defvar org-metaright-hook nil
19968 "Hook for functions attaching themselves to `M-right'.
19969 See `org-ctrl-c-ctrl-c-hook' for more information.")
19970 (defvar org-metaup-hook nil
19971 "Hook for functions attaching themselves to `M-up'.
19972 See `org-ctrl-c-ctrl-c-hook' for more information.")
19973 (defvar org-metadown-hook nil
19974 "Hook for functions attaching themselves to `M-down'.
19975 See `org-ctrl-c-ctrl-c-hook' for more information.")
19976 (defvar org-shiftmetaleft-hook nil
19977 "Hook for functions attaching themselves to `M-S-left'.
19978 See `org-ctrl-c-ctrl-c-hook' for more information.")
19979 (defvar org-shiftmetaright-hook nil
19980 "Hook for functions attaching themselves to `M-S-right'.
19981 See `org-ctrl-c-ctrl-c-hook' for more information.")
19982 (defvar org-shiftmetaup-hook nil
19983 "Hook for functions attaching themselves to `M-S-up'.
19984 See `org-ctrl-c-ctrl-c-hook' for more information.")
19985 (defvar org-shiftmetadown-hook nil
19986 "Hook for functions attaching themselves to `M-S-down'.
19987 See `org-ctrl-c-ctrl-c-hook' for more information.")
19988 (defvar org-metareturn-hook nil
19989 "Hook for functions attaching themselves to `M-RET'.
19990 See `org-ctrl-c-ctrl-c-hook' for more information.")
19991 (defvar org-shiftup-hook nil
19992 "Hook for functions attaching themselves to `S-up'.
19993 See `org-ctrl-c-ctrl-c-hook' for more information.")
19994 (defvar org-shiftup-final-hook nil
19995 "Hook for functions attaching themselves to `S-up'.
19996 This one runs after all other options except shift-select have been excluded.
19997 See `org-ctrl-c-ctrl-c-hook' for more information.")
19998 (defvar org-shiftdown-hook nil
19999 "Hook for functions attaching themselves to `S-down'.
20000 See `org-ctrl-c-ctrl-c-hook' for more information.")
20001 (defvar org-shiftdown-final-hook nil
20002 "Hook for functions attaching themselves to `S-down'.
20003 This one runs after all other options except shift-select have been excluded.
20004 See `org-ctrl-c-ctrl-c-hook' for more information.")
20005 (defvar org-shiftleft-hook nil
20006 "Hook for functions attaching themselves to `S-left'.
20007 See `org-ctrl-c-ctrl-c-hook' for more information.")
20008 (defvar org-shiftleft-final-hook nil
20009 "Hook for functions attaching themselves to `S-left'.
20010 This one runs after all other options except shift-select have been excluded.
20011 See `org-ctrl-c-ctrl-c-hook' for more information.")
20012 (defvar org-shiftright-hook nil
20013 "Hook for functions attaching themselves to `S-right'.
20014 See `org-ctrl-c-ctrl-c-hook' for more information.")
20015 (defvar org-shiftright-final-hook nil
20016 "Hook for functions attaching themselves to `S-right'.
20017 This one runs after all other options except shift-select have been excluded.
20018 See `org-ctrl-c-ctrl-c-hook' for more information.")
20020 (defun org-modifier-cursor-error ()
20021 "Throw an error, a modified cursor command was applied in wrong context."
20022 (user-error "This command is active in special context like tables, headlines or items"))
20024 (defun org-shiftselect-error ()
20025 "Throw an error because Shift-Cursor command was applied in wrong context."
20026 (if (and (boundp 'shift-select-mode) shift-select-mode)
20027 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20028 (user-error "This command works only in special context like headlines or timestamps")))
20030 (defun org-call-for-shift-select (cmd)
20031 (let ((this-command-keys-shift-translated t))
20032 (call-interactively cmd)))
20034 (defun org-shifttab (&optional arg)
20035 "Global visibility cycling or move to previous table field.
20036 Call `org-table-previous-field' within a table.
20037 When ARG is nil, cycle globally through visibility states.
20038 When ARG is a numeric prefix, show contents of this level."
20041 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20043 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20044 (message "Content view to level: %d" arg)
20045 (org-content (prefix-numeric-value arg2))
20046 (org-cycle-show-empty-lines t)
20047 (setq org-cycle-global-status 'overview)))
20048 (t (call-interactively 'org-global-cycle))))
20050 (defun org-shiftmetaleft ()
20051 "Promote subtree or delete table column.
20052 Calls `org-promote-subtree', `org-outdent-item-tree', or
20053 `org-table-delete-column', depending on context. See the
20054 individual commands for more information."
20057 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20058 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20059 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20060 ((if (not (org-region-active-p)) (org-at-item-p)
20061 (save-excursion (goto-char (region-beginning))
20063 (call-interactively 'org-outdent-item-tree))
20064 (t (org-modifier-cursor-error))))
20066 (defun org-shiftmetaright ()
20067 "Demote subtree or insert table column.
20068 Calls `org-demote-subtree', `org-indent-item-tree', or
20069 `org-table-insert-column', depending on context. See the
20070 individual commands for more information."
20073 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20074 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20075 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20076 ((if (not (org-region-active-p)) (org-at-item-p)
20077 (save-excursion (goto-char (region-beginning))
20079 (call-interactively 'org-indent-item-tree))
20080 (t (org-modifier-cursor-error))))
20082 (defun org-shiftmetaup (&optional arg)
20083 "Drag the line at point up.
20084 In a table, kill the current row.
20085 On a clock timestamp, update the value of the timestamp like `S-<up>'
20086 but also adjust the previous clocked item in the clock history.
20087 Everywhere else, drag the line at point up."
20090 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20091 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20092 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20093 (call-interactively 'org-timestamp-up)))
20094 (t (call-interactively 'org-drag-line-backward))))
20096 (defun org-shiftmetadown (&optional arg)
20097 "Drag the line at point down.
20098 In a table, insert an empty row at the current line.
20099 On a clock timestamp, update the value of the timestamp like `S-<down>'
20100 but also adjust the previous clocked item in the clock history.
20101 Everywhere else, drag the line at point down."
20104 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20105 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20106 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20107 (call-interactively 'org-timestamp-down)))
20108 (t (call-interactively 'org-drag-line-forward))))
20110 (defsubst org-hidden-tree-error ()
20112 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20114 (defun org-metaleft (&optional arg)
20115 "Promote heading or move table column to left.
20116 Calls `org-do-promote' or `org-table-move-column', depending on context.
20117 With no specific context, calls the Emacs default `backward-word'.
20118 See the individual commands for more information."
20121 ((run-hook-with-args-until-success 'org-metaleft-hook))
20122 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20123 ((org-with-limited-levels
20124 (or (org-at-heading-p)
20125 (and (org-region-active-p)
20127 (goto-char (region-beginning))
20128 (org-at-heading-p)))))
20129 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20130 (call-interactively 'org-do-promote))
20131 ;; At an inline task.
20132 ((org-at-heading-p)
20133 (call-interactively 'org-inlinetask-promote))
20134 ((or (org-at-item-p)
20135 (and (org-region-active-p)
20137 (goto-char (region-beginning))
20139 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20140 (call-interactively 'org-outdent-item))
20141 (t (call-interactively 'backward-word))))
20143 (defun org-metaright (&optional arg)
20144 "Demote a subtree, a list item or move table column to right.
20145 In front of a drawer or a block keyword, indent it correctly.
20146 With no specific context, calls the Emacs default `forward-word'.
20147 See the individual commands for more information."
20150 ((run-hook-with-args-until-success 'org-metaright-hook))
20151 ((org-at-table-p) (call-interactively 'org-table-move-column))
20152 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20153 ((org-at-block-p) (call-interactively 'org-indent-block))
20154 ((org-with-limited-levels
20155 (or (org-at-heading-p)
20156 (and (org-region-active-p)
20158 (goto-char (region-beginning))
20159 (org-at-heading-p)))))
20160 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20161 (call-interactively 'org-do-demote))
20162 ;; At an inline task.
20163 ((org-at-heading-p)
20164 (call-interactively 'org-inlinetask-demote))
20165 ((or (org-at-item-p)
20166 (and (org-region-active-p)
20168 (goto-char (region-beginning))
20170 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20171 (call-interactively 'org-indent-item))
20172 (t (call-interactively 'forward-word))))
20174 (defun org-check-for-hidden (what)
20175 "Check if there are hidden headlines/items in the current visual line.
20176 WHAT can be either `headlines' or `items'. If the current line is
20177 an outline or item heading and it has a folded subtree below it,
20178 this function returns t, nil otherwise."
20180 ((eq what 'headlines) org-outline-regexp-bol)
20181 ((eq what 'items) (org-item-beginning-re))
20182 (t (error "This should not happen"))))
20186 (unless (org-region-active-p)
20187 (setq beg (point-at-bol))
20188 (beginning-of-line 2)
20189 (while (and (not (eobp)) ;; this is like `next-line'
20190 (get-char-property (1- (point)) 'invisible))
20191 (beginning-of-line 2))
20194 (goto-char (point-at-eol))
20195 (setq end (max end (point)))
20196 (while (re-search-forward re end t)
20197 (if (get-char-property (match-beginning 0) 'invisible)
20201 (defun org-metaup (&optional arg)
20202 "Move subtree up or move table row up.
20203 Calls `org-move-subtree-up' or `org-table-move-row' or
20204 `org-move-item-up', depending on context. See the individual commands
20205 for more information."
20208 ((run-hook-with-args-until-success 'org-metaup-hook))
20209 ((org-region-active-p)
20210 (let* ((a (min (region-beginning) (region-end)))
20211 (b (1- (max (region-beginning) (region-end))))
20212 (c (save-excursion (goto-char a)
20213 (move-beginning-of-line 0)))
20214 (d (save-excursion (goto-char a)
20215 (move-end-of-line 0) (point))))
20216 (transpose-regions a b c d)
20218 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20219 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20220 ((org-at-item-p) (call-interactively 'org-move-item-up))
20221 (t (org-drag-element-backward))))
20223 (defun org-metadown (&optional arg)
20224 "Move subtree down or move table row down.
20225 Calls `org-move-subtree-down' or `org-table-move-row' or
20226 `org-move-item-down', depending on context. See the individual
20227 commands for more information."
20230 ((run-hook-with-args-until-success 'org-metadown-hook))
20231 ((org-region-active-p)
20232 (let* ((a (min (region-beginning) (region-end)))
20233 (b (max (region-beginning) (region-end)))
20234 (c (save-excursion (goto-char b)
20235 (move-beginning-of-line 1)))
20236 (d (save-excursion (goto-char b)
20237 (move-end-of-line 1) (1+ (point)))))
20238 (transpose-regions a b c d)
20240 ((org-at-table-p) (call-interactively 'org-table-move-row))
20241 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20242 ((org-at-item-p) (call-interactively 'org-move-item-down))
20243 (t (org-drag-element-forward))))
20245 (defun org-shiftup (&optional arg)
20246 "Increase item in timestamp or increase priority of current headline.
20247 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20248 depending on context. See the individual commands for more information."
20251 ((run-hook-with-args-until-success 'org-shiftup-hook))
20252 ((and org-support-shift-select (org-region-active-p))
20253 (org-call-for-shift-select 'previous-line))
20254 ((org-at-timestamp-p t)
20255 (call-interactively (if org-edit-timestamp-down-means-later
20256 'org-timestamp-down 'org-timestamp-up)))
20257 ((and (not (eq org-support-shift-select 'always))
20258 org-enable-priority-commands
20259 (org-at-heading-p))
20260 (call-interactively 'org-priority-up))
20261 ((and (not org-support-shift-select) (org-at-item-p))
20262 (call-interactively 'org-previous-item))
20263 ((org-clocktable-try-shift 'up arg))
20264 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20265 (org-support-shift-select
20266 (org-call-for-shift-select 'previous-line))
20267 (t (org-shiftselect-error))))
20269 (defun org-shiftdown (&optional arg)
20270 "Decrease item in timestamp or decrease priority of current headline.
20271 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20272 depending on context. See the individual commands for more information."
20275 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20276 ((and org-support-shift-select (org-region-active-p))
20277 (org-call-for-shift-select 'next-line))
20278 ((org-at-timestamp-p t)
20279 (call-interactively (if org-edit-timestamp-down-means-later
20280 'org-timestamp-up 'org-timestamp-down)))
20281 ((and (not (eq org-support-shift-select 'always))
20282 org-enable-priority-commands
20283 (org-at-heading-p))
20284 (call-interactively 'org-priority-down))
20285 ((and (not org-support-shift-select) (org-at-item-p))
20286 (call-interactively 'org-next-item))
20287 ((org-clocktable-try-shift 'down arg))
20288 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20289 (org-support-shift-select
20290 (org-call-for-shift-select 'next-line))
20291 (t (org-shiftselect-error))))
20293 (defun org-shiftright (&optional arg)
20294 "Cycle the thing at point or in the current line, depending on context.
20295 Depending on context, this does one of the following:
20297 - switch a timestamp at point one day into the future
20298 - on a headline, switch to the next TODO keyword.
20299 - on an item, switch entire list to the next bullet type
20300 - on a property line, switch to the next allowed value
20301 - on a clocktable definition line, move time block into the future"
20304 ((run-hook-with-args-until-success 'org-shiftright-hook))
20305 ((and org-support-shift-select (org-region-active-p))
20306 (org-call-for-shift-select 'forward-char))
20307 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20308 ((and (not (eq org-support-shift-select 'always))
20309 (org-at-heading-p))
20310 (let ((org-inhibit-logging
20311 (not org-treat-S-cursor-todo-selection-as-state-change))
20312 (org-inhibit-blocking
20313 (not org-treat-S-cursor-todo-selection-as-state-change)))
20314 (org-call-with-arg 'org-todo 'right)))
20315 ((or (and org-support-shift-select
20316 (not (eq org-support-shift-select 'always))
20317 (org-at-item-bullet-p))
20318 (and (not org-support-shift-select) (org-at-item-p)))
20319 (org-call-with-arg 'org-cycle-list-bullet nil))
20320 ((and (not (eq org-support-shift-select 'always))
20321 (org-at-property-p))
20322 (call-interactively 'org-property-next-allowed-value))
20323 ((org-clocktable-try-shift 'right arg))
20324 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20325 (org-support-shift-select
20326 (org-call-for-shift-select 'forward-char))
20327 (t (org-shiftselect-error))))
20329 (defun org-shiftleft (&optional arg)
20330 "Cycle the thing at point or in the current line, depending on context.
20331 Depending on context, this does one of the following:
20333 - switch a timestamp at point one day into the past
20334 - on a headline, switch to the previous TODO keyword.
20335 - on an item, switch entire list to the previous bullet type
20336 - on a property line, switch to the previous allowed value
20337 - on a clocktable definition line, move time block into the past"
20340 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20341 ((and org-support-shift-select (org-region-active-p))
20342 (org-call-for-shift-select 'backward-char))
20343 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20344 ((and (not (eq org-support-shift-select 'always))
20345 (org-at-heading-p))
20346 (let ((org-inhibit-logging
20347 (not org-treat-S-cursor-todo-selection-as-state-change))
20348 (org-inhibit-blocking
20349 (not org-treat-S-cursor-todo-selection-as-state-change)))
20350 (org-call-with-arg 'org-todo 'left)))
20351 ((or (and org-support-shift-select
20352 (not (eq org-support-shift-select 'always))
20353 (org-at-item-bullet-p))
20354 (and (not org-support-shift-select) (org-at-item-p)))
20355 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20356 ((and (not (eq org-support-shift-select 'always))
20357 (org-at-property-p))
20358 (call-interactively 'org-property-previous-allowed-value))
20359 ((org-clocktable-try-shift 'left arg))
20360 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20361 (org-support-shift-select
20362 (org-call-for-shift-select 'backward-char))
20363 (t (org-shiftselect-error))))
20365 (defun org-shiftcontrolright ()
20366 "Switch to next TODO set."
20369 ((and org-support-shift-select (org-region-active-p))
20370 (org-call-for-shift-select 'forward-word))
20371 ((and (not (eq org-support-shift-select 'always))
20372 (org-at-heading-p))
20373 (org-call-with-arg 'org-todo 'nextset))
20374 (org-support-shift-select
20375 (org-call-for-shift-select 'forward-word))
20376 (t (org-shiftselect-error))))
20378 (defun org-shiftcontrolleft ()
20379 "Switch to previous TODO set."
20382 ((and org-support-shift-select (org-region-active-p))
20383 (org-call-for-shift-select 'backward-word))
20384 ((and (not (eq org-support-shift-select 'always))
20385 (org-at-heading-p))
20386 (org-call-with-arg 'org-todo 'previousset))
20387 (org-support-shift-select
20388 (org-call-for-shift-select 'backward-word))
20389 (t (org-shiftselect-error))))
20391 (defun org-shiftcontrolup (&optional n)
20392 "Change timestamps synchronously up in CLOCK log lines.
20393 Optional argument N tells to change by that many units."
20395 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20396 (let (org-support-shift-select)
20397 (org-clock-timestamps-up n))
20398 (user-error "Not at a clock log")))
20400 (defun org-shiftcontroldown (&optional n)
20401 "Change timestamps synchronously down in CLOCK log lines.
20402 Optional argument N tells to change by that many units."
20404 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20405 (let (org-support-shift-select)
20406 (org-clock-timestamps-down n))
20407 (user-error "Not at a clock log")))
20409 (defun org-increase-number-at-point (&optional inc)
20410 "Increment the number at point.
20411 With an optional prefix numeric argument INC, increment using
20412 this numeric value."
20414 (if (not (number-at-point))
20415 (user-error "Not on a number")
20416 (unless inc (setq inc 1))
20417 (let ((pos (point))
20418 (beg (skip-chars-backward "-+^/*0-9eE."))
20419 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20420 (setq nap (buffer-substring-no-properties
20421 (+ pos beg) (+ pos beg end)))
20422 (delete-region (+ pos beg) (+ pos beg end))
20423 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20424 (when (org-at-table-p)
20426 (org-table-end-of-field 1))))
20428 (defun org-decrease-number-at-point (&optional inc)
20429 "Decrement the number at point.
20430 With an optional prefix numeric argument INC, decrement using
20431 this numeric value."
20433 (org-increase-number-at-point (- inc)))
20435 (defun org-ctrl-c-ret ()
20436 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20439 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20440 (t (call-interactively 'org-insert-heading))))
20442 (defun org-find-visible ()
20444 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20445 (get-char-property s 'invisible)))
20447 (defun org-find-invisible ()
20449 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20450 (not (get-char-property s 'invisible))))
20453 (defun org-copy-visible (beg end)
20454 "Copy the visible parts of the region."
20459 (narrow-to-region beg end)
20460 (setq s (goto-char (point-min)))
20461 (while (not (= (point) (point-max)))
20462 (goto-char (org-find-invisible))
20463 (push (buffer-substring s (point)) snippets)
20464 (setq s (goto-char (org-find-visible))))))
20465 (kill-new (apply 'concat (nreverse snippets)))))
20467 (defun org-copy-special ()
20468 "Copy region in table or copy current subtree.
20469 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20470 See the individual commands for more information."
20472 (call-interactively
20473 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20475 (defun org-cut-special ()
20476 "Cut region in table or cut current subtree.
20477 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20478 See the individual commands for more information."
20480 (call-interactively
20481 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20483 (defun org-paste-special (arg)
20484 "Paste rectangular region into table, or past subtree relative to level.
20485 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20486 See the individual commands for more information."
20488 (if (org-at-table-p)
20489 (org-table-paste-rectangle)
20490 (org-paste-subtree arg)))
20492 (defsubst org-in-fixed-width-region-p ()
20493 "Is point in a fixed-width region?"
20495 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20497 (defun org-edit-special (&optional arg)
20498 "Call a special editor for the element at point.
20499 When at a table, call the formula editor with `org-table-edit-formulas'.
20500 When in a source code block, call `org-edit-src-code'.
20501 When in a fixed-width region, call `org-edit-fixed-width-region'.
20502 When at an #+INCLUDE keyword, visit the included file.
20503 On a link, call `ffap' to visit the link at point.
20504 Otherwise, return a user error."
20506 (let ((element (org-element-at-point)))
20507 (assert (not buffer-read-only) nil
20508 "Buffer is read-only: %s" (buffer-name))
20509 (case (org-element-type element)
20511 (if (not arg) (org-edit-src-code)
20512 (let* ((info (org-babel-get-src-block-info))
20513 (lang (nth 0 info))
20514 (params (nth 2 info))
20515 (session (cdr (assq :session params))))
20516 (if (not session) (org-edit-src-code)
20517 ;; At a src-block with a session and function called with
20518 ;; an ARG: switch to the buffer related to the inferior
20521 (funcall (intern (concat "org-babel-prep-session:" lang))
20522 session params))))))
20524 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20525 (find-file-other-window
20526 (org-remove-double-quotes
20527 (car (org-split-string (org-element-property :value element)))))
20528 (user-error "No special environment to edit here")))
20530 (if (eq (org-element-property :type element) 'table.el)
20531 (org-edit-src-code)
20532 (call-interactively 'org-table-edit-formulas)))
20533 ;; Only Org tables contain `table-row' type elements.
20534 (table-row (call-interactively 'org-table-edit-formulas))
20535 ((example-block export-block) (org-edit-src-code))
20536 (fixed-width (org-edit-fixed-width-region))
20538 ;; No notable element at point. Though, we may be at a link,
20539 ;; which is an object. Thus, scan deeper.
20540 (if (eq (org-element-type (org-element-context element)) 'link)
20541 (call-interactively 'ffap)
20542 (user-error "No special environment to edit here"))))))
20544 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20545 (defun org-ctrl-c-ctrl-c (&optional arg)
20546 "Set tags in headline, or update according to changed information at point.
20548 This command does many different things, depending on context:
20550 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20551 this is what we do.
20553 - If the cursor is on a statistics cookie, update it.
20555 - If the cursor is in a headline, prompt for tags and insert them
20556 into the current line, aligned to `org-tags-column'. When called
20557 with prefix arg, realign all tags in the current buffer.
20559 - If the cursor is in one of the special #+KEYWORD lines, this
20560 triggers scanning the buffer for these lines and updating the
20563 - If the cursor is inside a table, realign the table. This command
20564 works even if the automatic table editor has been turned off.
20566 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20569 - If the cursor is at a footnote reference or definition, jump to
20570 the corresponding definition or references, respectively.
20572 - If the cursor is a the beginning of a dynamic block, update it.
20574 - If the current buffer is a capture buffer, close note and file it.
20576 - If the cursor is on a <<<target>>>, update radio targets and
20577 corresponding links in this buffer.
20579 - If the cursor is on a numbered item in a plain list, renumber the
20582 - If the cursor is on a checkbox, toggle it.
20584 - If the cursor is on a code block, evaluate it. The variable
20585 `org-confirm-babel-evaluate' can be used to control prompting
20586 before code block evaluation, by default every code block
20587 evaluation requires confirmation. Code block evaluation can be
20588 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20591 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20592 org-occur-highlights)
20593 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20594 (org-remove-occur-highlights)
20595 (message "Temporary highlights/overlays removed from current buffer"))
20596 ((and (local-variable-p 'org-finish-function (current-buffer))
20597 (fboundp org-finish-function))
20598 (funcall org-finish-function))
20599 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20601 (let* ((context (org-element-context)) (type (org-element-type context)))
20602 ;; Test if point is within a blank line.
20603 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20604 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20605 (user-error "C-c C-c can do nothing useful at this location"))
20607 ;; When at a link, act according to the parent instead.
20608 (link (setq context (org-element-property :parent context))
20609 (setq type (org-element-type context)))
20610 ;; Unsupported object types: refer to the first supported
20611 ;; element or object containing it.
20612 ((bold code entity export-snippet inline-babel-call inline-src-block
20613 italic latex-fragment line-break macro strike-through subscript
20614 superscript underline verbatim)
20615 (while (and (setq context (org-element-property :parent context))
20616 (not (memq (setq type (org-element-type context))
20617 '(radio-target paragraph verse-block
20619 ;; For convenience: at the first line of a paragraph on the
20620 ;; same line as an item, apply function on that item instead.
20621 (when (eq type 'paragraph)
20622 (let ((parent (org-element-property :parent context)))
20623 (when (and (eq (org-element-type parent) 'item)
20624 (= (point-at-bol) (org-element-property :begin parent)))
20625 (setq context parent type 'item))))
20626 ;; Act according to type of element or object at point.
20628 (clock (org-clock-update-time-maybe))
20631 (goto-char (org-element-property :post-affiliated context))
20632 (org-update-dblock)))
20633 (footnote-definition
20634 (goto-char (org-element-property :post-affiliated context))
20635 (call-interactively 'org-footnote-action))
20636 (footnote-reference (call-interactively 'org-footnote-action))
20637 ((headline inlinetask)
20638 (save-excursion (goto-char (org-element-property :begin context))
20639 (call-interactively 'org-set-tags)))
20641 ;; At an item: a double C-u set checkbox to "[-]"
20642 ;; unconditionally, whereas a single one will toggle its
20643 ;; presence. Without an universal argument, if the item
20644 ;; has a checkbox, toggle it. Otherwise repair the list.
20645 (let* ((box (org-element-property :checkbox context))
20646 (struct (org-element-property :structure context))
20647 (old-struct (copy-tree struct))
20648 (parents (org-list-parents-alist struct))
20649 (prevs (org-list-prevs-alist struct))
20650 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20651 (org-list-set-checkbox
20652 (org-element-property :begin context) struct
20653 (cond ((equal arg '(16)) "[-]")
20654 ((and (not box) (equal arg '(4))) "[ ]")
20655 ((or (not box) (equal arg '(4))) nil)
20656 ((eq box 'on) "[ ]")
20658 ;; Mimic `org-list-write-struct' but with grabbing
20659 ;; a return value from `org-list-struct-fix-box'.
20660 (org-list-struct-fix-ind struct parents 2)
20661 (org-list-struct-fix-item-end struct)
20662 (org-list-struct-fix-bul struct prevs)
20663 (org-list-struct-fix-ind struct parents)
20665 (org-list-struct-fix-box struct parents prevs orderedp)))
20666 (if (and box (equal struct old-struct))
20667 (if (equal arg '(16))
20668 (message "Checkboxes already reset")
20669 (user-error "Cannot toggle this checkbox: %s"
20671 "all subitems checked"
20672 "unchecked subitems")))
20673 (org-list-struct-apply-struct struct old-struct)
20674 (org-update-checkbox-count-maybe))
20676 (message "Checkboxes were removed due to empty box at line %d"
20677 (org-current-line block-item))))))
20679 (let ((org-inhibit-startup-visibility-stuff t)
20680 (org-startup-align-all-tables nil))
20681 (when (boundp 'org-table-coordinate-overlays)
20682 (mapc 'delete-overlay org-table-coordinate-overlays)
20683 (setq org-table-coordinate-overlays nil))
20684 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20685 (message "Local setup has been refreshed"))
20687 ;; At a plain list, with a double C-u argument, set
20688 ;; checkboxes of each item to "[-]", whereas a single one
20689 ;; will toggle their presence according to the state of the
20690 ;; first item in the list. Without an argument, repair the
20692 (let* ((begin (org-element-property :contents-begin context))
20693 (beginm (move-marker (make-marker) begin))
20694 (struct (org-element-property :structure context))
20695 (old-struct (copy-tree struct))
20696 (first-box (save-excursion
20698 (looking-at org-list-full-item-re)
20699 (match-string-no-properties 3)))
20700 (new-box (cond ((equal arg '(16)) "[-]")
20701 ((equal arg '(4)) (unless first-box "[ ]"))
20702 ((equal first-box "[X]") "[ ]")
20706 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20707 (org-list-get-all-items
20708 begin struct (org-list-prevs-alist struct))))
20709 ((and first-box (eq (point) begin))
20710 ;; For convenience, when point is at bol on the first
20711 ;; item of the list and no argument is provided, simply
20712 ;; toggle checkbox of that item, if any.
20713 (org-list-set-checkbox begin struct new-box)))
20714 (org-list-write-struct
20715 struct (org-list-parents-alist struct) old-struct)
20716 (org-update-checkbox-count-maybe)
20717 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20718 ((property-drawer node-property)
20719 (call-interactively 'org-property-action))
20720 ((radio-target target)
20721 (call-interactively 'org-update-radio-target-regexp))
20723 (call-interactively 'org-update-statistics-cookies))
20724 ((table table-cell table-row)
20725 ;; At a table, recalculate every field and align it. Also
20726 ;; send the table if necessary. If the table has
20727 ;; a `table.el' type, just give up. At a table row or
20728 ;; cell, maybe recalculate line but always align table.
20729 (if (eq (org-element-property :type context) 'table.el)
20730 (message "Use C-c ' to edit table.el tables")
20731 (let ((org-enable-table-editor t))
20732 (if (or (eq type 'table)
20733 ;; Check if point is at a TBLFM line.
20734 (and (eq type 'table-row)
20735 (= (point) (org-element-property :end context))))
20737 (if (org-at-TBLFM-p)
20738 (progn (require 'org-table)
20739 (org-table-calc-current-TBLFM))
20740 (goto-char (org-element-property :contents-begin context))
20741 (org-call-with-arg 'org-table-recalculate (or arg t))
20742 (orgtbl-send-table 'maybe)))
20743 (org-table-maybe-eval-formula)
20744 (cond (arg (call-interactively 'org-table-recalculate))
20745 ((org-table-maybe-recalculate-line))
20746 (t (org-table-align)))))))
20747 (timestamp (org-timestamp-change 0 'day))
20749 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20751 "C-c C-c can do nothing useful at this location")))))))))
20753 (defun org-mode-restart ()
20755 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20756 (funcall major-mode)
20757 (hack-local-variables)
20758 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20759 (org-indent-mode -1)))
20760 (message "%s restarted" major-mode))
20762 (defun org-kill-note-or-show-branches ()
20763 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20765 (if (not org-finish-function)
20768 (call-interactively 'show-branches))
20769 (let ((org-note-abort t))
20770 (funcall org-finish-function))))
20772 (defun org-open-line (n)
20773 "Insert a new row in tables, call `open-line' elsewhere.
20774 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20777 ((not org-special-ctrl-o)
20780 (org-table-insert-row))
20784 (defun org-return (&optional indent)
20785 "Goto next table row or insert a newline.
20786 Calls `org-table-next-row' or `newline', depending on context.
20787 See the individual commands for more information."
20791 ((or (bobp) (org-in-src-block-p))
20792 (if indent (newline-and-indent) (newline)))
20794 (org-table-justify-field-maybe)
20795 (call-interactively 'org-table-next-row))
20796 ;; when `newline-and-indent' is called within a list, make sure
20797 ;; text moved stays inside the item.
20798 ((and (org-in-item-p) indent)
20799 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20801 (save-match-data (newline))
20802 (org-indent-line-to (length (match-string 0))))
20803 (let ((ind (org-get-indentation)))
20805 (if (org-looking-back org-list-end-re)
20807 (org-indent-line-to ind)))))
20808 ((and org-return-follows-link
20809 (org-at-timestamp-p t)
20810 (not (eq org-ts-what 'after)))
20811 (org-follow-timestamp-link))
20812 ((and org-return-follows-link
20813 (let ((tprop (get-text-property (point) 'face)))
20814 (or (eq tprop 'org-link)
20815 (and (listp tprop) (memq 'org-link tprop)))))
20816 (call-interactively 'org-open-at-point))
20817 ((and (org-at-heading-p)
20819 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20823 (t (if indent (newline-and-indent) (newline))))))
20825 (defun org-return-indent ()
20826 "Goto next table row or insert a newline and indent.
20827 Calls `org-table-next-row' or `newline-and-indent', depending on
20828 context. See the individual commands for more information."
20832 (defun org-ctrl-c-star ()
20833 "Compute table, or change heading status of lines.
20834 Calls `org-table-recalculate' or `org-toggle-heading',
20835 depending on context."
20839 (call-interactively 'org-table-recalculate))
20841 ;; Convert all lines in region to list items
20842 (call-interactively 'org-toggle-heading))))
20844 (defun org-ctrl-c-minus ()
20845 "Insert separator line in table or modify bullet status of line.
20846 Also turns a plain line or a region of lines into list items.
20847 Calls `org-table-insert-hline', `org-toggle-item', or
20848 `org-cycle-list-bullet', depending on context."
20852 (call-interactively 'org-table-insert-hline))
20853 ((org-region-active-p)
20854 (call-interactively 'org-toggle-item))
20856 (call-interactively 'org-cycle-list-bullet))
20858 (call-interactively 'org-toggle-item))))
20860 (defun org-toggle-item (arg)
20861 "Convert headings or normal lines to items, items to normal lines.
20862 If there is no active region, only the current line is considered.
20864 If the first non blank line in the region is a headline, convert
20865 all headlines to items, shifting text accordingly.
20867 If it is an item, convert all items to normal lines.
20869 If it is normal text, change region into a list of items.
20870 With a prefix argument ARG, change the region in a single item."
20874 ;; Shift text in current section to IND, from point to END.
20875 ;; The function leaves point to END line.
20877 (let ((min-i 1000) (end (copy-marker end)))
20878 ;; First determine the minimum indentation (MIN-I) of
20882 (while (< (point) end)
20883 (let ((i (org-get-indentation)))
20885 ;; Skip blank lines and inline tasks.
20886 ((looking-at "^[ \t]*$"))
20887 ((looking-at org-outline-regexp-bol))
20888 ;; We can't find less than 0 indentation.
20889 ((zerop i) (throw 'exit (setq min-i 0)))
20890 ((< i min-i) (setq min-i i))))
20892 ;; Then indent each line so that a line indented to
20893 ;; MIN-I becomes indented to IND. Ignore blank lines
20894 ;; and inline tasks in the process.
20895 (let ((delta (- ind min-i)))
20896 (while (< (point) end)
20897 (unless (or (looking-at "^[ \t]*$")
20898 (looking-at org-outline-regexp-bol))
20899 (org-indent-line-to (+ (org-get-indentation) delta)))
20900 (forward-line)))))))
20903 ;; Return beginning of first non-blank line, starting from
20908 (skip-chars-forward " \r\t\n")
20911 ;; Determine boundaries of changes.
20912 (if (org-region-active-p)
20913 (setq beg (funcall skip-blanks (region-beginning))
20914 end (copy-marker (region-end)))
20915 (setq beg (funcall skip-blanks (point-at-bol))
20916 end (copy-marker (point-at-eol))))
20917 ;; Depending on the starting line, choose an action on the text
20918 ;; between BEG and END.
20919 (org-with-limited-levels
20923 ;; Case 1. Start at an item: de-itemize. Note that it only
20924 ;; happens when a region is active: `org-ctrl-c-minus'
20925 ;; would call `org-cycle-list-bullet' otherwise.
20927 (while (< (point) end)
20928 (when (org-at-item-p)
20929 (skip-chars-forward " \t")
20930 (delete-region (point) (match-end 0)))
20932 ;; Case 2. Start at an heading: convert to items.
20933 ((org-at-heading-p)
20934 (let* ((bul (org-list-bullet-string "-"))
20935 (bul-len (length bul))
20936 (done (org-entry-is-done-p))
20937 (todo (org-entry-is-todo-p))
20938 ;; Indentation of the first heading. It should be
20939 ;; relative to the indentation of its parent, if any.
20940 (start-ind (save-excursion
20942 ((not org-adapt-indentation) 0)
20943 ((not (outline-previous-heading)) 0)
20944 (t (length (match-string 0))))))
20945 ;; Level of first heading. Further headings will be
20946 ;; compared to it to determine hierarchy in the list.
20947 (ref-level (org-reduced-level (org-outline-level))))
20948 (when (or done todo) (org-todo ""))
20949 (while (< (point) end)
20950 (let* ((level (org-reduced-level (org-outline-level)))
20951 (delta (max 0 (- level ref-level))))
20952 ;; If current headline is less indented than the first
20953 ;; one, set it as reference, in order to preserve
20955 (when (< level ref-level) (setq ref-level level))
20956 (replace-match bul t t)
20957 (org-indent-line-to (+ start-ind (* delta bul-len)))
20958 (when (or done todo)
20959 (let* ((struct (org-list-struct))
20960 (old (copy-tree struct)))
20961 (org-list-set-checkbox (line-beginning-position)
20963 (if done "[X]" "[ ]"))
20964 (org-list-write-struct struct
20965 (org-list-parents-alist struct)
20967 ;; Ensure all text down to END (or SECTION-END) belongs
20968 ;; to the newly created item.
20969 (let ((section-end (save-excursion
20970 (or (outline-next-heading) (point)))))
20972 (funcall shift-text
20973 (+ start-ind (* (1+ delta) bul-len))
20974 (min end section-end)))))))
20975 ;; Case 3. Normal line with ARG: make the first line of region
20976 ;; an item, and shift indentation of others lines to
20977 ;; set them as item's body.
20978 (arg (let* ((bul (org-list-bullet-string "-"))
20979 (bul-len (length bul))
20980 (ref-ind (org-get-indentation)))
20981 (skip-chars-forward " \t")
20984 (while (< (point) end)
20985 ;; Ensure that lines less indented than first one
20986 ;; still get included in item body.
20987 (funcall shift-text
20988 (+ ref-ind bul-len)
20989 (min end (save-excursion (or (outline-next-heading)
20992 ;; Case 4. Normal line without ARG: turn each non-item line
20995 (while (< (point) end)
20996 (unless (or (org-at-heading-p) (org-at-item-p))
20997 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20999 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21000 (forward-line))))))))
21002 (defun org-toggle-heading (&optional nstars)
21003 "Convert headings to normal text, or items or text to headings.
21004 If there is no active region, only convert the current line.
21006 With a \\[universal-argument] prefix, convert the whole list at
21007 point into heading.
21011 - If the first non blank line is a headline, remove the stars
21012 from all headlines in the region.
21014 - If it is a normal line, turn each and every normal line (i.e.,
21015 not an heading or an item) in the region into headings. If you
21016 want to convert only the first line of this region, use one
21017 universal prefix argument.
21019 - If it is a plain list item, turn all plain list items into headings.
21021 When converting a line into a heading, the number of stars is chosen
21022 such that the lines become children of the current entry. However,
21023 when a numeric prefix argument is given, its value determines the
21024 number of stars to add."
21028 ;; Return beginning of first non-blank line, starting from
21033 (while (org-at-comment-p) (forward-line))
21034 (skip-chars-forward " \r\t\n")
21037 ;; Determine boundaries of changes. If a universal prefix has
21038 ;; been given, put the list in a region. If region ends at a bol,
21039 ;; do not consider the last line to be in the region.
21041 (when (and current-prefix-arg (org-at-item-p))
21042 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
21043 (org-mark-element))
21045 (if (org-region-active-p)
21046 (setq beg (funcall skip-blanks (region-beginning))
21047 end (copy-marker (save-excursion
21048 (goto-char (region-end))
21049 (if (bolp) (point) (point-at-eol)))))
21050 (setq beg (funcall skip-blanks (point-at-bol))
21051 end (copy-marker (point-at-eol))))
21052 ;; Ensure inline tasks don't count as headings.
21053 (org-with-limited-levels
21057 ;; Case 1. Started at an heading: de-star headings.
21058 ((org-at-heading-p)
21059 (while (< (point) end)
21060 (when (org-at-heading-p t)
21061 (looking-at org-outline-regexp) (replace-match "")
21064 ;; Case 2. Started at an item: change items into headlines.
21065 ;; One star will be added by `org-list-to-subtree'.
21067 (let* ((stars (make-string
21068 ;; subtract the star that will be added again by
21069 ;; `org-list-to-subtree'
21070 (if (numberp nstars) (1- nstars)
21071 (or (org-current-level) 0))
21074 (cond (nstars "") ; stars from prefix only
21075 ((equal stars "") "") ; before first heading
21076 (org-odd-levels-only "*") ; inside heading, odd
21077 (t "")))) ; inside heading, oddeven
21078 (while (< (point) end)
21079 (when (org-at-item-p)
21080 ;; Pay attention to cases when region ends before list.
21081 (let* ((struct (org-list-struct))
21082 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
21084 (narrow-to-region (point) list-end)
21086 (org-list-to-subtree
21087 (org-list-parse-list t)
21088 '(:istart (concat stars add-stars (funcall get-stars depth))
21089 :icount (concat stars add-stars (funcall get-stars depth)))))))
21092 ;; Case 3. Started at normal text: make every line an heading,
21093 ;; skipping headlines and items.
21096 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21098 (cond (nstars "") ; stars from prefix only
21099 ((equal stars "") "*") ; before first heading
21100 (org-odd-levels-only "**") ; inside heading, odd
21101 (t "*"))) ; inside heading, oddeven
21102 (rpl (concat stars add-stars " "))
21103 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
21104 (while (< (point) (if (equal nstars '(4)) lend end))
21105 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21106 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21107 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21108 (forward-line)))))))
21109 (unless toggled (message "Cannot toggle heading from here"))))
21111 (defun org-meta-return (&optional arg)
21112 "Insert a new heading or wrap a region in a table.
21113 Calls `org-insert-heading' or `org-table-wrap-region', depending
21114 on context. See the individual commands for more information."
21116 (org-check-before-invisible-edit 'insert)
21117 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21118 (let* ((element (org-element-at-point))
21119 (type (org-element-type element)))
21120 (when (eq type 'table-row)
21121 (setq element (org-element-property :parent element))
21122 (setq type 'table))
21123 (if (and (eq type 'table)
21124 (eq (org-element-property :type element) 'org)
21125 (>= (point) (org-element-property :contents-begin element))
21126 (< (point) (org-element-property :contents-end element)))
21127 (call-interactively 'org-table-wrap-region)
21128 (call-interactively 'org-insert-heading)))))
21132 (defsubst org-in-subtree-not-table-p ()
21133 "Are we in a subtree and not in a table?"
21134 (and (not (org-before-first-heading-p))
21135 (not (org-at-table-p))))
21137 ;; Define the Org-mode menus
21138 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21140 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21141 ["Next Field" org-cycle (org-at-table-p)]
21142 ["Previous Field" org-shifttab (org-at-table-p)]
21143 ["Next Row" org-return (org-at-table-p)]
21145 ["Blank Field" org-table-blank-field (org-at-table-p)]
21146 ["Edit Field" org-table-edit-field (org-at-table-p)]
21147 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21150 ["Move Column Left" org-metaleft (org-at-table-p)]
21151 ["Move Column Right" org-metaright (org-at-table-p)]
21152 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21153 ["Insert Column" org-shiftmetaright (org-at-table-p)]
21154 ["Ascii plot" orgtbl-ascii-plot (org-at-table-p)])
21156 ["Move Row Up" org-metaup (org-at-table-p)]
21157 ["Move Row Down" org-metadown (org-at-table-p)]
21158 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21159 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21160 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21162 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21164 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21165 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21166 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21167 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21170 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21171 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21172 ["Edit Formulas" org-edit-special (org-at-table-p)]
21174 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21175 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21176 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21178 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21180 ["Sum Column/Rectangle" org-table-sum
21181 (or (org-at-table-p) (org-region-active-p))]
21182 ["Which Column?" org-table-current-column (org-at-table-p)])
21184 org-table-toggle-formula-debugger
21185 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21186 ["Show Col/Row Numbers"
21187 org-table-toggle-coordinate-overlays
21189 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21191 ["Create" org-table-create (and (not (org-at-table-p))
21192 org-enable-table-editor)]
21193 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21194 ["Import from File" org-table-import (not (org-at-table-p))]
21195 ["Export to File" org-table-export (org-at-table-p)]
21197 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
21199 (easy-menu-define org-org-menu org-mode-map "Org menu"
21202 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21203 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21204 ["Sparse Tree..." org-sparse-tree t]
21205 ["Reveal Context" org-reveal t]
21206 ["Show All" show-all t]
21208 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21210 ["New Heading" org-insert-heading t]
21211 ("Navigate Headings"
21212 ["Up" outline-up-heading t]
21213 ["Next" outline-next-visible-heading t]
21214 ["Previous" outline-previous-visible-heading t]
21215 ["Next Same Level" outline-forward-same-level t]
21216 ["Previous Same Level" outline-backward-same-level t]
21218 ["Jump" org-goto t])
21220 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21222 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
21223 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
21225 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21226 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21227 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21229 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21231 ["Copy visible text" org-copy-visible t]
21233 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21234 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21235 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21236 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21238 ["Sort Region/Children" org-sort t]
21240 ["Convert to odd levels" org-convert-to-odd-levels t]
21241 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21243 ["Emphasis..." org-emphasize t]
21244 ["Edit Source Example" org-edit-special t]
21246 ["Footnote new/jump" org-footnote-action t]
21247 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21249 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21251 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21252 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21253 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21257 ["Store Link (Global)" org-store-link t]
21258 ["Find existing link to here" org-occur-link-in-agenda-files t]
21259 ["Insert Link" org-insert-link t]
21260 ["Follow Link" org-open-at-point t]
21262 ["Next link" org-next-link t]
21263 ["Previous link" org-previous-link t]
21265 ["Descriptive Links"
21266 org-toggle-link-display
21268 :selected org-descriptive-links
21271 org-toggle-link-display
21273 :selected (not org-descriptive-links)])
21276 ["TODO/DONE/-" org-todo t]
21278 ["Next keyword" org-shiftright (org-at-heading-p)]
21279 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21280 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21281 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21282 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21283 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21284 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21286 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21287 :selected org-enforce-todo-dependencies :style toggle :active t]
21288 "Settings for tree at point"
21289 ["Do Children sequentially" org-toggle-ordered-property :style radio
21290 :selected (org-entry-get nil "ORDERED")
21291 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21292 ["Do Children parallel" org-toggle-ordered-property :style radio
21293 :selected (not (org-entry-get nil "ORDERED"))
21294 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21296 ["Set Priority" org-priority t]
21297 ["Priority Up" org-shiftup t]
21298 ["Priority Down" org-shiftdown t]
21300 ["Get news from all feeds" org-feed-update-all t]
21301 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21302 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21303 ("TAGS and Properties"
21304 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21305 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21307 ["Set property" org-set-property (not (org-before-first-heading-p))]
21308 ["Column view of properties" org-columns t]
21309 ["Insert Column View DBlock" org-insert-columns-dblock t])
21310 ("Dates and Scheduling"
21311 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21312 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21314 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21315 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21316 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21317 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21318 ["Compute Time Range" org-evaluate-time-range t]
21319 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21320 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21322 ["Custom time format" org-toggle-time-stamp-overlays
21323 :style radio :selected org-display-custom-times]
21325 ["Goto Calendar" org-goto-calendar t]
21326 ["Date from Calendar" org-date-from-calendar t]
21328 ["Start/Restart Timer" org-timer-start t]
21329 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21330 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21331 ["Insert Timer String" org-timer t]
21332 ["Insert Timer Item" org-timer-item t])
21334 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21335 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21336 ["Clock out" org-clock-out t]
21337 ["Clock cancel" org-clock-cancel t]
21339 ["Mark as default task" org-clock-mark-default-task t]
21340 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21341 ["Goto running clock" org-clock-goto t]
21343 ["Display times" org-clock-display t]
21344 ["Create clock table" org-clock-report t]
21346 ["Record DONE time"
21347 (progn (setq org-log-done (not org-log-done))
21348 (message "Switching to %s will %s record a timestamp"
21349 (car org-done-keywords)
21350 (if org-log-done "automatically" "not")))
21351 :style toggle :selected org-log-done])
21353 ["Agenda Command..." org-agenda t]
21354 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21355 ("File List for Agenda")
21356 ("Special views current file"
21357 ["TODO Tree" org-show-todo-tree t]
21358 ["Check Deadlines" org-check-deadlines t]
21359 ["Timeline" org-timeline t]
21360 ["Tags/Property tree" org-match-sparse-tree t])
21362 ["Export/Publish..." org-export-dispatch t]
21364 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21365 :selected org-cdlatex-mode]
21366 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21367 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21368 ["Modify math symbol" org-cdlatex-math-modify
21369 (org-inside-LaTeX-fragment-p)]
21370 ["Insert citation" org-reftex-citation t]
21372 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21375 ["Push Files and Views" org-mobile-push t]
21376 ["Get Captured and Flagged" org-mobile-pull t]
21377 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21379 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21382 ["Show Version" org-version t]
21383 ["Info Documentation" org-info t])
21385 ["Browse Org Group" org-customize t]
21387 ["Expand This Menu" org-create-customize-menu
21388 (fboundp 'customize-menu-create)])
21389 ["Send bug report" org-submit-bug-report t]
21392 ["Refresh setup current buffer" org-mode-restart t]
21393 ["Reload Org (after update)" org-reload t]
21394 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21397 (defun org-info (&optional node)
21398 "Read documentation for Org-mode in the info system.
21399 With optional NODE, go directly to that node."
21401 (info (format "(org)%s" (or node ""))))
21404 (defun org-submit-bug-report ()
21405 "Submit a bug report on Org-mode via mail.
21407 Don't hesitate to report any problems or inaccurate documentation.
21409 If you don't have setup sending mail from (X)Emacs, please copy the
21410 output buffer into your mail program, as it gives us important
21411 information about your Org-mode version and configuration."
21413 (require 'reporter)
21414 (org-load-modules-maybe)
21415 (org-require-autoloaded-modules)
21416 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21417 (reporter-submit-bug-report
21418 "emacs-orgmode@gnu.org"
21419 (org-version nil 'full)
21421 (save-window-excursion
21422 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21423 (delete-other-windows)
21425 (insert "You are about to submit a bug report to the Org-mode mailing list.
21427 We would like to add your full Org-mode and Outline configuration to the
21428 bug report. This greatly simplifies the work of the maintainer and
21429 other experts on the mailing list.
21431 HOWEVER, some variables you have customized may contain private
21432 information. The names of customers, colleagues, or friends, might
21433 appear in the form of file names, tags, todo states, or search strings.
21434 If you answer yes to the prompt, you might want to check and remove
21435 such private information before sending the email.")
21436 (add-text-properties (point-min) (point-max) '(face org-warning))
21437 (when (yes-or-no-p "Include your Org-mode configuration ")
21441 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21442 (or (and (symbol-value v)
21443 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21445 (get v 'custom-type) (get v 'standard-value)
21446 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21448 (kill-buffer (get-buffer "*Warn about privacy*"))
21451 "Remember to cover the basics, that is, what you expected to happen and
21452 what in fact did happen. You don't know how to make a good report? See
21454 http://orgmode.org/manual/Feedback.html#Feedback
21456 Your bug report will be posted to the Org-mode mailing list.
21457 ------------------------------------------------------------------------")
21459 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21460 (replace-match "\\1Bug: \\3 [\\2]")))))
21463 (defun org-install-agenda-files-menu ()
21464 (let ((bl (buffer-list)))
21467 (set-buffer (pop bl))
21468 (if (derived-mode-p 'org-mode) (setq bl nil)))
21469 (when (derived-mode-p 'org-mode)
21471 '("Org") "File List for Agenda"
21474 ["Edit File List" (org-edit-agenda-file-list) t]
21475 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21476 ["Remove Current File from List" org-remove-file t]
21477 ["Cycle through agenda files" org-cycle-agenda-files t]
21478 ["Occur in all agenda files" org-occur-in-agenda-files t]
21480 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21484 (defun org-require-autoloaded-modules ()
21487 '(org-agenda org-archive org-attach org-clock org-colview org-id
21488 org-table org-timer)))
21491 (defun org-reload (&optional uncompiled)
21492 "Reload all org lisp files.
21493 With prefix arg UNCOMPILED, load the uncompiled versions."
21495 (require 'loadhist)
21496 (let* ((org-dir (org-find-library-dir "org"))
21497 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21498 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21499 (remove-re (mapconcat 'identity
21500 (mapcar (lambda (f) (concat "^" f "$"))
21501 (list (if (featurep 'xemacs)
21503 "org-colview-xemacs")
21504 "org" "org-loaddefs" "org-version"))
21506 (feats (delete-dups
21507 (mapcar 'file-name-sans-extension
21508 (mapcar 'file-name-nondirectory
21510 (mapcar 'feature-file
21517 (if (and (string-match feature-re f)
21518 (not (string-match remove-re f)))
21522 (list "org-version" "org")))
21523 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21524 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21525 load-uncore load-misses)
21528 (mapcar (lambda (f)
21529 (or (org-load-noerror-mustsuffix (concat org-dir f))
21530 (and (string= org-dir contrib-dir)
21531 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21532 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21533 (add-to-list 'load-uncore f 'append)
21538 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21539 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21541 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21542 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21543 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21546 (defun org-customize ()
21547 "Call the customize function with org as argument."
21549 (org-load-modules-maybe)
21550 (org-require-autoloaded-modules)
21551 (customize-browse 'org))
21553 (defun org-create-customize-menu ()
21554 "Create a full customization menu for Org-mode, insert it into the menu."
21556 (org-load-modules-maybe)
21557 (org-require-autoloaded-modules)
21558 (if (fboundp 'customize-menu-create)
21561 '("Org") "Customize"
21562 `(["Browse Org group" org-customize t]
21564 ,(customize-menu-create 'org)
21565 ["Set" Custom-set t]
21566 ["Save" Custom-save t]
21567 ["Reset to Current" Custom-reset-current t]
21568 ["Reset to Saved" Custom-reset-saved t]
21569 ["Reset to Standard Settings" Custom-reset-standard t]))
21570 (message "\"Org\"-menu now contains full customization menu"))
21571 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21573 ;;;; Miscellaneous stuff
21575 ;;; Generally useful functions
21577 (defsubst org-get-at-eol (property n)
21578 "Get text property PROPERTY at the end of line less N characters."
21579 (get-text-property (- (point-at-eol) n) property))
21581 (defun org-find-text-property-in-string (prop s)
21582 "Return the first non-nil value of property PROP in string S."
21583 (or (get-text-property 0 prop s)
21584 (get-text-property (or (next-single-property-change 0 prop s) 0)
21587 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21588 "Display the given MESSAGE as a warning."
21589 (if (fboundp 'display-warning)
21590 (display-warning 'org message
21591 (if (featurep 'xemacs) 'warning :warning))
21592 (let ((buf (get-buffer-create "*Org warnings*")))
21593 (with-current-buffer buf
21594 (goto-char (point-max))
21595 (insert "Warning (Org): " message)
21598 (display-buffer buf)
21601 (defun org-eval (form)
21602 "Eval FORM and return result."
21603 (condition-case error
21605 (error (format "%%![Error: %s]" error))))
21607 (defun org-in-clocktable-p ()
21608 "Check if the cursor is in a clocktable."
21609 (let ((pos (point)) start)
21612 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21613 (setq start (match-beginning 0))
21614 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21615 (>= (match-end 0) pos)
21618 (defun org-in-verbatim-emphasis ()
21620 (and (org-in-regexp org-emph-re 2)
21621 (>= (point) (match-beginning 3))
21622 (<= (point) (match-end 4))
21623 (member (match-string 3) '("=" "~")))))
21625 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21626 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21627 (if (and marker (marker-buffer marker)
21628 (buffer-live-p (marker-buffer marker)))
21630 (org-pop-to-buffer-same-window (marker-buffer marker))
21631 (if (or (> marker (point-max)) (< marker (point-min)))
21634 (org-show-context 'org-goto))
21636 (bookmark-jump bookmark)
21637 (error "Cannot find location"))))
21639 (defun org-quote-csv-field (s)
21640 "Quote field for inclusion in CSV material."
21641 (if (string-match "[\",]" s)
21642 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21645 (defun org-force-self-insert (N)
21646 "Needed to enforce self-insert under remapping."
21648 (self-insert-command N))
21650 (defun org-string-width (s)
21651 "Compute width of string, ignoring invisible characters.
21652 This ignores character with invisibility property `org-link', and also
21653 characters with property `org-cwidth', because these will become invisible
21654 upon the next fontification round."
21656 (when (or (eq t buffer-invisibility-spec)
21657 (assq 'org-link buffer-invisibility-spec))
21658 (while (setq b (text-property-any 0 (length s)
21659 'invisible 'org-link s))
21660 (setq s (concat (substring s 0 b)
21661 (substring s (or (next-single-property-change
21662 b 'invisible s) (length s)))))))
21663 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21664 (setq s (concat (substring s 0 b)
21665 (substring s (or (next-single-property-change
21666 b 'org-cwidth s) (length s))))))
21667 (setq l (string-width s) b -1)
21668 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21669 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21672 (defun org-shorten-string (s maxlength)
21673 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21674 If the string is shorter or has length MAXLENGTH, just return the
21675 original string. If it is longer, the functions finds a space in the
21676 string, breaks this string off at that locations and adds three dots
21677 as ellipsis. Including the ellipsis, the string will not be longer
21678 than MAXLENGTH. If finding a good breaking point in the string does
21679 not work, the string is just chopped off in the middle of a word
21681 (if (<= (length s) maxlength)
21683 (let* ((n (max (- maxlength 4) 1))
21684 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21685 (if (string-match re s)
21686 (concat (match-string 1 s) "...")
21687 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21689 (defun org-get-indentation (&optional line)
21690 "Get the indentation of the current line, interpreting tabs.
21691 When LINE is given, assume it represents a line and compute its indentation."
21693 (if (string-match "^ *" (org-remove-tabs line))
21696 (beginning-of-line 1)
21697 (skip-chars-forward " \t")
21698 (current-column))))
21700 (defun org-get-string-indentation (s)
21701 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21702 (let ((n -1) (i 0) (w tab-width) c)
21704 (while (< (setq n (1+ n)) (length s))
21705 (setq c (aref s n))
21706 (cond ((= c ?\ ) (setq i (1+ i)))
21707 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21708 (t (throw 'exit t)))))
21711 (defun org-remove-tabs (s &optional width)
21712 "Replace tabulators in S with spaces.
21713 Assumes that s is a single line, starting in column 0."
21714 (setq width (or width tab-width))
21715 (while (string-match "\t" s)
21716 (setq s (replace-match
21718 (- (* width (/ (+ (match-beginning 0) width) width))
21719 (match-beginning 0)) ?\ )
21723 (defun org-fix-indentation (line ind)
21724 "Fix indentation in LINE.
21725 IND is a cons cell with target and minimum indentation.
21726 If the current indentation in LINE is smaller than the minimum,
21727 leave it alone. If it is larger than ind, set it to the target."
21728 (let* ((l (org-remove-tabs line))
21729 (i (org-get-indentation l))
21730 (i1 (car ind)) (i2 (cdr ind)))
21731 (if (>= i i2) (setq l (substring line i2)))
21733 (concat (make-string i1 ?\ ) l)
21736 (defun org-remove-indentation (code &optional n)
21737 "Remove the maximum common indentation from the lines in CODE.
21738 N may optionally be the number of spaces to remove."
21741 (org-do-remove-indentation n)
21744 (defun org-do-remove-indentation (&optional n)
21745 "Remove the maximum common indentation from the buffer."
21746 (untabify (point-min) (point-max))
21747 (let ((min 10000) re)
21750 (goto-char (point-min))
21751 (while (re-search-forward "^ *[^ \n]" nil t)
21752 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21753 (unless (or (= min 0) (= min 10000))
21754 (setq re (format "^ \\{%d\\}" min))
21755 (goto-char (point-min))
21756 (while (re-search-forward re nil t)
21761 (defun org-fill-template (template alist)
21762 "Find each %key of ALIST in TEMPLATE and replace it."
21763 (let ((case-fold-search nil)
21765 (setq alist (sort (copy-sequence alist)
21766 (lambda (a b) (< (length (car a)) (length (car b))))))
21767 (while (setq entry (pop alist))
21769 (replace-regexp-in-string
21770 (concat "%" (regexp-quote (car entry)))
21771 (or (cdr entry) "") template t t)))
21774 (defun org-base-buffer (buffer)
21775 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21778 (or (buffer-base-buffer buffer)
21781 (defun org-wrap (string &optional width lines)
21782 "Wrap string to either a number of lines, or a width in characters.
21783 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21784 that costs. If there is a word longer than WIDTH, the text is actually
21785 wrapped to the length of that word.
21786 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21787 many lines, whatever width that takes.
21788 The return value is a list of lines, without newlines at the end."
21789 (let* ((words (org-split-string string "[ \t\n]+"))
21790 (maxword (apply 'max (mapcar 'org-string-width words)))
21793 (org-do-wrap words (max maxword width)))
21796 (setq ll (org-do-wrap words maxword))
21797 (if (<= (length ll) lines)
21800 (while (> (length ll) lines)
21802 (setq ll (org-do-wrap words w)))
21804 (t (error "Cannot wrap this")))))
21806 (defun org-do-wrap (words width)
21807 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21810 (setq line (pop words))
21811 (while (and words (< (+ (length line) (length (car words))) width))
21812 (setq line (concat line " " (pop words))))
21813 (setq lines (push line lines)))
21816 (defun org-split-string (string &optional separators)
21817 "Splits STRING into substrings at SEPARATORS.
21818 No empty strings are returned if there are matches at the beginning
21819 and end of string."
21820 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21824 (while (and (string-match rexp string
21826 (= start (match-beginning 0))
21827 (< start (length string)))
21829 (< (match-beginning 0) (length string)))
21831 (or (eq (match-beginning 0) 0)
21832 (and (eq (match-beginning 0) (match-end 0))
21833 (eq (match-beginning 0) start))
21835 (cons (substring string start (match-beginning 0))
21837 (setq start (match-end 0)))
21838 (or (eq start (length string))
21840 (cons (substring string start)
21844 (defun org-quote-vert (s)
21845 "Replace \"|\" with \"\\vert\"."
21846 (while (string-match "|" s)
21847 (setq s (replace-match "\\vert" t t s)))
21850 (defun org-uuidgen-p (s)
21851 "Is S an ID created by UUIDGEN?"
21852 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21854 (defun org-in-src-block-p (&optional inside)
21855 "Whether point is in a code source block.
21856 When INSIDE is non-nil, don't consider we are within a src block
21857 when point is at #+BEGIN_SRC or #+END_SRC."
21858 (let ((case-fold-search t) ov)
21859 (or (and (eq (get-char-property (point) 'src-block) t))
21863 (beginning-of-line)
21864 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21866 (defun org-context ()
21867 "Return a list of contexts of the current cursor position.
21868 If several contexts apply, all are returned.
21869 Each context entry is a list with a symbol naming the context, and
21870 two positions indicating start and end of the context. Possible
21873 :headline anywhere in a headline
21874 :headline-stars on the leading stars in a headline
21875 :todo-keyword on a TODO keyword (including DONE) in a headline
21876 :tags on the TAGS in a headline
21877 :priority on the priority cookie in a headline
21878 :item on the first line of a plain list item
21879 :item-bullet on the bullet/number of a plain list item
21880 :checkbox on the checkbox in a plain list item
21881 :table in an org-mode table
21882 :table-special on a special filed in a table
21883 :table-table in a table.el table
21884 :clocktable in a clocktable
21885 :src-block in a source block
21886 :link on a hyperlink
21887 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21888 :target on a <<target>>
21889 :radio-target on a <<<radio-target>>>
21890 :latex-fragment on a LaTeX fragment
21891 :latex-preview on a LaTeX fragment with overlaid preview image
21893 This function expects the position to be visible because it uses font-lock
21894 faces as a help to recognize the following contexts: :table-special, :link,
21896 (let* ((f (get-text-property (point) 'face))
21897 (faces (if (listp f) f (list f)))
21898 (case-fold-search t)
21899 (p (point)) clist o)
21900 ;; First the large context
21902 ((org-at-heading-p t)
21903 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21905 (beginning-of-line 1)
21906 (looking-at org-todo-line-tags-regexp))
21907 (push (org-point-in-group p 1 :headline-stars) clist)
21908 (push (org-point-in-group p 2 :todo-keyword) clist)
21909 (push (org-point-in-group p 4 :tags) clist))
21911 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21912 (if (looking-at "\\[#[A-Z0-9]\\]")
21913 (push (org-point-in-group p 0 :priority) clist)))
21916 (push (org-point-in-group p 2 :item-bullet) clist)
21917 (push (list :item (point-at-bol)
21918 (save-excursion (org-end-of-item) (point)))
21920 (and (org-at-item-checkbox-p)
21921 (push (org-point-in-group p 0 :checkbox) clist)))
21924 (push (list :table (org-table-begin) (org-table-end)) clist)
21925 (if (memq 'org-formula faces)
21926 (push (list :table-special
21927 (previous-single-property-change p 'face)
21928 (next-single-property-change p 'face)) clist)))
21929 ((org-at-table-p 'any)
21930 (push (list :table-table) clist)))
21933 (let ((case-fold-search t))
21934 ;; New the "medium" contexts: clocktables, source blocks
21935 (cond ((org-in-clocktable-p)
21936 (push (list :clocktable
21937 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21938 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21939 (match-beginning 1))
21940 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21941 (match-end 0))) clist))
21942 ((org-in-src-block-p)
21943 (push (list :src-block
21944 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21945 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21946 (match-beginning 1))
21947 (and (search-forward "#+END_SRC" nil t)
21948 (match-beginning 0))) clist))))
21951 ;; Now the small context
21953 ((org-at-timestamp-p)
21954 (push (org-point-in-group p 0 :timestamp) clist))
21955 ((memq 'org-link faces)
21957 (previous-single-property-change p 'face)
21958 (next-single-property-change p 'face)) clist))
21959 ((memq 'org-special-keyword faces)
21960 (push (list :keyword
21961 (previous-single-property-change p 'face)
21962 (next-single-property-change p 'face)) clist))
21964 (push (org-point-in-group p 0 :target) clist)
21965 (goto-char (1- (match-beginning 0)))
21966 (if (looking-at org-radio-target-regexp)
21967 (push (org-point-in-group p 0 :radio-target) clist))
21969 ((setq o (car (delq nil
21972 (if (memq x org-latex-fragment-image-overlays) x))
21973 (overlays-at (point))))))
21974 (push (list :latex-fragment
21975 (overlay-start o) (overlay-end o)) clist)
21976 (push (list :latex-preview
21977 (overlay-start o) (overlay-end o)) clist))
21978 ((org-inside-LaTeX-fragment-p)
21979 ;; FIXME: positions wrong.
21980 (push (list :latex-fragment (point) (point)) clist)))
21982 (setq clist (nreverse (delq nil clist)))
21985 ;; FIXME: Compare with at-regexp-p Do we need both?
21986 (defun org-in-regexp (re &optional nlines visually)
21987 "Check if point is inside a match of regexp.
21988 Normally only the current line is checked, but you can include NLINES extra
21989 lines both before and after point into the search.
21990 If VISUALLY is set, require that the cursor is not after the match but
21991 really on, so that the block visually is on the match."
21993 (let ((pos (point))
21994 (eol (point-at-eol (+ 1 (or nlines 0))))
21995 (inc (if visually 1 0)))
21997 (beginning-of-line (- 1 (or nlines 0)))
21998 (while (re-search-forward re eol t)
21999 (if (and (<= (match-beginning 0) pos)
22000 (>= (+ inc (match-end 0)) pos))
22001 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
22003 (defun org-at-regexp-p (regexp)
22004 "Is point inside a match of REGEXP in the current line?"
22007 (let ((pos (point)) (end (point-at-eol)))
22008 (beginning-of-line 1)
22009 (while (re-search-forward regexp end t)
22010 (if (and (<= (match-beginning 0) pos)
22011 (>= (match-end 0) pos))
22015 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22016 "Non-nil when point is between matches of START-RE and END-RE.
22018 Also return a non-nil value when point is on one of the matches.
22020 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22021 buffer positions. Default values are the positions of headlines
22022 surrounding the point.
22024 The functions returns a cons cell whose car (resp. cdr) is the
22025 position before START-RE (resp. after END-RE)."
22027 (let ((pos (point))
22028 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22029 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22032 ;; Point is on a block when on START-RE or if START-RE can be
22033 ;; found before it...
22034 (and (or (org-at-regexp-p start-re)
22035 (re-search-backward start-re limit-up t))
22036 (setq beg (match-beginning 0))
22037 ;; ... and END-RE after it...
22038 (goto-char (match-end 0))
22039 (re-search-forward end-re limit-down t)
22040 (> (setq end (match-end 0)) pos)
22041 ;; ... without another START-RE in-between.
22042 (goto-char (match-beginning 0))
22043 (not (re-search-backward start-re (1+ beg) t))
22045 (cons beg end))))))
22047 (defun org-in-block-p (names)
22048 "Non-nil when point belongs to a block whose name belongs to NAMES.
22050 NAMES is a list of strings containing names of blocks.
22052 Return first block name matched, or nil. Beware that in case of
22053 nested blocks, the returned name may not belong to the closest
22057 (let ((case-fold-search t)
22058 (lim-up (save-excursion (outline-previous-heading)))
22059 (lim-down (save-excursion (outline-next-heading))))
22060 (mapc (lambda (name)
22061 (let ((n (regexp-quote name)))
22062 (when (org-between-regexps-p
22063 (concat "^[ \t]*#\\+begin_" n)
22064 (concat "^[ \t]*#\\+end_" n)
22070 (defun org-in-drawer-p ()
22071 "Non-nil if point is within a drawer.
22072 If point is within a drawer, return it, as parsed data."
22073 (let ((element (save-match-data (org-element-at-point))))
22074 (while (and element (not (memq (org-element-type element)
22075 '(drawer property-drawer))))
22076 (setq element (org-element-property :parent element)))
22079 (defun org-occur-in-agenda-files (regexp &optional nlines)
22080 "Call `multi-occur' with buffers for all agenda files."
22081 (interactive "sOrg-files matching: \np")
22082 (let* ((files (org-agenda-files))
22083 (tnames (mapcar 'file-truename files))
22084 (extra org-agenda-text-search-extra-files)
22086 (when (eq (car extra) 'agenda-archives)
22087 (setq extra (cdr extra))
22088 (setq files (org-add-archive-files files)))
22089 (while (setq f (pop extra))
22090 (unless (member (file-truename f) tnames)
22091 (add-to-list 'files f 'append)
22092 (add-to-list 'tnames (file-truename f) 'append)))
22094 (mapcar (lambda (x)
22095 (with-current-buffer
22096 (or (get-file-buffer x) (find-file-noselect x))
22102 (if (boundp 'occur-mode-find-occurrence-hook)
22104 (add-hook 'occur-mode-find-occurrence-hook
22106 (when (derived-mode-p 'org-mode)
22109 (defadvice occur-mode-goto-occurrence
22110 (after org-occur-reveal activate)
22111 (and (derived-mode-p 'org-mode) (org-reveal)))
22112 (defadvice occur-mode-goto-occurrence-other-window
22113 (after org-occur-reveal activate)
22114 (and (derived-mode-p 'org-mode) (org-reveal)))
22115 (defadvice occur-mode-display-occurrence
22116 (after org-occur-reveal activate)
22117 (when (derived-mode-p 'org-mode)
22118 (let ((pos (occur-mode-find-occurrence)))
22119 (with-current-buffer (marker-buffer pos)
22124 (defun org-occur-link-in-agenda-files ()
22125 "Create a link and search for it in the agendas.
22126 The link is not stored in `org-stored-links', it is just created
22127 for the search purpose."
22129 (let ((link (condition-case nil
22130 (org-store-link nil)
22131 (error "Unable to create a link to here"))))
22132 (org-occur-in-agenda-files (regexp-quote link))))
22134 (defun org-reverse-string (string)
22135 "Return the reverse of STRING."
22136 (apply 'string (reverse (string-to-list string))))
22138 ;; defsubst org-uniquify must be defined before first use
22140 (defun org-uniquify-alist (alist)
22141 "Merge elements of ALIST with the same key.
22143 For example, in this alist:
22145 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
22146 => '((a 1 3) (b 2))
22148 merge (a 1) and (a 3) into (a 1 3).
22150 The function returns the new ALIST."
22155 (if (not (assoc (car e) rtn))
22157 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22158 (setq rtn (assq-delete-all (car e) rtn))
22163 (defun org-delete-all (elts list)
22164 "Remove all elements in ELTS from LIST."
22166 (setq list (delete (pop elts) list)))
22169 (defun org-count (cl-item cl-seq)
22170 "Count the number of occurrences of ITEM in SEQ.
22171 Taken from `count' in cl-seq.el with all keyword arguments removed."
22172 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
22173 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
22174 (while (< cl-start cl-end)
22175 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
22176 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
22177 (setq cl-start (1+ cl-start)))
22180 (defun org-remove-if (predicate seq)
22181 "Remove everything from SEQ that fulfills PREDICATE."
22185 (if (not (funcall predicate e)) (push e res)))
22188 (defun org-remove-if-not (predicate seq)
22189 "Remove everything from SEQ that does not fulfill PREDICATE."
22193 (if (funcall predicate e) (push e res)))
22196 (defun org-reduce (cl-func cl-seq &rest cl-keys)
22197 "Reduce two-argument FUNCTION across SEQ.
22198 Taken from `reduce' in cl-seq.el with all keyword arguments but
22199 \":initial-value\" removed."
22200 (let ((cl-accum (cond ((memq :initial-value cl-keys)
22201 (cadr (memq :initial-value cl-keys)))
22202 (cl-seq (pop cl-seq))
22203 (t (funcall cl-func)))))
22205 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22208 (defun org-every (pred seq)
22209 "Return true if PREDICATE is true of every element of SEQ.
22210 Adapted from `every' in cl.el."
22212 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22215 (defun org-some (pred seq)
22216 "Return true if PREDICATE is true of any element of SEQ.
22217 Adapted from `some' in cl.el."
22219 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22222 (defun org-back-over-empty-lines ()
22223 "Move backwards over whitespace, to the beginning of the first empty line.
22224 Returns the number of empty lines passed."
22225 (let ((pos (point)))
22226 (if (cdr (assoc 'heading org-blank-before-new-entry))
22227 (skip-chars-backward " \t\n\r")
22229 (forward-line -1)))
22230 (beginning-of-line 2)
22231 (goto-char (min (point) pos))
22232 (count-lines (point) pos)))
22234 (defun org-skip-whitespace ()
22235 (skip-chars-forward " \t\n\r"))
22237 (defun org-point-in-group (point group &optional context)
22238 "Check if POINT is in match-group GROUP.
22239 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22240 match. If the match group does not exist or point is not inside it,
22242 (and (match-beginning group)
22243 (>= point (match-beginning group))
22244 (<= point (match-end group))
22246 (list context (match-beginning group) (match-end group))
22249 (defun org-switch-to-buffer-other-window (&rest args)
22250 "Switch to buffer in a second window on the current frame.
22251 In particular, do not allow pop-up frames.
22252 Returns the newly created buffer."
22254 (apply 'switch-to-buffer-other-window args)))
22256 (defun org-combine-plists (&rest plists)
22257 "Create a single property list from all plists in PLISTS.
22258 The process starts by copying the first list, and then setting properties
22259 from the other lists. Settings in the last list are the most significant
22260 ones and overrule settings in the other lists."
22261 (let ((rtn (copy-sequence (pop plists)))
22264 (setq ls (pop plists))
22266 (setq p (pop ls) v (pop ls))
22267 (setq rtn (plist-put rtn p v))))
22270 (defun org-replace-escapes (string table)
22271 "Replace %-escapes in STRING with values in TABLE.
22272 TABLE is an association list with keys like \"%a\" and string values.
22273 The sequences in STRING may contain normal field width and padding information,
22274 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22275 so values can contain further %-escapes if they are define later in TABLE."
22276 (let ((tbl (copy-alist table))
22277 (case-fold-search nil)
22280 (while (setq e (pop tbl))
22281 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22282 (when (and (cdr e) (string-match re (cdr e)))
22283 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22285 (add-text-properties 0 3 (list 'sref sref) safe)
22286 (setcdr e (replace-match safe t t (cdr e)))))
22287 (while (string-match re string)
22288 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22290 (setq string (replace-match rpl t t string))))
22291 (while (setq pchg (next-property-change pchg string))
22292 (let ((sref (get-text-property pchg 'sref string)))
22293 (when (and sref (string-match "SREF" string pchg))
22294 (setq string (replace-match sref t t string)))))
22297 (defun org-sublist (list start end)
22298 "Return a section of LIST, from START to END.
22299 Counting starts at 1."
22300 (let (rtn (c start))
22301 (setq list (nthcdr (1- start) list))
22302 (while (and list (<= c end))
22303 (push (pop list) rtn)
22307 (defun org-find-base-buffer-visiting (file)
22308 "Like `find-buffer-visiting' but always return the base buffer and
22309 not an indirect buffer."
22310 (let ((buf (or (get-file-buffer file)
22311 (find-buffer-visiting file))))
22313 (or (buffer-base-buffer buf) buf)
22316 (defun org-image-file-name-regexp (&optional extensions)
22317 "Return regexp matching the file names of images.
22318 If EXTENSIONS is given, only match these."
22319 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22320 (image-file-name-regexp)
22321 (let ((image-file-name-extensions
22323 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22324 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22326 (regexp-opt (nconc (mapcar 'upcase
22327 image-file-name-extensions)
22328 image-file-name-extensions)
22332 (defun org-file-image-p (file &optional extensions)
22333 "Return non-nil if FILE is an image."
22335 (string-match (org-image-file-name-regexp extensions) file)))
22337 (defun org-get-cursor-date (&optional with-time)
22338 "Return the date at cursor in as a time.
22339 This works in the calendar and in the agenda, anywhere else it just
22340 returns the current time.
22341 If WITH-TIME is non-nil, returns the time of the event at point (in
22342 the agenda) or the current time of the day."
22343 (let (date day defd tp tm hod mod)
22345 (setq tp (get-text-property (point) 'time))
22346 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22347 (setq hod (string-to-number (match-string 1 tp))
22348 mod (string-to-number (match-string 2 tp))))
22349 (or tp (setq hod (nth 2 (decode-time (current-time)))
22350 mod (nth 1 (decode-time (current-time))))))
22352 ((eq major-mode 'calendar-mode)
22353 (setq date (calendar-cursor-to-date)
22354 defd (encode-time 0 (or mod 0) (or hod 0)
22355 (nth 1 date) (nth 0 date) (nth 2 date))))
22356 ((eq major-mode 'org-agenda-mode)
22357 (setq day (get-text-property (point) 'day))
22359 (setq date (calendar-gregorian-from-absolute day)
22360 defd (encode-time 0 (or mod 0) (or hod 0)
22361 (nth 1 date) (nth 0 date) (nth 2 date))))))
22362 (or defd (current-time))))
22364 (defun org-mark-subtree (&optional up)
22365 "Mark the current subtree.
22366 This puts point at the start of the current subtree, and mark at
22367 the end. If a numeric prefix UP is given, move up into the
22368 hierarchy of headlines by UP levels before marking the subtree."
22370 (org-with-limited-levels
22371 (cond ((org-at-heading-p) (beginning-of-line))
22372 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22373 (t (outline-previous-visible-heading 1))))
22374 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22375 (if (org-called-interactively-p 'any)
22376 (call-interactively 'org-mark-element)
22377 (org-mark-element)))
22382 (defun org--get-expected-indentation (element contentsp)
22383 "Expected indentation column for current line, according to ELEMENT.
22384 ELEMENT is an element containing point. CONTENTSP is non-nil
22385 when indentation is to be computed according to contents of
22387 (let ((type (org-element-type element))
22388 (start (org-element-property :begin element)))
22389 (org-with-wide-buffer
22393 (footnote-definition 0)
22394 ((headline inlinetask nil)
22395 (if (not org-adapt-indentation) 0
22396 (let ((level (org-current-level)))
22397 (if level (1+ level) 0))))
22399 (org-list-item-body-column
22400 (org-element-property :post-affiliated element)))
22403 (org-get-indentation))))
22404 ((memq type '(headline inlinetask nil))
22405 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22406 (org--get-expected-indentation element t)
22408 ((eq type 'footnote-definition) 0)
22409 ;; First paragraph of a footnote definition or an item.
22410 ;; Indent like parent.
22411 ((< (line-beginning-position) start)
22412 (org--get-expected-indentation
22413 (org-element-property :parent element) t))
22414 ;; At first line: indent according to previous sibling, if any,
22415 ;; ignoring footnote definitions and inline tasks, or parent's
22417 ((= (line-beginning-position) start)
22420 (if (= (point-min) start) (throw 'exit 0)
22421 (goto-char (1- start))
22422 (let ((previous (org-element-at-point)))
22423 (while (let ((parent (org-element-property :parent previous)))
22425 (setq previous parent)
22426 (<= (org-element-property :end parent) start))))
22427 (cond ((or (not previous)
22428 (> (org-element-property :end previous) start))
22429 (throw 'exit (org--get-expected-indentation previous t)))
22430 ((memq (org-element-type previous)
22431 '(footnote-definition inlinetask))
22432 (setq start (org-element-property :begin previous)))
22433 (t (goto-char (org-element-property :begin previous))
22434 (throw 'exit (org-get-indentation)))))))))
22435 ;; Otherwise, move to the first non-blank line above.
22437 (beginning-of-line)
22438 (let ((pos (point)))
22439 (skip-chars-backward " \r\t\n")
22441 ;; Two blank lines end a footnote definition or a plain
22442 ;; list. When we indent an empty line after them, the
22443 ;; containing list or footnote definition is over, so it
22444 ;; qualifies as a previous sibling. Therefore, we indent
22445 ;; like its first line.
22446 ((and (memq type '(footnote-definition plain-list))
22447 (> (count-lines (point) pos) 2))
22449 (org-get-indentation))
22450 ;; Line above is the first one of a paragraph at the
22451 ;; beginning of an item or a footnote definition. Indent
22453 ((< (line-beginning-position) start)
22454 (org--get-expected-indentation
22455 (org-element-property :parent element) t))
22456 ;; POS is after contents in a greater element. Indent like
22457 ;; the beginning of the element.
22459 ;; As a special case, if point is at the end of a footnote
22460 ;; definition or an item, indent like the very last element
22462 ((let ((cend (org-element-property :contents-end element)))
22463 (and cend (<= cend pos)))
22464 (if (memq type '(footnote-definition item plain-list))
22465 (org--get-expected-indentation (org-element-at-point) nil)
22467 (org-get-indentation)))
22468 ;; In any other case, indent like the current line.
22469 (t (org-get-indentation)))))))))
22471 (defun org--align-node-property ()
22472 "Align node property at point.
22473 Alignment is done according to `org-property-format', which see."
22474 (when (save-excursion
22475 (beginning-of-line)
22476 (looking-at org-property-re))
22478 (concat (match-string 4)
22480 (format org-property-format (match-string 1) (match-string 3))))
22483 (defun org-indent-line ()
22484 "Indent line depending on context.
22486 Indentation is done according to the following rules:
22488 - Footnote definitions, headlines and inline tasks have to
22491 - On the very first line of an element, consider, in order, the
22492 next rules until one matches:
22494 1. If there's a sibling element before, ignoring footnote
22495 definitions and inline tasks, indent like its first line.
22497 2. If element has a parent, indent like its contents. More
22498 precisely, if parent is an item, indent after the
22499 description part, if any, or the bullet (see
22500 ``org-list-description-max-indent'). Else, indent like
22501 parent's first line.
22503 3. Otherwise, indent relatively to current level, if
22504 `org-adapt-indentation' is non-nil, or to left margin.
22506 - On a blank line at the end of a plain list, an item, or
22507 a footnote definition, indent like the very last element
22510 - In the code part of a source block, use language major mode
22511 to indent current line if `org-src-tab-acts-natively' is
22512 non-nil. If it is nil, do nothing.
22514 - Otherwise, indent like the first non-blank line above.
22516 The function doesn't indent an item as it could break the whole
22517 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22518 \\[org-shiftmetaright].
22520 Also align node properties according to `org-property-format'."
22524 (let ((indent-line-function
22525 (cadadr (assq 'indent-line-function org-fb-vars))))
22526 (indent-according-to-mode)))
22527 ((org-at-heading-p) 'noindent)
22529 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22530 (type (org-element-type element)))
22531 (cond ((and (memq type '(plain-list item))
22532 (= (line-beginning-position)
22533 (org-element-property :post-affiliated element)))
22535 ((and (eq type 'src-block)
22536 org-src-tab-acts-natively
22537 (> (line-beginning-position)
22538 (org-element-property :post-affiliated element))
22539 (< (line-beginning-position)
22540 (org-with-wide-buffer
22541 (goto-char (org-element-property :end element))
22542 (skip-chars-backward " \r\t\n")
22543 (line-beginning-position))))
22544 (let ((org-src-strip-leading-and-trailing-blank-lines nil))
22545 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB"))))
22547 (let ((column (org--get-expected-indentation element nil)))
22548 ;; Preserve current column.
22549 (if (<= (current-column) (current-indentation))
22550 (org-indent-line-to column)
22551 (save-excursion (org-indent-line-to column))))
22552 ;; Align node property. Also preserve current column.
22553 (when (eq type 'node-property)
22554 (let ((column (current-column)))
22555 (org--align-node-property)
22556 (org-move-to-column column)))))))))
22558 (defun org-indent-region (start end)
22559 "Indent each non-blank line in the region.
22560 Called from a program, START and END specify the region to
22561 indent. The function will not indent contents of example blocks,
22562 verse blocks and export blocks as leading white spaces are
22563 assumed to be significant there."
22567 (beginning-of-line)
22570 ;; Set IND as indentation for all lines between point and
22571 ;; POS or END, whichever comes first. Blank lines are
22572 ;; ignored. Leave point after POS once done.
22573 (let ((limit (copy-marker (min end pos))))
22574 (while (< (point) limit)
22575 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
22577 (set-marker limit nil))))
22578 (end (copy-marker end)))
22579 (while (< (point) end)
22580 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22581 (let* ((element (org-element-at-point))
22582 (type (org-element-type element))
22583 (element-end (copy-marker (org-element-property :end element)))
22584 (ind (org--get-expected-indentation element nil)))
22585 (if (or (memq type '(paragraph table table-row))
22586 (not (or (org-element-property :contents-begin element)
22588 '(example-block export-block src-block)))))
22589 ;; Elements here are indented as a single block. Also
22590 ;; align node properties.
22592 (when (eq type 'node-property)
22593 (org--align-node-property)
22594 (beginning-of-line))
22595 (funcall indent-to ind element-end))
22596 ;; Elements in this category consist of three parts:
22597 ;; before the contents, the contents, and after the
22598 ;; contents. The contents are treated specially,
22599 ;; according to the element type, or not indented at
22600 ;; all. Other parts are indented as a single block.
22601 (let* ((post (copy-marker
22602 (org-element-property :post-affiliated element)))
22606 ((not (org-element-property :contents-begin element))
22607 ;; Fake contents for source blocks.
22608 (org-with-wide-buffer
22612 ((memq type '(footnote-definition item plain-list))
22613 ;; Contents in these elements could start on
22614 ;; the same line as the beginning of the
22615 ;; element. Make sure we start indenting
22616 ;; from the second line.
22617 (org-with-wide-buffer
22621 (t (org-element-property :contents-begin element)))))
22623 (or (org-element-property :contents-end element)
22624 ;; Fake contents for source blocks.
22625 (org-with-wide-buffer
22626 (goto-char element-end)
22627 (skip-chars-backward " \r\t\n")
22628 (line-beginning-position))))))
22629 (funcall indent-to ind cbeg)
22630 (when (< (point) end)
22632 ((example-block export-block verse-block))
22634 ;; In a source block, indent source code according
22635 ;; to language major mode, but only if
22636 ;; `org-src-tab-acts-natively' is non-nil.
22637 (when (and (< (point) end) org-src-tab-acts-natively)
22639 (let (org-src-strip-leading-and-trailing-blank-lines
22640 ;; Region boundaries in edit buffer.
22641 (start (1+ (- (point) cbeg)))
22642 (end (- (min cend end) cbeg)))
22643 (org-babel-do-in-edit-buffer
22644 (indent-region start end))))))
22645 (t (org-indent-region (point) (min cend end))))
22646 (goto-char (min cend end))
22647 (when (< (point) end) (funcall indent-to ind element-end)))
22648 (set-marker post nil)
22649 (set-marker cbeg nil)
22650 (set-marker cend nil)))
22651 (set-marker element-end nil))))
22652 (set-marker end nil))))
22654 (defun org-indent-drawer ()
22655 "Indent the drawer at point."
22657 (unless (save-excursion
22658 (beginning-of-line)
22659 (org-looking-at-p org-drawer-regexp))
22660 (user-error "Not at a drawer"))
22661 (let ((element (org-element-at-point)))
22662 (unless (memq (org-element-type element) '(drawer property-drawer))
22663 (user-error "Not at a drawer"))
22664 (org-with-wide-buffer
22665 (org-indent-region (org-element-property :begin element)
22666 (org-element-property :end element))))
22667 (message "Drawer at point indented"))
22669 (defun org-indent-block ()
22670 "Indent the block at point."
22672 (unless (save-excursion
22673 (beginning-of-line)
22674 (let ((case-fold-search t))
22675 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22676 (user-error "Not at a block"))
22677 (let ((element (org-element-at-point)))
22678 (unless (memq (org-element-type element)
22679 '(comment-block center-block example-block export-block
22680 quote-block special-block src-block
22682 (user-error "Not at a block"))
22683 (org-with-wide-buffer
22684 (org-indent-region (org-element-property :begin element)
22685 (org-element-property :end element))))
22686 (message "Block at point indented"))
22691 ;; We use our own fill-paragraph and auto-fill functions.
22693 ;; `org-fill-paragraph' relies on adaptive filling and context
22694 ;; checking. Appropriate `fill-prefix' is computed with
22695 ;; `org-adaptive-fill-function'.
22697 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22698 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22699 ;; `org-adaptive-fill-function' value. Internally,
22700 ;; `org-comment-line-break-function' breaks the line.
22702 ;; `org-setup-filling' installs filling and auto-filling related
22703 ;; variables during `org-mode' initialization.
22705 (defvar org-element-paragraph-separate) ; org-element.el
22706 (defun org-setup-filling ()
22707 (require 'org-element)
22708 ;; Prevent auto-fill from inserting unwanted new items.
22709 (when (boundp 'fill-nobreak-predicate)
22711 'fill-nobreak-predicate
22713 (append fill-nobreak-predicate
22714 '(org-fill-line-break-nobreak-p
22715 org-fill-paragraph-with-timestamp-nobreak-p)))))
22716 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22717 (org-set-local 'paragraph-start paragraph-ending)
22718 (org-set-local 'paragraph-separate paragraph-ending))
22719 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22720 (org-set-local 'auto-fill-inhibit-regexp nil)
22721 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22722 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22723 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22725 (defun org-fill-line-break-nobreak-p ()
22726 "Non-nil when a new line at point would create an Org line break."
22728 (skip-chars-backward "[ \t]")
22729 (skip-chars-backward "\\\\")
22730 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22732 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22733 "Non-nil when a new line at point would split a timestamp."
22734 (and (org-at-timestamp-p t)
22735 (not (looking-at org-ts-regexp-both))))
22737 (declare-function message-in-body-p "message" ())
22738 (defvar orgtbl-line-start-regexp) ; From org-table.el
22739 (defun org-adaptive-fill-function ()
22740 "Compute a fill prefix for the current line.
22741 Return fill prefix, as a string, or nil if current line isn't
22742 meant to be filled. For convenience, if `adaptive-fill-regexp'
22743 matches in paragraphs or comments, use it."
22745 (when (derived-mode-p 'message-mode)
22747 (beginning-of-line)
22748 (cond ((or (not (message-in-body-p))
22749 (looking-at orgtbl-line-start-regexp))
22751 ((looking-at message-cite-prefix-regexp)
22752 (throw 'exit (match-string-no-properties 0)))
22753 ((looking-at org-outline-regexp)
22754 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22755 (org-with-wide-buffer
22756 (unless (org-at-heading-p)
22757 (let* ((p (line-beginning-position))
22758 (element (save-excursion
22759 (beginning-of-line)
22760 (org-element-at-point)))
22761 (type (org-element-type element))
22762 (post-affiliated (org-element-property :post-affiliated element)))
22763 (unless (< p post-affiliated)
22767 (beginning-of-line)
22768 (looking-at "[ \t]*")
22769 (concat (match-string 0) "# ")))
22770 (footnote-definition "")
22772 (make-string (org-list-item-body-column post-affiliated) ?\s))
22774 ;; Fill prefix is usually the same as the current line,
22775 ;; unless the paragraph is at the beginning of an item.
22776 (let ((parent (org-element-property :parent element)))
22778 (beginning-of-line)
22779 (cond ((eq (org-element-type parent) 'item)
22780 (make-string (org-list-item-body-column
22781 (org-element-property :begin parent))
22783 ((and adaptive-fill-regexp
22785 ;; `adaptive-fill-function' to let
22786 ;; `fill-context-prefix' handle
22787 ;; `adaptive-fill-regexp' variable.
22788 (let (adaptive-fill-function)
22789 (fill-context-prefix
22791 (org-element-property :end element)))))
22792 ((looking-at "[ \t]+") (match-string 0))
22795 ;; Only fill contents if P is within block boundaries.
22796 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22799 (cend (save-excursion
22800 (goto-char (org-element-property :end element))
22801 (skip-chars-backward " \r\t\n")
22802 (line-beginning-position))))
22803 (when (and (>= p cbeg) (< p cend))
22804 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22808 (declare-function message-goto-body "message" ())
22809 (defvar message-cite-prefix-regexp) ; From message.el
22810 (defun org-fill-paragraph (&optional justify)
22811 "Fill element at point, when applicable.
22813 This function only applies to comment blocks, comments, example
22814 blocks and paragraphs. Also, as a special case, re-align table
22815 when point is at one.
22817 If JUSTIFY is non-nil (interactively, with prefix argument),
22818 justify as well. If `sentence-end-double-space' is non-nil, then
22819 period followed by one space does not end a sentence, so don't
22820 break a line there. The variable `fill-column' controls the
22823 For convenience, when point is at a plain list, an item or
22824 a footnote definition, try to fill the first paragraph within."
22826 (if (and (derived-mode-p 'message-mode)
22827 (or (not (message-in-body-p))
22828 (save-excursion (move-beginning-of-line 1)
22829 (looking-at message-cite-prefix-regexp))))
22830 ;; First ensure filling is correct in message-mode.
22831 (let ((fill-paragraph-function
22832 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22833 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22834 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22835 (paragraph-separate
22836 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22837 (fill-paragraph nil))
22838 (with-syntax-table org-mode-transpose-word-syntax-table
22839 ;; Move to end of line in order to get the first paragraph
22840 ;; within a plain list or a footnote definition.
22841 (let ((element (save-excursion
22843 (or (ignore-errors (org-element-at-point))
22844 (user-error "An element cannot be parsed line %d"
22845 (line-number-at-pos (point)))))))
22846 ;; First check if point is in a blank line at the beginning of
22847 ;; the buffer. In that case, ignore filling.
22848 (case (org-element-type element)
22849 ;; Use major mode filling function is src blocks.
22850 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22851 ;; Align Org tables, leave table.el tables as-is.
22852 (table-row (org-table-align) t)
22854 (when (eq (org-element-property :type element) 'org)
22856 (goto-char (org-element-property :post-affiliated element))
22857 (org-table-align)))
22860 ;; Paragraphs may contain `line-break' type objects.
22861 (let ((beg (max (point-min)
22862 (org-element-property :contents-begin element)))
22863 (end (min (point-max)
22864 (org-element-property :contents-end element))))
22865 ;; Do nothing if point is at an affiliated keyword.
22866 (if (< (line-end-position) beg) t
22867 (when (derived-mode-p 'message-mode)
22868 ;; In `message-mode', do not fill following citation
22869 ;; in current paragraph nor text before message body.
22870 (let ((body-start (save-excursion (message-goto-body))))
22871 (when body-start (setq beg (max body-start beg))))
22872 (when (save-excursion
22874 (concat "^" message-cite-prefix-regexp) end t))
22875 (setq end (match-beginning 0))))
22876 ;; Fill paragraph, taking line breaks into account.
22879 (let ((cuts (list beg)))
22880 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22881 (when (eq 'line-break
22883 (save-excursion (backward-char)
22884 (org-element-context))))
22885 (push (point) cuts)))
22886 (dolist (c (delq end cuts))
22887 (fill-region-as-paragraph c end justify)
22890 ;; Contents of `comment-block' type elements should be
22891 ;; filled as plain text, but only if point is within block
22894 (let* ((case-fold-search t)
22895 (beg (save-excursion
22896 (goto-char (org-element-property :begin element))
22897 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22900 (end (save-excursion
22901 (goto-char (org-element-property :end element))
22902 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22903 (line-beginning-position))))
22904 (if (or (< (point) beg) (> (point) end)) t
22905 (fill-region-as-paragraph
22906 (save-excursion (end-of-line)
22907 (re-search-backward "^[ \t]*$" beg 'move)
22908 (line-beginning-position))
22909 (save-excursion (beginning-of-line)
22910 (re-search-forward "^[ \t]*$" end 'move)
22911 (line-beginning-position))
22915 (let ((begin (org-element-property :post-affiliated element))
22916 (end (org-element-property :end element)))
22917 (when (and (>= (point) begin) (<= (point) end))
22918 (let ((begin (save-excursion
22920 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22921 (progn (forward-line) (point))
22923 (end (save-excursion
22925 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22926 (1- (line-beginning-position))
22927 (skip-chars-backward " \r\t\n")
22928 (line-end-position)))))
22929 ;; Do not fill comments when at a blank line.
22930 (when (> end begin)
22933 (beginning-of-line)
22934 (looking-at "[ \t]*#")
22935 (let ((comment-prefix (match-string 0)))
22936 (goto-char (match-end 0))
22937 (if (looking-at adaptive-fill-regexp)
22938 (concat comment-prefix (match-string 0))
22939 (concat comment-prefix " "))))))
22941 (fill-region-as-paragraph begin end justify))))))
22943 ;; Ignore every other element.
22946 (defun org-auto-fill-function ()
22947 "Auto-fill function."
22948 ;; Check if auto-filling is meaningful.
22949 (let ((fc (current-fill-column)))
22950 (when (and fc (> (current-column) fc))
22951 (let* ((fill-prefix (org-adaptive-fill-function))
22952 ;; Enforce empty fill prefix, if required. Otherwise, it
22953 ;; will be computed again.
22954 (adaptive-fill-mode (not (equal fill-prefix ""))))
22955 (when fill-prefix (do-auto-fill))))))
22957 (defun org-comment-line-break-function (&optional soft)
22958 "Break line at point and indent, continuing comment if within one.
22959 The inserted newline is marked hard if variable
22960 `use-hard-newlines' is true, unless optional argument SOFT is
22962 (if soft (insert-and-inherit ?\n) (newline 1))
22963 (save-excursion (forward-char -1) (delete-horizontal-space))
22964 (delete-horizontal-space)
22965 (indent-to-left-margin)
22966 (insert-before-markers-and-inherit fill-prefix))
22969 ;;; Fixed Width Areas
22971 (defun org-toggle-fixed-width ()
22972 "Toggle fixed-width markup.
22974 Add or remove fixed-width markup on current line, whenever it
22975 makes sense. Return an error otherwise.
22977 If a region is active and if it contains only fixed-width areas
22978 or blank lines, remove all fixed-width markup in it. If the
22979 region contains anything else, convert all non-fixed-width lines
22980 to fixed-width ones.
22982 Blank lines at the end of the region are ignored unless the
22983 region only contains such lines."
22985 (if (not (org-region-active-p))
22988 ;; Remove fixed width marker only in a fixed-with element.
22990 ;; Add fixed width maker in paragraphs, in blank lines after
22991 ;; elements or at the beginning of a headline or an inlinetask,
22992 ;; and before any one-line elements (e.g., a clock).
22994 (beginning-of-line)
22995 (let* ((element (org-element-at-point))
22996 (type (org-element-type element)))
22998 ((and (eq type 'fixed-width)
22999 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23001 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23002 ((and (memq type '(babel-call clock comment diary-sexp headline
23003 horizontal-rule keyword paragraph
23005 (<= (org-element-property :post-affiliated element) (point)))
23006 (skip-chars-forward " \t")
23008 ((and (org-looking-at-p "[ \t]*$")
23009 (or (eq type 'inlinetask)
23011 (skip-chars-forward " \r\t\n")
23012 (<= (org-element-property :end element) (point)))))
23013 (delete-region (point) (line-end-position))
23016 (t (user-error "Cannot insert a fixed-width line here")))))
23018 (let* ((begin (save-excursion
23019 (goto-char (region-beginning))
23020 (line-beginning-position)))
23023 (goto-char (region-end))
23024 (unless (eolp) (beginning-of-line))
23025 (if (save-excursion (re-search-backward "\\S-" begin t))
23026 (progn (skip-chars-backward " \r\t\n") (point))
23032 (skip-chars-forward " \r\t\n")
23033 (when (eobp) (throw 'not-all-p nil))
23034 (while (< (point) end)
23035 (let ((element (org-element-at-point)))
23036 (if (eq (org-element-type element) 'fixed-width)
23037 (goto-char (org-element-property :end element))
23038 (throw 'not-all-p nil))))
23040 (if all-fixed-width-p
23043 (while (< (point) end)
23044 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23047 (if (= (line-end-position) (match-end 0)) 0 1)))
23049 (let ((min-ind (point-max)))
23050 ;; Find minimum indentation across all lines.
23053 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23056 (while (< (point) end)
23057 (unless (org-looking-at-p "[ \t]*$")
23058 (let ((ind (org-get-indentation)))
23059 (setq min-ind (min min-ind ind))
23060 (when (zerop ind) (throw 'zerop t))))
23062 ;; Loop over all lines and add fixed-width markup everywhere
23063 ;; but in fixed-width lines.
23066 (while (< (point) end)
23068 ((org-at-heading-p)
23071 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23074 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23075 (let* ((element (org-element-at-point))
23076 (element-end (org-element-property :end element)))
23077 (if (eq (org-element-type element) 'fixed-width)
23078 (progn (goto-char element-end)
23079 (skip-chars-backward " \r\t\n")
23081 (let ((limit (min end element-end)))
23082 (while (< (point) limit)
23083 (org-move-to-column min-ind t)
23085 (forward-line))))))
23087 (org-move-to-column min-ind t)
23089 (forward-line)))))))
23090 (set-marker end nil))))
23095 ;; Org comments syntax is quite complex. It requires the entire line
23096 ;; to be just a comment. Also, even with the right syntax at the
23097 ;; beginning of line, some some elements (i.e. verse-block or
23098 ;; example-block) don't accept comments. Usual Emacs comment commands
23099 ;; cannot cope with those requirements. Therefore, Org replaces them.
23101 ;; Org still relies on `comment-dwim', but cannot trust
23102 ;; `comment-only-p'. So, `comment-region-function' and
23103 ;; `uncomment-region-function' both point
23104 ;; to`org-comment-or-uncomment-region'. Eventually,
23105 ;; `org-insert-comment' takes care of insertion of comments at the
23106 ;; beginning of line.
23108 ;; `org-setup-comments-handling' install comments related variables
23109 ;; during `org-mode' initialization.
23111 (defun org-setup-comments-handling ()
23113 (org-set-local 'comment-use-syntax nil)
23114 (org-set-local 'comment-start "# ")
23115 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23116 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
23117 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
23118 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
23120 (defun org-insert-comment ()
23121 "Insert an empty comment above current line.
23122 If the line is empty, insert comment at its beginning. When
23123 point is within a source block, comment according to the related
23125 (if (let ((element (org-element-at-point)))
23126 (and (eq (org-element-type element) 'src-block)
23128 (goto-char (org-element-property :post-affiliated element))
23129 (line-end-position))
23132 (goto-char (org-element-property :end element))
23133 (skip-chars-backward " \r\t\n")
23134 (line-beginning-position))
23136 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23137 (beginning-of-line)
23138 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23143 (defvar comment-empty-lines) ; From newcomment.el.
23144 (defun org-comment-or-uncomment-region (beg end &rest ignore)
23145 "Comment or uncomment each non-blank line in the region.
23146 Uncomment each non-blank line between BEG and END if it only
23147 contains commented lines. Otherwise, comment them. If region is
23148 strictly within a source block, use appropriate comment syntax."
23149 (if (let ((element (org-element-at-point)))
23150 (and (eq (org-element-type element) 'src-block)
23152 (goto-char (org-element-property :post-affiliated element))
23153 (line-end-position))
23155 (>= (save-excursion
23156 (goto-char (org-element-property :end element))
23157 (skip-chars-backward " \r\t\n")
23158 (line-beginning-position))
23160 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23163 (narrow-to-region (save-excursion (goto-char beg)
23164 (skip-chars-forward " \r\t\n" end)
23165 (line-beginning-position))
23166 (save-excursion (goto-char end)
23167 (skip-chars-backward " \r\t\n" beg)
23168 (line-end-position)))
23170 ;; UNCOMMENTP is non-nil when every non blank line between
23171 ;; BEG and END is a comment.
23173 (goto-char (point-min))
23174 (while (and (not (eobp))
23175 (let ((element (org-element-at-point)))
23176 (and (eq (org-element-type element) 'comment)
23177 (goto-char (min (point-max)
23178 (org-element-property
23179 :end element)))))))
23182 ;; Only blank lines and comments in region: uncomment it.
23184 (goto-char (point-min))
23185 (while (not (eobp))
23186 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23187 (replace-match "" nil nil nil 1))
23189 ;; Comment each line in region.
23190 (let ((min-indent (point-max)))
23191 ;; First find the minimum indentation across all lines.
23193 (goto-char (point-min))
23194 (while (and (not (eobp)) (not (zerop min-indent)))
23195 (unless (looking-at "[ \t]*$")
23196 (setq min-indent (min min-indent (current-indentation))))
23198 ;; Then loop over all lines.
23200 (goto-char (point-min))
23201 (while (not (eobp))
23202 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23203 ;; Don't get fooled by invisible text (e.g. link path)
23204 ;; when moving to column MIN-INDENT.
23205 (let ((buffer-invisibility-spec nil))
23206 (org-move-to-column min-indent t))
23207 (insert comment-start))
23208 (forward-line)))))))))
23210 (defun org-comment-dwim (arg)
23211 "Call `comment-dwim' within a source edit buffer if needed."
23213 (if (org-in-src-block-p)
23214 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23215 (call-interactively 'comment-dwim)))
23220 ;; This section contains tools to operate on timestamp objects, as
23221 ;; returned by, e.g. `org-element-context'.
23223 (defun org-timestamp-has-time-p (timestamp)
23224 "Non-nil when TIMESTAMP has a time specified."
23225 (org-element-property :hour-start timestamp))
23227 (defun org-timestamp-format (timestamp format &optional end utc)
23228 "Format a TIMESTAMP element into a string.
23230 FORMAT is a format specifier to be passed to
23231 `format-time-string'.
23233 When optional argument END is non-nil, use end of date-range or
23234 time-range, if possible.
23236 When optional argument UTC is non-nil, time will be expressed as
23238 (format-time-string
23240 (apply 'encode-time
23243 (lambda (prop) (or (org-element-property prop timestamp) 0))
23244 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23245 '(:minute-start :hour-start :day-start :month-start
23249 (defun org-timestamp-split-range (timestamp &optional end)
23250 "Extract a timestamp object from a date or time range.
23252 TIMESTAMP is a timestamp object. END, when non-nil, means extract
23253 the end of the range. Otherwise, extract its start.
23255 Return a new timestamp object sharing the same parent as
23257 (let ((type (org-element-property :type timestamp)))
23258 (if (memq type '(active inactive diary)) timestamp
23259 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
23261 (org-element-put-property
23262 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23263 ;; Copy start properties over end properties if END is
23264 ;; non-nil. Otherwise, copy end properties over `start' ones.
23265 (let ((p-alist '((:minute-start . :minute-end)
23266 (:hour-start . :hour-end)
23267 (:day-start . :day-end)
23268 (:month-start . :month-end)
23269 (:year-start . :year-end))))
23270 (dolist (p-cell p-alist)
23271 (org-element-put-property
23273 (funcall (if end 'car 'cdr) p-cell)
23274 (org-element-property
23275 (funcall (if end 'cdr 'car) p-cell) split-ts)))
23276 ;; Eventually refresh `:raw-value'.
23277 (org-element-put-property split-ts :raw-value nil)
23278 (org-element-put-property
23279 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23281 (defun org-timestamp-translate (timestamp &optional boundary)
23282 "Apply `org-translate-time' on a TIMESTAMP object.
23283 When optional argument BOUNDARY is non-nil, it is either the
23284 symbol `start' or `end'. In this case, only translate the
23285 starting or ending part of TIMESTAMP if it is a date or time
23286 range. Otherwise, translate both parts."
23287 (if (and (not boundary)
23288 (memq (org-element-property :type timestamp)
23289 '(active-range inactive-range)))
23291 (org-translate-time
23292 (org-element-property :raw-value
23293 (org-timestamp-split-range timestamp)))
23295 (org-translate-time
23296 (org-element-property :raw-value
23297 (org-timestamp-split-range timestamp t))))
23298 (org-translate-time
23299 (org-element-property
23301 (if (not boundary) timestamp
23302 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
23308 (defun org-reftex-citation ()
23309 "Use reftex-citation to insert a citation into the buffer.
23310 This looks for a line like
23312 #+BIBLIOGRAPHY: foo plain option:-d
23314 and derives from it that foo.bib is the bibliography file relevant
23315 for this document. It then installs the necessary environment for RefTeX
23316 to work in this buffer and calls `reftex-citation' to insert a citation
23319 Export of such citations to both LaTeX and HTML is handled by the contributed
23320 package ox-bibtex by Taru Karttunen."
23322 (let ((reftex-docstruct-symbol 'rds)
23323 (reftex-cite-format "\\cite{%l}")
23328 (let ((case-fold-search t)
23329 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23330 (if (not (save-excursion
23331 (or (re-search-forward re nil t)
23332 (re-search-backward re nil t))))
23333 (user-error "No bibliography defined in file")
23334 (setq bib (concat (match-string 1) ".bib")
23335 rds (list (list 'bib bib)))))))
23336 (call-interactively 'reftex-citation)))
23338 ;;;; Functions extending outline functionality
23340 (defun org-beginning-of-line (&optional arg)
23341 "Go to the beginning of the current line. If that is invisible, continue
23342 to a visible line beginning. This makes the function of C-a more intuitive.
23343 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23344 first attempt, and only move to after the tags when the cursor is already
23345 beyond the end of the headline."
23347 (let ((pos (point))
23348 (special (if (consp org-special-ctrl-a/e)
23349 (car org-special-ctrl-a/e)
23350 org-special-ctrl-a/e))
23351 deactivate-mark refpos)
23352 (if (org-bound-and-true-p visual-line-mode)
23353 (beginning-of-visual-line 1)
23354 (beginning-of-line 1))
23355 (if (and arg (fboundp 'move-beginning-of-line))
23356 (call-interactively 'move-beginning-of-line)
23360 (if (org-truely-invisible-p)
23361 (while (and (not (bobp)) (org-truely-invisible-p))
23363 (beginning-of-line 1))
23364 (forward-char 1))))
23367 ((and (looking-at org-complex-heading-regexp)
23368 (= (char-after (match-end 1)) ?\ ))
23369 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23373 (cond ((> pos refpos) refpos)
23374 ((= pos (point)) refpos)
23376 (cond ((> pos (point)) (point))
23377 ((not (eq last-command this-command)) (point))
23380 ;; Being at an item and not looking at an the item means point
23381 ;; was previously moved to beginning of a visual line, which
23382 ;; doesn't contain the item. Therefore, do nothing special,
23384 (when (looking-at org-list-full-item-re)
23385 ;; Set special position at first white space character after
23386 ;; bullet, and check-box, if any.
23387 (let ((after-bullet
23388 (let ((box (match-end 3)))
23389 (if (not box) (match-end 1)
23390 (let ((after (char-after box)))
23391 (if (and after (= after ? )) (1+ box) box))))))
23392 ;; Special case: Move point to special position when
23393 ;; currently after it or at beginning of line.
23395 (when (or (> pos after-bullet) (= (point) pos))
23396 (goto-char after-bullet))
23397 ;; Reversed case: Move point to special position when
23398 ;; point was already at beginning of line and command is
23400 (when (and (= (point) pos) (eq last-command this-command))
23401 (goto-char after-bullet))))))))
23403 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23404 (setq disable-point-adjustment
23405 (or (not (invisible-p (point)))
23406 (not (invisible-p (max (point-min) (1- (point))))))))
23408 (defun org-end-of-line (&optional arg)
23409 "Go to the end of the line.
23410 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23411 tags on the first attempt, and only move to after the tags when
23412 the cursor is already beyond the end of the headline."
23414 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23415 org-special-ctrl-a/e))
23416 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23417 'end-of-visual-line)
23418 ((fboundp 'move-end-of-line) 'move-end-of-line)
23421 (if (or (not special) arg) (call-interactively move-fun)
23422 (let* ((element (save-excursion (beginning-of-line)
23423 (org-element-at-point)))
23424 (type (org-element-type element)))
23426 ((memq type '(headline inlinetask))
23427 (let ((pos (point)))
23428 (beginning-of-line 1)
23429 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23431 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23432 (goto-char (match-beginning 1))
23433 (goto-char (match-end 0)))
23434 (if (or (< pos (match-end 0))
23435 (not (eq this-command last-command)))
23436 (goto-char (match-end 0))
23437 (goto-char (match-beginning 1))))
23438 (call-interactively move-fun))))
23439 ((outline-invisible-p (line-end-position))
23440 ;; If element is hidden, `move-end-of-line' would put point
23441 ;; after it. Use `end-of-line' to stay on current line.
23442 (call-interactively 'end-of-line))
23443 (t (call-interactively move-fun)))))
23444 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23445 (setq disable-point-adjustment
23446 (or (not (invisible-p (point)))
23447 (not (invisible-p (max (point-min) (1- (point))))))))
23449 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23450 (define-key org-mode-map "\C-e" 'org-end-of-line)
23452 (defun org-backward-sentence (&optional arg)
23453 "Go to beginning of sentence, or beginning of table field.
23454 This will call `backward-sentence' or `org-table-beginning-of-field',
23455 depending on context."
23458 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
23459 (t (call-interactively 'backward-sentence))))
23461 (defun org-forward-sentence (&optional arg)
23462 "Go to end of sentence, or end of table field.
23463 This will call `forward-sentence' or `org-table-end-of-field',
23464 depending on context."
23467 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
23468 (t (call-interactively 'forward-sentence))))
23470 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23471 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23473 (defun org-kill-line (&optional arg)
23474 "Kill line, to tags or end of line."
23477 ((or (not org-special-ctrl-k)
23479 (not (org-at-heading-p)))
23480 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23481 org-ctrl-k-protect-subtree)
23482 (if (or (eq org-ctrl-k-protect-subtree 'error)
23483 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23484 (user-error "C-k aborted as it would kill a hidden subtree")))
23485 (call-interactively
23486 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23487 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23488 (kill-region (point) (match-beginning 1))
23489 (org-set-tags nil t))
23490 (t (kill-region (point) (point-at-eol)))))
23492 (define-key org-mode-map "\C-k" 'org-kill-line)
23494 (defun org-yank (&optional arg)
23495 "Yank. If the kill is a subtree, treat it specially.
23496 This command will look at the current kill and check if is a single
23497 subtree, or a series of subtrees[1]. If it passes the test, and if the
23498 cursor is at the beginning of a line or after the stars of a currently
23499 empty headline, then the yank is handled specially. How exactly depends
23500 on the value of the following variables, both set by default.
23502 `org-yank-folded-subtrees'
23503 When set, the subtree(s) will be folded after insertion, but only
23504 if doing so would now swallow text after the yanked text.
23506 `org-yank-adjusted-subtrees'
23507 When set, the subtree will be promoted or demoted in order to
23508 fit into the local outline tree structure, which means that the
23509 level will be adjusted so that it becomes the smaller one of the
23510 two *visible* surrounding headings.
23512 Any prefix to this command will cause `yank' to be called directly with
23513 no special treatment. In particular, a simple \\[universal-argument] prefix \
23515 plainly yank the text as it is.
23517 \[1] The test checks if the first non-white line is a heading
23518 and if there are no other headings with fewer stars."
23520 (org-yank-generic 'yank arg))
23522 (defun org-yank-generic (command arg)
23523 "Perform some yank-like command.
23525 This function implements the behavior described in the `org-yank'
23526 documentation. However, it has been generalized to work for any
23527 interactive command with similar behavior."
23529 ;; pretend to be command COMMAND
23530 (setq this-command command)
23533 (call-interactively command)
23535 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23536 (and (org-kill-is-subtree-p)
23538 (and (looking-at "[ \t]*$")
23541 (buffer-substring (point-at-bol) (point)))))))
23544 ((and subtreep org-yank-folded-subtrees)
23545 (let ((beg (point))
23547 (if (and subtreep org-yank-adjusted-subtrees)
23548 (org-paste-subtree nil nil 'for-yank)
23549 (call-interactively command))
23553 (when (and (bolp) subtreep
23554 (not (setq swallowp
23555 (org-yank-folding-would-swallow-text beg end))))
23556 (org-with-limited-levels
23557 (or (looking-at org-outline-regexp)
23558 (re-search-forward org-outline-regexp-bol end t))
23559 (while (and (< (point) end) (looking-at org-outline-regexp))
23561 (org-cycle-show-empty-lines 'folded)
23562 (condition-case nil
23563 (outline-forward-same-level 1)
23564 (error (goto-char end))))))
23567 "Inserted text not folded because that would swallow text"))
23570 (skip-chars-forward " \t\n\r")
23571 (beginning-of-line 1)
23572 (push-mark beg 'nomsg)))
23573 ((and subtreep org-yank-adjusted-subtrees)
23574 (let ((beg (point-at-bol)))
23575 (org-paste-subtree nil nil 'for-yank)
23576 (push-mark beg 'nomsg)))
23578 (call-interactively command))))))
23580 (defun org-yank-folding-would-swallow-text (beg end)
23581 "Would hide-subtree at BEG swallow any text after END?"
23583 (org-with-limited-levels
23586 (when (or (looking-at org-outline-regexp)
23587 (re-search-forward org-outline-regexp-bol end t))
23588 (setq level (org-outline-level)))
23590 (skip-chars-forward " \t\r\n\v\f")
23592 (and (bolp) (looking-at org-outline-regexp)
23593 (<= (org-outline-level) level)))
23594 nil ; Nothing would be swallowed
23595 t))))) ; something would swallow
23597 (define-key org-mode-map "\C-y" 'org-yank)
23599 (defun org-truely-invisible-p ()
23600 "Check if point is at a character currently not visible.
23601 This version does not only check the character property, but also
23603 ;; Early versions of noutline don't have `outline-invisible-p'.
23604 (if (org-bound-and-true-p visible-mode)
23606 (outline-invisible-p)))
23608 (defun org-invisible-p2 ()
23609 "Check if point is at a character currently not visible."
23611 (if (and (eolp) (not (bobp))) (backward-char 1))
23612 ;; Early versions of noutline don't have `outline-invisible-p'.
23613 (outline-invisible-p)))
23615 (defun org-back-to-heading (&optional invisible-ok)
23616 "Call `outline-back-to-heading', but provide a better error message."
23617 (condition-case nil
23618 (outline-back-to-heading invisible-ok)
23619 (error (error "Before first headline at position %d in buffer %s"
23620 (point) (current-buffer)))))
23622 (defun org-before-first-heading-p ()
23623 "Before first heading?"
23626 (null (re-search-backward org-outline-regexp-bol nil t))))
23628 (defun org-at-heading-p (&optional ignored)
23629 (outline-on-heading-p t))
23630 ;; Compatibility alias with Org versions < 7.8.03
23631 (defalias 'org-on-heading-p 'org-at-heading-p)
23633 (defun org-in-commented-heading-p (&optional no-inheritance)
23634 "Non-nil if point is under a commented heading.
23635 This function also checks ancestors of the current headline,
23636 unless optional argument NO-INHERITANCE is non-nil."
23638 ((org-before-first-heading-p) nil)
23639 ((let ((headline (nth 4 (org-heading-components))))
23641 (let ((case-fold-search nil))
23642 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23644 (no-inheritance nil)
23646 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23648 (defun org-at-comment-p nil
23649 "Is cursor in a commented line?"
23652 (beginning-of-line)
23653 (looking-at "^[ \t]*# "))))
23655 (defun org-at-drawer-p nil
23656 "Is cursor at a drawer keyword?"
23658 (move-beginning-of-line 1)
23659 (looking-at org-drawer-regexp)))
23661 (defun org-at-block-p nil
23662 "Is cursor at a block keyword?"
23664 (move-beginning-of-line 1)
23665 (looking-at org-block-regexp)))
23667 (defun org-point-at-end-of-empty-headline ()
23668 "If point is at the end of an empty headline, return t, else nil.
23669 If the heading only contains a TODO keyword, it is still still considered
23671 (and (looking-at "[ \t]*$")
23672 (when org-todo-line-regexp
23674 (beginning-of-line 1)
23675 (let ((case-fold-search nil))
23676 (looking-at org-todo-line-regexp)
23677 (string= (match-string 3) ""))))))
23679 (defun org-at-heading-or-item-p ()
23680 (or (org-at-heading-p) (org-at-item-p)))
23682 (defun org-at-target-p ()
23683 (or (org-in-regexp org-radio-target-regexp)
23684 (org-in-regexp org-target-regexp)))
23685 ;; Compatibility alias with Org versions < 7.8.03
23686 (defalias 'org-on-target-p 'org-at-target-p)
23688 (defun org-up-heading-all (arg)
23689 "Move to the heading line of which the present line is a subheading.
23690 This function considers both visible and invisible heading lines.
23691 With argument, move up ARG levels."
23692 (if (fboundp 'outline-up-heading-all)
23693 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23694 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23696 (defun org-up-heading-safe ()
23697 "Move to the heading line of which the present line is a subheading.
23698 This version will not throw an error. It will return the level of the
23699 headline found, or nil if no higher level is found.
23701 Also, this function will be a lot faster than `outline-up-heading',
23702 because it relies on stars being the outline starters. This can really
23703 make a significant difference in outlines with very many siblings."
23704 (let (start-level re)
23705 (org-back-to-heading t)
23706 (setq start-level (funcall outline-level))
23707 (if (equal start-level 1)
23709 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23710 (if (re-search-backward re nil t)
23711 (funcall outline-level)))))
23713 (defun org-first-sibling-p ()
23714 "Is this heading the first child of its parents?"
23716 (let ((re org-outline-regexp-bol)
23718 (unless (org-at-heading-p t)
23719 (user-error "Not at a heading"))
23720 (setq level (funcall outline-level))
23722 (if (not (re-search-backward re nil t))
23724 (setq l (funcall outline-level))
23727 (defun org-goto-sibling (&optional previous)
23728 "Goto the next sibling, even if it is invisible.
23729 When PREVIOUS is set, go to the previous sibling instead. Returns t
23730 when a sibling was found. When none is found, return nil and don't
23732 (let ((fun (if previous 're-search-backward 're-search-forward))
23734 (re org-outline-regexp-bol)
23736 (when (ignore-errors (org-back-to-heading t))
23737 (setq level (funcall outline-level))
23739 (or previous (forward-char 1))
23740 (while (funcall fun re nil t)
23741 (setq l (funcall outline-level))
23742 (when (< l level) (goto-char pos) (throw 'exit nil))
23743 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23747 (defun org-show-siblings ()
23748 "Show all siblings of the current headline."
23750 (while (org-goto-sibling) (org-flag-heading nil)))
23752 (while (org-goto-sibling 'previous)
23753 (org-flag-heading nil))))
23755 (defun org-goto-first-child ()
23756 "Goto the first child, even if it is invisible.
23757 Return t when a child was found. Otherwise don't move point and
23759 (let (level (pos (point)) (re org-outline-regexp-bol))
23760 (when (ignore-errors (org-back-to-heading t))
23761 (setq level (outline-level))
23763 (if (and (re-search-forward re nil t) (> (outline-level) level))
23764 (progn (goto-char (match-beginning 0)) t)
23765 (goto-char pos) nil))))
23767 (defun org-show-hidden-entry ()
23768 "Show an entry where even the heading is hidden."
23772 (defun org-flag-heading (flag &optional entry)
23773 "Flag the current heading. FLAG non-nil means make invisible.
23774 When ENTRY is non-nil, show the entire entry."
23776 (org-back-to-heading t)
23777 ;; Check if we should show the entire entry
23782 (and (outline-next-heading)
23783 (org-flag-heading nil))))
23784 (outline-flag-region (max (point-min) (1- (point)))
23785 (save-excursion (outline-end-of-heading) (point))
23788 (defun org-get-next-sibling ()
23789 "Move to next heading of the same level, and return point.
23790 If there is no such heading, return nil.
23791 This is like outline-next-sibling, but invisible headings are ok."
23792 (let ((level (funcall outline-level)))
23793 (outline-next-heading)
23794 (while (and (not (eobp)) (> (funcall outline-level) level))
23795 (outline-next-heading))
23796 (if (or (eobp) (< (funcall outline-level) level))
23800 (defun org-get-last-sibling ()
23801 "Move to previous heading of the same level, and return point.
23802 If there is no such heading, return nil."
23803 (let ((opoint (point))
23804 (level (funcall outline-level)))
23805 (outline-previous-heading)
23806 (when (and (/= (point) opoint) (outline-on-heading-p t))
23807 (while (and (> (funcall outline-level) level)
23809 (outline-previous-heading))
23810 (if (< (funcall outline-level) level)
23814 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23815 "Goto to the end of a subtree."
23816 ;; This contains an exact copy of the original function, but it uses
23817 ;; `org-back-to-heading', to make it work also in invisible
23818 ;; trees. And is uses an invisible-ok argument.
23819 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23820 ;; Furthermore, when used inside Org, finding the end of a large subtree
23821 ;; with many children and grandchildren etc, this can be much faster
23822 ;; than the outline version.
23823 (org-back-to-heading invisible-ok)
23825 (level (funcall outline-level)))
23826 (if (and (derived-mode-p 'org-mode) (< level 1000))
23827 ;; A true heading (not a plain list item), in Org-mode
23828 ;; This means we can easily find the end by looking
23829 ;; only for the right number of stars. Using a regexp to do
23830 ;; this is so much faster than using a Lisp loop.
23831 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23833 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23834 ;; something else, do it the slow way
23835 (while (and (not (eobp))
23836 (or first (> (funcall outline-level) level)))
23838 (outline-next-heading)))
23840 (if (memq (preceding-char) '(?\n ?\^M))
23842 ;; Go to end of line before heading
23844 (if (memq (preceding-char) '(?\n ?\^M))
23845 ;; leave blank line before heading
23846 (forward-char -1))))))
23849 (defun org-end-of-meta-data-and-drawers ()
23850 "Jump to the first text after meta data and drawers in the current entry.
23851 This will move over empty lines, lines with planning time stamps,
23852 clocking lines, and drawers."
23853 (org-back-to-heading t)
23854 (let ((end (save-excursion (outline-next-heading) (point)))
23855 (re (concat "\\(" org-drawer-regexp "\\)"
23856 "\\|" "[ \t]*" org-keyword-time-regexp)))
23858 (while (re-search-forward re end t)
23859 (if (not (match-end 1))
23860 ;; empty or planning line
23862 ;; a drawer, find the end
23863 (re-search-forward "^[ \t]*:END:" end 'move)
23865 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23868 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23869 "Move forward to the ARG'th subheading at same level as this one.
23870 Stop at the first and last subheadings of a superior heading.
23871 Normally this only looks at visible headings, but when INVISIBLE-OK is
23872 non-nil it will also look at invisible ones."
23874 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23875 (if (and arg (< arg 0))
23876 (goto-char (point-min))
23877 (outline-next-heading))
23879 (let ((level (- (match-end 0) (match-beginning 0) 1))
23880 (f (if (and arg (< arg 0))
23881 're-search-backward
23882 're-search-forward))
23883 (count (if arg (abs arg) 1))
23885 (while (and (prog1 (> count 0)
23886 (forward-char (if (and arg (< arg 0)) -1 1)))
23887 (funcall f org-outline-regexp-bol nil 'move))
23888 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23889 (cond ((< l level) (setq count 0))
23893 (goto-char (line-beginning-position))
23894 (not (outline-invisible-p)))))
23895 (setq count (1- count))
23897 (setq result (point)))))))
23898 (goto-char result))
23899 (beginning-of-line 1)))
23901 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23902 "Move backward to the ARG'th subheading at same level as this one.
23903 Stop at the first and last subheadings of a superior heading."
23905 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23907 (defun org-next-block (arg &optional backward block-regexp)
23908 "Jump to the next block.
23909 With a prefix argument ARG, jump forward ARG many source blocks.
23910 When BACKWARD is non-nil, jump to the previous block.
23911 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23913 (let ((re (or block-regexp org-block-regexp))
23914 (re-search-fn (or (and backward 're-search-backward)
23915 're-search-forward)))
23916 (if (looking-at re) (forward-char 1))
23917 (condition-case nil
23918 (funcall re-search-fn re nil nil arg)
23919 (error (user-error "No %s code blocks"
23920 (if backward "previous" "further" ))))
23921 (goto-char (match-beginning 0)) (org-show-context)))
23923 (defun org-previous-block (arg &optional block-regexp)
23924 "Jump to the previous block.
23925 With a prefix argument ARG, jump backward ARG many source blocks.
23926 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23928 (org-next-block arg t block-regexp))
23930 (defun org-forward-paragraph ()
23931 "Move forward to beginning of next paragraph or equivalent.
23933 The function moves point to the beginning of the next visible
23934 structural element, which can be a paragraph, a table, a list
23935 item, etc. It also provides some special moves for convenience:
23937 - On an affiliated keyword, jump to the beginning of the
23939 - On an item or a footnote definition, move to the second
23940 element inside, if any.
23941 - On a table or a property drawer, jump after it.
23942 - On a verse or source block, stop after blank lines."
23944 (when (eobp) (user-error "Cannot move further down"))
23945 (let* ((deactivate-mark nil)
23946 (element (org-element-at-point))
23947 (type (org-element-type element))
23948 (post-affiliated (org-element-property :post-affiliated element))
23949 (contents-begin (org-element-property :contents-begin element))
23950 (contents-end (org-element-property :contents-end element))
23951 (end (let ((end (org-element-property :end element)) (parent element))
23952 (while (and (setq parent (org-element-property :parent parent))
23953 (= (org-element-property :contents-end parent) end))
23954 (setq end (org-element-property :end parent)))
23956 (cond ((not element)
23957 (skip-chars-forward " \r\t\n")
23958 (or (eobp) (beginning-of-line)))
23959 ;; On affiliated keywords, move to element's beginning.
23960 ((< (point) post-affiliated)
23961 (goto-char post-affiliated))
23962 ;; At a table row, move to the end of the table. Similarly,
23963 ;; at a node property, move to the end of the property
23965 ((memq type '(node-property table-row))
23966 (goto-char (org-element-property
23967 :end (org-element-property :parent element))))
23968 ((memq type '(property-drawer table)) (goto-char end))
23969 ;; Consider blank lines as separators in verse and source
23970 ;; blocks to ease editing.
23971 ((memq type '(src-block verse-block))
23972 (when (eq type 'src-block)
23974 (save-excursion (goto-char end)
23975 (skip-chars-backward " \r\t\n")
23976 (line-beginning-position))))
23977 (beginning-of-line)
23978 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23979 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23981 (skip-chars-forward " \r\t\n")
23982 (if (= (point) contents-end) (goto-char end)
23983 (beginning-of-line))))
23984 ;; With no contents, just skip element.
23985 ((not contents-begin) (goto-char end))
23986 ;; If contents are invisible, skip the element altogether.
23987 ((outline-invisible-p (line-end-position))
23990 (org-with-limited-levels (outline-next-visible-heading 1)))
23991 ;; At a plain list, make sure we move to the next item
23992 ;; instead of skipping the whole list.
23993 (plain-list (forward-char)
23994 (org-forward-paragraph))
23995 (otherwise (goto-char end))))
23996 ((>= (point) contents-end) (goto-char end))
23997 ((>= (point) contents-begin)
23998 ;; This can only happen on paragraphs and plain lists.
24000 (paragraph (goto-char end))
24001 ;; At a plain list, try to move to second element in
24002 ;; first item, if possible.
24003 (plain-list (end-of-line)
24004 (org-forward-paragraph))))
24005 ;; When contents start on the middle of a line (e.g. in
24006 ;; items and footnote definitions), try to reach first
24007 ;; element starting after current line.
24008 ((> (line-end-position) contents-begin)
24010 (org-forward-paragraph))
24011 (t (goto-char contents-begin)))))
24013 (defun org-backward-paragraph ()
24014 "Move backward to start of previous paragraph or equivalent.
24016 The function moves point to the beginning of the current
24017 structural element, which can be a paragraph, a table, a list
24018 item, etc., or to the beginning of the previous visible one if
24019 point is already there. It also provides some special moves for
24022 - On an affiliated keyword, jump to the first one.
24023 - On a table or a property drawer, move to its beginning.
24024 - On a verse or source block, stop before blank lines."
24026 (when (bobp) (user-error "Cannot move further up"))
24027 (let* ((deactivate-mark nil)
24028 (element (org-element-at-point))
24029 (type (org-element-type element))
24030 (contents-begin (org-element-property :contents-begin element))
24031 (contents-end (org-element-property :contents-end element))
24032 (post-affiliated (org-element-property :post-affiliated element))
24033 (begin (org-element-property :begin element)))
24035 ((not element) (goto-char (point-min)))
24038 (org-backward-paragraph))
24039 ((<= (point) post-affiliated) (goto-char begin))
24040 ((memq type '(node-property table-row))
24041 (goto-char (org-element-property
24042 :post-affiliated (org-element-property :parent element))))
24043 ((memq type '(property-drawer table)) (goto-char begin))
24044 ((memq type '(src-block verse-block))
24045 (when (eq type 'src-block)
24046 (setq contents-begin
24047 (save-excursion (goto-char begin) (forward-line) (point))))
24048 (if (= (point) contents-begin) (goto-char post-affiliated)
24049 ;; Inside a verse block, see blank lines as paragraph
24051 (let ((origin (point)))
24052 (skip-chars-backward " \r\t\n" contents-begin)
24053 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24054 (skip-chars-forward " \r\t\n" origin)
24055 (if (= (point) origin) (goto-char contents-begin)
24056 (beginning-of-line))))))
24057 ((not contents-begin) (goto-char (or post-affiliated begin)))
24058 ((eq type 'paragraph)
24059 (goto-char contents-begin)
24060 ;; When at first paragraph in an item or a footnote definition,
24061 ;; move directly to beginning of line.
24062 (let ((parent-contents
24063 (org-element-property
24064 :contents-begin (org-element-property :parent element))))
24065 (when (and parent-contents (= parent-contents contents-begin))
24066 (beginning-of-line))))
24067 ;; At the end of a greater element, move to the beginning of the
24068 ;; last element within.
24069 ((>= (point) contents-end)
24070 (goto-char (1- contents-end))
24071 (org-backward-paragraph))
24072 (t (goto-char (or post-affiliated begin))))
24073 ;; Ensure we never leave point invisible.
24074 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24076 (defun org-forward-element ()
24077 "Move forward by one element.
24078 Move to the next element at the same level, when possible."
24080 (cond ((eobp) (user-error "Cannot move further down"))
24081 ((org-with-limited-levels (org-at-heading-p))
24082 (let ((origin (point)))
24083 (goto-char (org-end-of-subtree nil t))
24084 (unless (org-with-limited-levels (org-at-heading-p))
24086 (user-error "Cannot move further down"))))
24088 (let* ((elem (org-element-at-point))
24089 (end (org-element-property :end elem))
24090 (parent (org-element-property :parent elem)))
24091 (cond ((and parent (= (org-element-property :contents-end parent) end))
24092 (goto-char (org-element-property :end parent)))
24093 ((integer-or-marker-p end) (goto-char end))
24094 (t (message "No element at point")))))))
24096 (defun org-backward-element ()
24097 "Move backward by one element.
24098 Move to the previous element at the same level, when possible."
24100 (cond ((bobp) (user-error "Cannot move further up"))
24101 ((org-with-limited-levels (org-at-heading-p))
24102 ;; At a headline, move to the previous one, if any, or stay
24104 (let ((origin (point)))
24105 (org-with-limited-levels (org-backward-heading-same-level 1))
24106 ;; When current headline has no sibling above, move to its
24108 (when (= (point) origin)
24109 (or (org-with-limited-levels (org-up-heading-safe))
24110 (progn (goto-char origin)
24111 (user-error "Cannot move further up"))))))
24113 (let* ((elem (org-element-at-point))
24114 (beg (org-element-property :begin elem)))
24116 ;; Move to beginning of current element if point isn't
24118 ((null beg) (message "No element at point"))
24119 ((/= (point) beg) (goto-char beg))
24121 (skip-chars-backward " \r\t\n")
24123 (let ((prev (org-element-at-point)))
24124 (goto-char (org-element-property :begin prev))
24125 (while (and (setq prev (org-element-property :parent prev))
24126 (<= (org-element-property :end prev) beg))
24127 (goto-char (org-element-property :begin prev)))))))))))
24129 (defun org-up-element ()
24130 "Move to upper element."
24132 (if (org-with-limited-levels (org-at-heading-p))
24133 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24134 (let* ((elem (org-element-at-point))
24135 (parent (org-element-property :parent elem)))
24136 (if parent (goto-char (org-element-property :begin parent))
24137 (if (org-with-limited-levels (org-before-first-heading-p))
24138 (user-error "No surrounding element")
24139 (org-with-limited-levels (org-back-to-heading)))))))
24141 (defvar org-element-greater-elements)
24142 (defun org-down-element ()
24143 "Move to inner element."
24145 (let ((element (org-element-at-point)))
24147 ((memq (org-element-type element) '(plain-list table))
24148 (goto-char (org-element-property :contents-begin element))
24150 ((memq (org-element-type element) org-element-greater-elements)
24151 ;; If contents are hidden, first disclose them.
24152 (when (outline-invisible-p (line-end-position)) (org-cycle))
24153 (goto-char (or (org-element-property :contents-begin element)
24154 (user-error "No content for this element"))))
24155 (t (user-error "No inner element")))))
24157 (defun org-drag-element-backward ()
24158 "Move backward element at point."
24160 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24161 (let* ((elem (org-element-at-point))
24164 (goto-char (org-element-property :begin elem))
24165 (skip-chars-backward " \r\t\n")
24167 (let* ((beg (org-element-property :begin elem))
24168 (prev (org-element-at-point))
24170 (while (and (setq up (org-element-property :parent up))
24171 (<= (org-element-property :end up) beg))
24174 ;; Error out if no previous element or previous element is
24175 ;; a parent of the current one.
24176 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24177 (user-error "Cannot drag element backward")
24178 (let ((pos (point)))
24179 (org-element-swap-A-B prev-elem elem)
24180 (goto-char (+ (org-element-property :begin prev-elem)
24181 (- pos (org-element-property :begin elem)))))))))
24183 (defun org-drag-element-forward ()
24184 "Move forward element at point."
24186 (let* ((pos (point))
24187 (elem (org-element-at-point)))
24188 (when (= (point-max) (org-element-property :end elem))
24189 (user-error "Cannot drag element forward"))
24190 (goto-char (org-element-property :end elem))
24191 (let ((next-elem (org-element-at-point)))
24192 (when (or (org-element-nested-p elem next-elem)
24193 (and (eq (org-element-type next-elem) 'headline)
24194 (not (eq (org-element-type elem) 'headline))))
24196 (user-error "Cannot drag element forward"))
24197 ;; Compute new position of point: it's shifted by NEXT-ELEM
24198 ;; body's length (without final blanks) and by the length of
24199 ;; blanks between ELEM and NEXT-ELEM.
24200 (let ((size-next (- (save-excursion
24201 (goto-char (org-element-property :end next-elem))
24202 (skip-chars-backward " \r\t\n")
24204 ;; Small correction if buffer doesn't end
24205 ;; with a newline character.
24206 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24207 (org-element-property :begin next-elem)))
24208 (size-blank (- (org-element-property :end elem)
24210 (goto-char (org-element-property :end elem))
24211 (skip-chars-backward " \r\t\n")
24214 (org-element-swap-A-B elem next-elem)
24215 (goto-char (+ pos size-next size-blank))))))
24217 (defun org-drag-line-forward (arg)
24218 "Drag the line at point ARG lines forward."
24220 (dotimes (n (abs arg))
24221 (let ((c (current-column)))
24224 (beginning-of-line 2)
24225 (transpose-lines 1)
24226 (beginning-of-line 0))
24227 (transpose-lines 1)
24228 (beginning-of-line -1))
24229 (org-move-to-column c))))
24231 (defun org-drag-line-backward (arg)
24232 "Drag the line at point ARG lines backward."
24234 (org-drag-line-forward (- arg)))
24236 (defun org-mark-element ()
24237 "Put point at beginning of this element, mark at end.
24239 Interactively, if this command is repeated or (in Transient Mark
24240 mode) if the mark is active, it marks the next element after the
24241 ones already marked."
24243 (let (deactivate-mark)
24244 (if (and (org-called-interactively-p 'any)
24245 (or (and (eq last-command this-command) (mark t))
24246 (and transient-mark-mode mark-active)))
24250 (goto-char (org-element-property :end (org-element-at-point)))))
24251 (let ((element (org-element-at-point)))
24253 (push-mark (org-element-property :end element) t t)
24254 (goto-char (org-element-property :begin element))))))
24256 (defun org-narrow-to-element ()
24257 "Narrow buffer to current element."
24259 (let ((elem (org-element-at-point)))
24261 ((eq (car elem) 'headline)
24263 (org-element-property :begin elem)
24264 (org-element-property :end elem)))
24265 ((memq (car elem) org-element-greater-elements)
24267 (org-element-property :contents-begin elem)
24268 (org-element-property :contents-end elem)))
24271 (org-element-property :begin elem)
24272 (org-element-property :end elem))))))
24274 (defun org-transpose-element ()
24275 "Transpose current and previous elements, keeping blank lines between.
24276 Point is moved after both elements."
24278 (org-skip-whitespace)
24279 (let ((end (org-element-property :end (org-element-at-point))))
24280 (org-drag-element-backward)
24283 (defun org-unindent-buffer ()
24284 "Un-indent the visible part of the buffer.
24285 Relative indentation (between items, inside blocks, etc.) isn't
24288 (unless (eq major-mode 'org-mode)
24289 (user-error "Cannot un-indent a buffer not in Org mode"))
24290 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
24291 unindent-tree ; For byte-compiler.
24297 (if (memq (org-element-type element) '(headline section))
24298 (funcall unindent-tree (org-element-contents element))
24302 (org-element-property :begin element)
24303 (org-element-property :end element))
24304 (org-do-remove-indentation)))))
24305 (reverse contents))))))
24306 (funcall unindent-tree (org-element-contents parse-tree))))
24308 (defun org-show-subtree ()
24309 "Show everything after this heading at deeper levels."
24311 (outline-flag-region
24314 (org-end-of-subtree t t))
24317 (defun org-show-entry ()
24318 "Show the body directly following this heading.
24319 Show the heading too, if it is currently invisible."
24323 (org-back-to-heading t)
24324 (outline-flag-region
24325 (max (point-min) (1- (point)))
24327 (if (re-search-forward
24328 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24329 (match-beginning 1)
24332 (org-cycle-hide-drawers 'children))))
24334 (defun org-make-options-regexp (kwds &optional extra)
24335 "Make a regular expression for keyword lines."
24338 (mapconcat 'regexp-quote kwds "\\|")
24339 (if extra (concat "\\|" extra))
24340 "\\):[ \t]*\\(.*\\)"))
24342 ;; Make isearch reveal the necessary context
24343 (defun org-isearch-end ()
24344 "Reveal context after isearch exits."
24345 (when isearch-success ; only if search was successful
24346 (if (featurep 'xemacs)
24347 ;; Under XEmacs, the hook is run in the correct place,
24348 ;; we directly show the context.
24349 (org-show-context 'isearch)
24350 ;; In Emacs the hook runs *before* restoring the overlays.
24351 ;; So we have to use a one-time post-command-hook to do this.
24352 ;; (Emacs 22 has a special variable, see function `org-mode')
24353 (unless (and (boundp 'isearch-mode-end-hook-quit)
24354 isearch-mode-end-hook-quit)
24355 ;; Only when the isearch was not quitted.
24356 (org-add-hook 'post-command-hook 'org-isearch-post-command
24357 'append 'local)))))
24359 (defun org-isearch-post-command ()
24360 "Remove self from hook, and show context."
24361 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24362 (org-show-context 'isearch))
24365 ;;;; Integration with and fixes for other packages
24369 (defvar org-imenu-markers nil
24370 "All markers currently used by Imenu.")
24371 (make-variable-buffer-local 'org-imenu-markers)
24373 (defun org-imenu-new-marker (&optional pos)
24374 "Return a new marker for use by Imenu, and remember the marker."
24375 (let ((m (make-marker)))
24376 (move-marker m (or pos (point)))
24377 (push m org-imenu-markers)
24380 (defun org-imenu-get-tree ()
24381 "Produce the index for Imenu."
24382 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24383 (setq org-imenu-markers nil)
24384 (let* ((n org-imenu-depth)
24385 (re (concat "^" (org-get-limited-outline-regexp)))
24386 (subs (make-vector (1+ n) nil))
24388 m level head0 head)
24392 (goto-char (point-max))
24393 (while (re-search-backward re nil t)
24394 (setq level (org-reduced-level (funcall outline-level)))
24395 (when (and (<= level n)
24396 (looking-at org-complex-heading-regexp)
24397 (setq head0 (org-match-string-no-properties 4)))
24398 (setq head (org-link-display-format head0)
24399 m (org-imenu-new-marker))
24400 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24401 (if (>= level last-level)
24402 (push (cons head m) (aref subs level))
24403 (push (cons head (aref subs (1+ level))) (aref subs level))
24404 (loop for i from (1+ level) to n do (aset subs i nil)))
24405 (setq last-level level)))))
24408 (eval-after-load "imenu"
24410 (add-hook 'imenu-after-jump-hook
24412 (if (derived-mode-p 'org-mode)
24413 (org-show-context 'org-goto))))))
24415 (defun org-link-display-format (link)
24416 "Replace a link with its the description.
24417 If there is no description, use the link target."
24419 (if (string-match org-bracket-link-analytic-regexp link)
24420 (replace-match (if (match-end 5)
24421 (match-string 5 link)
24422 (concat (match-string 1 link)
24423 (match-string 3 link)))
24427 (defun org-toggle-link-display ()
24428 "Toggle the literal or descriptive display of links."
24430 (if org-descriptive-links
24431 (progn (org-remove-from-invisibility-spec '(org-link))
24432 (org-restart-font-lock)
24433 (setq org-descriptive-links nil))
24434 (progn (add-to-invisibility-spec '(org-link))
24435 (org-restart-font-lock)
24436 (setq org-descriptive-links t))))
24438 ;; Speedbar support
24440 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24441 "Overlay marking the agenda restriction line in speedbar.")
24442 (overlay-put org-speedbar-restriction-lock-overlay
24443 'face 'org-agenda-restriction-lock)
24444 (overlay-put org-speedbar-restriction-lock-overlay
24445 'help-echo "Agendas are currently limited to this item.")
24446 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24448 (defun org-speedbar-set-agenda-restriction ()
24449 "Restrict future agenda commands to the location at point in speedbar.
24450 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24452 (require 'org-agenda)
24453 (let (p m tp np dir txt)
24455 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24457 (setq m (get-text-property p 'org-imenu-marker))
24458 (with-current-buffer (marker-buffer m)
24460 (org-agenda-set-restriction-lock 'subtree)))
24461 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24462 'speedbar-function 'speedbar-find-file))
24463 (setq tp (previous-single-property-change
24464 (1+ p) 'speedbar-function)
24465 np (next-single-property-change
24466 tp 'speedbar-function)
24467 dir (speedbar-line-directory)
24468 txt (buffer-substring-no-properties (or tp (point-min))
24469 (or np (point-max))))
24470 (with-current-buffer (find-file-noselect
24471 (let ((default-directory dir))
24472 (expand-file-name txt)))
24473 (unless (derived-mode-p 'org-mode)
24474 (user-error "Cannot restrict to non-Org-mode file"))
24475 (org-agenda-set-restriction-lock 'file)))
24476 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24477 (move-overlay org-speedbar-restriction-lock-overlay
24478 (point-at-bol) (point-at-eol))
24479 (setq current-prefix-arg nil)
24480 (org-agenda-maybe-redo)))
24482 (defvar speedbar-file-key-map)
24483 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24484 (eval-after-load "speedbar"
24486 (speedbar-add-supported-extension ".org")
24487 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24488 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24489 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24490 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24491 (add-hook 'speedbar-visiting-tag-hook
24492 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24494 ;;; Fixes and Hacks for problems with other packages
24496 (defun org-mode-flyspell-verify ()
24497 "Function used for `flyspell-generic-check-word-predicate'."
24498 (if (org-at-heading-p)
24499 ;; At a headline or an inlinetask, check title only. This is
24500 ;; faster than relying on `org-element-at-point'.
24501 (and (save-excursion (beginning-of-line)
24502 (and (let ((case-fold-search t))
24503 (not (looking-at "\\*+ END[ \t]*$")))
24504 (looking-at org-complex-heading-regexp)))
24505 (match-beginning 4)
24506 (>= (point) (match-beginning 4))
24507 (or (not (match-beginning 5))
24508 (< (point) (match-beginning 5))))
24509 (let* ((element (org-element-at-point))
24510 (post-affiliated (org-element-property :post-affiliated element))
24513 ;; Non-nil if checks can be done for object at point.
24515 (let ((object (save-excursion
24516 (when (org-looking-at-p "\\>") (backward-char))
24517 (org-element-context element))))
24518 (case (org-element-type object)
24519 ;; Prevent checks in links due to keybinding conflict
24521 ((code entity export-snippet inline-babel-call
24522 inline-src-block line-break latex-fragment link macro
24523 statistics-cookie target timestamp verbatim)
24525 (footnote-reference
24526 ;; Only in inline footnotes, within the definition.
24527 (and (eq (org-element-property :type object) 'inline)
24529 (goto-char (org-element-property :begin object))
24530 (search-forward ":" nil t 2))
24532 (otherwise t)))))))
24534 ;; Ignore checks in all affiliated keywords but captions.
24535 ((< (point) post-affiliated)
24536 (and (save-excursion
24537 (beginning-of-line)
24538 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24539 (> (point) (match-end 0))
24540 (funcall object-check)))
24541 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24542 ((and org-log-into-drawer
24543 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24545 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24546 (setq parent (org-element-property :parent parent)))
24548 (eq (compare-strings
24550 (org-element-property :drawer-name parent) nil nil t)
24554 (case (org-element-type element)
24555 ((comment quote-section) t)
24557 ;; Allow checks between block markers, not on them.
24558 (and (> (line-beginning-position) post-affiliated)
24561 (skip-chars-forward " \r\t\n")
24562 (< (point) (org-element-property :end element)))))
24563 ;; Arbitrary list of keywords where checks are meaningful.
24564 ;; Make sure point is on the value part of the element.
24566 (and (member (org-element-property :key element)
24567 '("DESCRIPTION" "TITLE"))
24569 (beginning-of-line) (search-forward ":") (point))
24571 ;; Check is globally allowed in paragraphs verse blocks and
24572 ;; table rows (after affiliated keywords) but some objects
24573 ;; must not be affected.
24574 ((paragraph table-row verse-block)
24575 (and (>= (point) (org-element-property :contents-begin element))
24576 (< (point) (org-element-property :contents-end element))
24577 (funcall object-check)))))))))
24578 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24580 (defun org-remove-flyspell-overlays-in (beg end)
24581 "Remove flyspell overlays in region."
24582 (and (org-bound-and-true-p flyspell-mode)
24583 (fboundp 'flyspell-delete-region-overlays)
24584 (flyspell-delete-region-overlays beg end)))
24586 (defvar flyspell-delayed-commands)
24587 (eval-after-load "flyspell"
24588 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24590 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24591 (eval-after-load "bookmark"
24592 '(if (boundp 'bookmark-after-jump-hook)
24593 ;; We can use the hook
24594 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24595 ;; Hook not available, use advice
24596 (defadvice bookmark-jump (after org-make-visible activate)
24597 "Make the position visible."
24598 (org-bookmark-jump-unhide))))
24600 ;; Make sure saveplace shows the location if it was hidden
24601 (eval-after-load "saveplace"
24602 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24603 "Make the position visible."
24604 (org-bookmark-jump-unhide)))
24606 ;; Make sure ecb shows the location if it was hidden
24607 (eval-after-load "ecb"
24608 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24609 "Make hierarchy visible when jumping into location from ECB tree buffer."
24610 (if (derived-mode-p 'org-mode)
24611 (org-show-context))))
24613 (defun org-bookmark-jump-unhide ()
24614 "Unhide the current position, to show the bookmark location."
24615 (and (derived-mode-p 'org-mode)
24616 (or (outline-invisible-p)
24617 (save-excursion (goto-char (max (point-min) (1- (point))))
24618 (outline-invisible-p)))
24619 (org-show-context 'bookmark-jump)))
24621 (defun org-mark-jump-unhide ()
24622 "Make the point visible with `org-show-context' after jumping to the mark."
24623 (when (and (derived-mode-p 'org-mode)
24624 (outline-invisible-p))
24625 (org-show-context 'mark-goto)))
24627 (eval-after-load "simple"
24628 '(defadvice pop-to-mark-command (after org-make-visible activate)
24629 "Make the point visible with `org-show-context'."
24630 (org-mark-jump-unhide)))
24632 (eval-after-load "simple"
24633 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24634 "Make the point visible with `org-show-context'."
24635 (org-mark-jump-unhide)))
24637 (eval-after-load "simple"
24638 '(defadvice pop-global-mark (after org-make-visible activate)
24639 "Make the point visible with `org-show-context'."
24640 (org-mark-jump-unhide)))
24642 ;; Make session.el ignore our circular variable
24643 (defvar session-globals-exclude)
24644 (eval-after-load "session"
24645 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24651 (run-hooks 'org-load-hook)
24653 ;;; org.el ends here